From 15a742e63ff2b76a38d005d4ea9e4fc5fddeb540 Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Mon, 21 Feb 2022 16:00:15 +0800 Subject: [PATCH 01/12] wps-privateSharedServices --- internal/services/signalr/client/client.go | 17 +- ...web_pubsub_shared_private_link_resource.go | 75 +++++++ ...ubsub_shared_private_link_resource_test.go | 128 ++++++++++++ internal/services/signalr/registration.go | 11 +- internal/services/signalr/resourceids.go | 2 + ..._pubsub_shared_private_link_resource_id.go | 23 +++ ...ub_shared_private_link_resource_id_test.go | 88 +++++++++ ...web_pubsub_shared_private_link_resource.go | 187 ++++++++++++++++++ 8 files changed, 520 insertions(+), 11 deletions(-) create mode 100644 internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go create mode 100644 internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go create mode 100644 internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id.go create mode 100644 internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go create mode 100644 internal/services/signalr/web_pubsub_shared_private_link_resource.go diff --git a/internal/services/signalr/client/client.go b/internal/services/signalr/client/client.go index 9b39383375b7..df5ff5f6daf4 100644 --- a/internal/services/signalr/client/client.go +++ b/internal/services/signalr/client/client.go @@ -7,9 +7,10 @@ import ( ) type Client struct { - SignalRClient *signalr.SignalRClient - WebPubsubClient *webpubsub.Client - WebPubsubHubsClient *webpubsub.HubsClient + SignalRClient *signalr.SignalRClient + WebPubsubClient *webpubsub.Client + WebPubsubHubsClient *webpubsub.HubsClient + WebPubsubSharedPrivateLinkResourceClient *webpubsub.SharedPrivateLinkResourcesClient } func NewClient(o *common.ClientOptions) *Client { @@ -22,9 +23,13 @@ func NewClient(o *common.ClientOptions) *Client { webpubsubHubsClient := webpubsub.NewHubsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&webpubsubHubsClient.Client, o.ResourceManagerAuthorizer) + webPubsubSharedPrivateLinkResourceClient := webpubsub.NewSharedPrivateLinkResourcesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&webPubsubSharedPrivateLinkResourceClient.Client, o.ResourceManagerAuthorizer) + return &Client{ - SignalRClient: &signalRClient, - WebPubsubClient: &webpubsubClient, - WebPubsubHubsClient: &webpubsubHubsClient, + SignalRClient: &signalRClient, + WebPubsubClient: &webpubsubClient, + WebPubsubHubsClient: &webpubsubHubsClient, + WebPubsubSharedPrivateLinkResourceClient: &webPubsubSharedPrivateLinkResourceClient, } } diff --git a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go new file mode 100644 index 000000000000..357c54980146 --- /dev/null +++ b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go @@ -0,0 +1,75 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +type WebPubsubSharedPrivateLinkResourceId struct { + SubscriptionId string + ResourceGroup string + WebPubSubName string + SharedPrivateLinkResourceName string +} + +func NewWebPubsubSharedPrivateLinkResourceID(subscriptionId, resourceGroup, webPubSubName, sharedPrivateLinkResourceName string) WebPubsubSharedPrivateLinkResourceId { + return WebPubsubSharedPrivateLinkResourceId{ + SubscriptionId: subscriptionId, + ResourceGroup: resourceGroup, + WebPubSubName: webPubSubName, + SharedPrivateLinkResourceName: sharedPrivateLinkResourceName, + } +} + +func (id WebPubsubSharedPrivateLinkResourceId) String() string { + segments := []string{ + fmt.Sprintf("Shared Private Link Resource Name %q", id.SharedPrivateLinkResourceName), + fmt.Sprintf("Web Pub Sub Name %q", id.WebPubSubName), + fmt.Sprintf("Resource Group %q", id.ResourceGroup), + } + segmentsStr := strings.Join(segments, " / ") + return fmt.Sprintf("%s: (%s)", "Web Pubsub Shared Private Link Resource", segmentsStr) +} + +func (id WebPubsubSharedPrivateLinkResourceId) ID() string { + fmtString := "/subscriptions/%s/resourcegroups/%s/providers/Microsoft.SignalRService/WebPubSub/%s/sharedPrivateLinkResources/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.WebPubSubName, id.SharedPrivateLinkResourceName) +} + +// WebPubsubSharedPrivateLinkResourceID parses a WebPubsubSharedPrivateLinkResource ID into an WebPubsubSharedPrivateLinkResourceId struct +func WebPubsubSharedPrivateLinkResourceID(input string) (*WebPubsubSharedPrivateLinkResourceId, error) { + id, err := resourceids.ParseAzureResourceID(input) + if err != nil { + return nil, err + } + + resourceId := WebPubsubSharedPrivateLinkResourceId{ + SubscriptionId: id.SubscriptionID, + ResourceGroup: id.ResourceGroup, + } + + if resourceId.SubscriptionId == "" { + return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + } + + if resourceId.ResourceGroup == "" { + return nil, fmt.Errorf("ID was missing the 'resourcegroups' element") + } + + if resourceId.WebPubSubName, err = id.PopSegment("WebPubSub"); err != nil { + return nil, err + } + if resourceId.SharedPrivateLinkResourceName, err = id.PopSegment("sharedPrivateLinkResources"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &resourceId, nil +} diff --git a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go new file mode 100644 index 000000000000..63d8ed343f17 --- /dev/null +++ b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go @@ -0,0 +1,128 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "testing" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.Id = WebPubsubSharedPrivateLinkResourceId{} + +func TestWebPubsubSharedPrivateLinkResourceIDFormatter(t *testing.T) { + actual := NewWebPubsubSharedPrivateLinkResourceID("12345678-1234-9876-4563-123456789012", "resGroup1", "Webpubsub1", "resource1").ID() + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1" + if actual != expected { + t.Fatalf("Expected %q but got %q", expected, actual) + } +} + +func TestWebPubsubSharedPrivateLinkResourceID(t *testing.T) { + testData := []struct { + Input string + Error bool + Expected *WebPubsubSharedPrivateLinkResourceId + }{ + + { + // empty + Input: "", + Error: true, + }, + + { + // missing SubscriptionId + Input: "/", + Error: true, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Error: true, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Error: true, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/", + Error: true, + }, + + { + // missing WebPubSubName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/", + Error: true, + }, + + { + // missing value for WebPubSubName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Error: true, + }, + + { + // missing SharedPrivateLinkResourceName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", + Error: true, + }, + + { + // missing value for SharedPrivateLinkResourceName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/", + Error: true, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", + Expected: &WebPubsubSharedPrivateLinkResourceId{ + SubscriptionId: "12345678-1234-9876-4563-123456789012", + ResourceGroup: "resGroup1", + WebPubSubName: "Webpubsub1", + SharedPrivateLinkResourceName: "resource1", + }, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.SIGNALRSERVICE/WEBPUBSUB/WEBPUBSUB1/SHAREDPRIVATELINKRESOURCES/RESOURCE1", + Error: true, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Input) + + actual, err := WebPubsubSharedPrivateLinkResourceID(v.Input) + if err != nil { + if v.Error { + continue + } + + t.Fatalf("Expect a value but got an error: %s", err) + } + if v.Error { + t.Fatal("Expect an error but didn't get one") + } + + if actual.SubscriptionId != v.Expected.SubscriptionId { + t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) + } + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) + } + if actual.WebPubSubName != v.Expected.WebPubSubName { + t.Fatalf("Expected %q but got %q for WebPubSubName", v.Expected.WebPubSubName, actual.WebPubSubName) + } + if actual.SharedPrivateLinkResourceName != v.Expected.SharedPrivateLinkResourceName { + t.Fatalf("Expected %q but got %q for SharedPrivateLinkResourceName", v.Expected.SharedPrivateLinkResourceName, actual.SharedPrivateLinkResourceName) + } + } +} diff --git a/internal/services/signalr/registration.go b/internal/services/signalr/registration.go index 66258f075dec..857c6e7d9b15 100644 --- a/internal/services/signalr/registration.go +++ b/internal/services/signalr/registration.go @@ -37,10 +37,11 @@ func (r Registration) SupportedDataSources() map[string]*pluginsdk.Resource { // SupportedResources returns the supported Resources supported by this Service func (r Registration) SupportedResources() map[string]*pluginsdk.Resource { return map[string]*pluginsdk.Resource{ - "azurerm_signalr_service": resourceArmSignalRService(), - "azurerm_signalr_service_network_acl": resourceArmSignalRServiceNetworkACL(), - "azurerm_web_pubsub": resourceWebPubSub(), - "azurerm_web_pubsub_hub": resourceWebPubsubHub(), - "azurerm_web_pubsub_network_acl": resourceWebpubsubNetworkACL(), + "azurerm_signalr_service": resourceArmSignalRService(), + "azurerm_signalr_service_network_acl": resourceArmSignalRServiceNetworkACL(), + "azurerm_web_pubsub": resourceWebPubSub(), + "azurerm_web_pubsub_hub": resourceWebPubsubHub(), + "azurerm_web_pubsub_network_acl": resourceWebpubsubNetworkACL(), + "azurerm_web_pubsub_shared_private_link_resource": resourceWebpubsubSharedPrivateLinkService(), } } diff --git a/internal/services/signalr/resourceids.go b/internal/services/signalr/resourceids.go index fde5e518291a..a5953e9466b2 100644 --- a/internal/services/signalr/resourceids.go +++ b/internal/services/signalr/resourceids.go @@ -2,3 +2,5 @@ package signalr //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubHub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/hubs/Webpubsubhub1 +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubSharedPrivateLinkResource -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1 + diff --git a/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id.go b/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id.go new file mode 100644 index 000000000000..c3254d22ec0a --- /dev/null +++ b/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id.go @@ -0,0 +1,23 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + + "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/parse" +) + +func WebPubsubSharedPrivateLinkResourceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := parse.WebPubsubSharedPrivateLinkResourceID(v); err != nil { + errors = append(errors, err) + } + + return +} diff --git a/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go b/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go new file mode 100644 index 000000000000..4c79cbf3a923 --- /dev/null +++ b/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go @@ -0,0 +1,88 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import "testing" + +func TestWebPubsubSharedPrivateLinkResourceID(t *testing.T) { + cases := []struct { + Input string + Valid bool + }{ + + { + // empty + Input: "", + Valid: false, + }, + + { + // missing SubscriptionId + Input: "/", + Valid: false, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Valid: false, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Valid: false, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/", + Valid: false, + }, + + { + // missing WebPubSubName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/", + Valid: false, + }, + + { + // missing value for WebPubSubName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Valid: false, + }, + + { + // missing SharedPrivateLinkResourceName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", + Valid: false, + }, + + { + // missing value for SharedPrivateLinkResourceName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/", + Valid: false, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", + Valid: true, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.SIGNALRSERVICE/WEBPUBSUB/WEBPUBSUB1/SHAREDPRIVATELINKRESOURCES/RESOURCE1", + Valid: false, + }, + } + for _, tc := range cases { + t.Logf("[DEBUG] Testing Value %s", tc.Input) + _, errors := WebPubsubSharedPrivateLinkResourceID(tc.Input, "test") + valid := len(errors) == 0 + + if tc.Valid != valid { + t.Fatalf("Expected %t but got %t", tc.Valid, valid) + } + } +} diff --git a/internal/services/signalr/web_pubsub_shared_private_link_resource.go b/internal/services/signalr/web_pubsub_shared_private_link_resource.go new file mode 100644 index 000000000000..dc9ac60de424 --- /dev/null +++ b/internal/services/signalr/web_pubsub_shared_private_link_resource.go @@ -0,0 +1,187 @@ +package signalr + +import ( + "fmt" + "time" + + "github.com/Azure/azure-sdk-for-go/services/webpubsub/mgmt/2021-10-01/webpubsub" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/validate" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +func resourceWebpubsubSharedPrivateLinkService() *pluginsdk.Resource { + return &pluginsdk.Resource{ + Create: resourceWebPubsubSharedPrivateLinkServiceCreateUpdate, + Read: resourceWebPubsubSharedPrivateLinkServiceRead, + Update: resourceWebPubsubSharedPrivateLinkServiceCreateUpdate, + Delete: resourceWebPubsubSharedPrivateLinkServiceDelete, + + Timeouts: &pluginsdk.ResourceTimeout{ + Create: pluginsdk.DefaultTimeout(30 * time.Minute), + Read: pluginsdk.DefaultTimeout(5 * time.Minute), + Update: pluginsdk.DefaultTimeout(30 * time.Minute), + Delete: pluginsdk.DefaultTimeout(30 * time.Minute), + }, + + Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { + _, err := parse.WebPubsubSharedPrivateLinkResourceID(id) + return err + }), + + Schema: map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "web_pubsub_id": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.WebPubsubID, + }, + + "group_id": { + Type: pluginsdk.TypeString, + Required: true, + //todo check the validation func: which value is supported? + ValidateFunc: validation.StringIsNotEmpty, + }, + + "private_link_resource_id": { + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: azure.ValidateResourceID, + }, + + "request_message": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "status": { + Type: pluginsdk.TypeString, + Computed: true, + }, + }, + } +} + +func resourceWebPubsubSharedPrivateLinkServiceCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).SignalR.WebPubsubSharedPrivateLinkResourceClient + subscriptionId := meta.(*clients.Client).Account.SubscriptionId + ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + webPubsubID, err := parse.WebPubsubID(d.Get("web_pubsub_id").(string)) + if err != nil { + return fmt.Errorf("parsing ID of %q: %+v", webPubsubID, err) + } + + id := parse.NewWebPubsubSharedPrivateLinkResourceID(subscriptionId, webPubsubID.ResourceGroup, webPubsubID.WebPubSubName, d.Get("name").(string)) + + if d.IsNewResource() { + existing, err := client.Get(ctx, id.SharedPrivateLinkResourceName, id.ResourceGroup, id.WebPubSubName) + if err != nil { + if !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("checking for existing %q: %+v", id, err) + } + } + if !utils.ResponseWasNotFound(existing.Response) { + return tf.ImportAsExistsError("azurerm_web_pubsub_shared_private_link_resource", id.ID()) + } + } + + parameters := webpubsub.SharedPrivateLinkResource{ + SharedPrivateLinkResourceProperties: &webpubsub.SharedPrivateLinkResourceProperties{ + GroupID: utils.String(d.Get("group_id").(string)), + PrivateLinkResourceID: utils.String(d.Get("private_link_resource_id").(string)), + }, + } + + requestMessage := d.Get("request_message").(string) + if requestMessage != "" { + parameters.SharedPrivateLinkResourceProperties.RequestMessage = utils.String(requestMessage) + } + + if _, err := client.CreateOrUpdate(ctx, id.SharedPrivateLinkResourceName, parameters, id.ResourceGroup, id.WebPubSubName); err != nil { + return err + } + + d.SetId(id.ID()) + + return resourceWebPubsubSharedPrivateLinkServiceRead(d, meta) +} +func resourceWebPubsubSharedPrivateLinkServiceRead(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).SignalR.WebPubsubSharedPrivateLinkResourceClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.WebPubsubSharedPrivateLinkResourceID(d.Id()) + if err != nil { + return err + } + + resp, err := client.Get(ctx, id.SharedPrivateLinkResourceName, id.ResourceGroup, id.WebPubSubName) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + d.SetId("") + return fmt.Errorf("%q was not found", id) + } + return fmt.Errorf("making request on %q: %+v", id, err) + } + + d.Set("name", resp.Name) + d.Set("web_pubsub_id", parse.NewWebPubsubID(id.SubscriptionId, id.ResourceGroup, id.WebPubSubName).ID()) + + if props := resp.SharedPrivateLinkResourceProperties; props != nil { + if props.GroupID != nil { + d.Set("group_id", props.GroupID) + } + + if props.PrivateLinkResourceID != nil { + d.Set("private_link_resource_id", props.PrivateLinkResourceID) + } + + if props.RequestMessage != nil { + d.Set("request_message", props.RequestMessage) + } + + d.Set("status", props.Status) + } + + return nil +} +func resourceWebPubsubSharedPrivateLinkServiceDelete(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).SignalR.WebPubsubSharedPrivateLinkResourceClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.WebPubsubSharedPrivateLinkResourceID(d.Id()) + if err != nil { + return err + } + + future, err := client.Delete(ctx, id.SharedPrivateLinkResourceName, id.ResourceGroup, id.WebPubSubName) + if err != nil { + return fmt.Errorf("deleting %q: %+v", id, err) + } + + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + if !response.WasNotFound(future.Response()) { + return fmt.Errorf("waiting for deleting %q: %+v", id, err) + } + } + return nil +} From a5d1b5df64745bb78017c1e8eeaa2517fabd8ce2 Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Mon, 21 Feb 2022 17:37:16 +0800 Subject: [PATCH 02/12] add private link data source --- internal/services/signalr/client/client.go | 5 + internal/services/signalr/registration.go | 5 +- ...bsub_private_linked_service_data_source.go | 95 +++++++++++++++++++ 3 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 internal/services/signalr/web_pubsub_private_linked_service_data_source.go diff --git a/internal/services/signalr/client/client.go b/internal/services/signalr/client/client.go index df5ff5f6daf4..21bd031df0f1 100644 --- a/internal/services/signalr/client/client.go +++ b/internal/services/signalr/client/client.go @@ -11,6 +11,7 @@ type Client struct { WebPubsubClient *webpubsub.Client WebPubsubHubsClient *webpubsub.HubsClient WebPubsubSharedPrivateLinkResourceClient *webpubsub.SharedPrivateLinkResourcesClient + WebPubsubPrivateLinkedResourceClient *webpubsub.PrivateLinkResourcesClient } func NewClient(o *common.ClientOptions) *Client { @@ -26,10 +27,14 @@ func NewClient(o *common.ClientOptions) *Client { webPubsubSharedPrivateLinkResourceClient := webpubsub.NewSharedPrivateLinkResourcesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&webPubsubSharedPrivateLinkResourceClient.Client, o.ResourceManagerAuthorizer) + webPubsubPrivateLinkResourceClient := webpubsub.NewPrivateLinkResourcesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&webPubsubPrivateLinkResourceClient.Client, o.ResourceManagerAuthorizer) + return &Client{ SignalRClient: &signalRClient, WebPubsubClient: &webpubsubClient, WebPubsubHubsClient: &webpubsubHubsClient, WebPubsubSharedPrivateLinkResourceClient: &webPubsubSharedPrivateLinkResourceClient, + WebPubsubPrivateLinkedResourceClient: &webPubsubPrivateLinkResourceClient, } } diff --git a/internal/services/signalr/registration.go b/internal/services/signalr/registration.go index 857c6e7d9b15..e4305c866c0e 100644 --- a/internal/services/signalr/registration.go +++ b/internal/services/signalr/registration.go @@ -29,8 +29,9 @@ func (r Registration) WebsiteCategories() []string { // SupportedDataSources returns the supported Data Sources supported by this Service func (r Registration) SupportedDataSources() map[string]*pluginsdk.Resource { return map[string]*pluginsdk.Resource{ - "azurerm_signalr_service": dataSourceArmSignalRService(), - "azurerm_web_pubsub": dataSourceWebPubsub(), + "azurerm_signalr_service": dataSourceArmSignalRService(), + "azurerm_web_pubsub": dataSourceWebPubsub(), + "azurerm_web_pubsub_private_link_resource": dataSourceWebPubsubPrivateLinkResource(), } } diff --git a/internal/services/signalr/web_pubsub_private_linked_service_data_source.go b/internal/services/signalr/web_pubsub_private_linked_service_data_source.go new file mode 100644 index 000000000000..88c70dbeba46 --- /dev/null +++ b/internal/services/signalr/web_pubsub_private_linked_service_data_source.go @@ -0,0 +1,95 @@ +package signalr + +import ( + "fmt" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/parse" + "time" + + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/validate" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" +) + +func dataSourceWebPubsubPrivateLinkResource() *pluginsdk.Resource { + return &pluginsdk.Resource{ + Read: dataSourceWebPubsubPrivateLinkResourceRead, + + Timeouts: &pluginsdk.ResourceTimeout{ + Read: pluginsdk.DefaultTimeout(5 * time.Minute), + }, + + Schema: map[string]*pluginsdk.Schema{ + "web_pubsub_id": { + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validate.WebPubsubID, + }, + + "shared_private_link_resource_types": { + Type: pluginsdk.TypeSet, + Computed: true, + Elem: &pluginsdk.Resource{ + Schema: map[string]*pluginsdk.Schema{ + "group_id": { + Type: pluginsdk.TypeString, + Computed: true, + }, + + "description": { + Type: pluginsdk.TypeString, + Computed: true, + }, + }, + }, + }, + }, + } +} + +func dataSourceWebPubsubPrivateLinkResourceRead(d *pluginsdk.ResourceData, meta interface{}) error { + privateLinkResourceClient := meta.(*clients.Client).SignalR.WebPubsubPrivateLinkedResourceClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + webPubsubID, err := parse.WebPubsubID(d.Get("web_pubsub_id").(string)) + if err != nil { + return fmt.Errorf("parsing ID of %q: %+v", webPubsubID, err) + } + + resourceList, err := privateLinkResourceClient.List(ctx, webPubsubID.ResourceGroup, webPubsubID.WebPubSubName) + if err != nil { + return fmt.Errorf("retrieving Private Link Resource for Resource %s: %+v", webPubsubID, err) + } + + if resourceList.Values() == nil { + return fmt.Errorf("retrieving Private Link Resource for Resource %s: `resource value` was nil", webPubsubID) + } + + d.SetId(webPubsubID.ID()) + val := resourceList.Values() + + linkTypeList := make([]interface{}, 0) + + for _, v := range val { + if v.PrivateLinkResourceProperties != nil && v.PrivateLinkResourceProperties.ShareablePrivateLinkResourceTypes != nil { + for _, resource := range *v.PrivateLinkResourceProperties.ShareablePrivateLinkResourceTypes { + item := make(map[string]interface{}) + if props := resource.Properties; props != nil { + if props.GroupID != nil { + item["group_id"] = props.GroupID + } + if props.Description != nil { + item["description"] = props.Description + } + } + linkTypeList = append(linkTypeList, item) + } + } + } + + if err := d.Set("shared_private_link_resource_types", linkTypeList); err != nil { + return fmt.Errorf("setting `shared_private_link_resource_types` error: %+v", err) + } + return nil +} From d01043fdc579254065be4182549edb7c44200dca Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 22 Feb 2022 12:59:36 +0800 Subject: [PATCH 03/12] private link --- ...bsub_private_linked_service_data_source.go | 2 +- ...private_linked_service_data_source_test.go | 51 +++++++ ...web_pubsub_shared_private_link_resource.go | 4 +- ...ubsub_shared_private_link_resource_test.go | 136 ++++++++++++++++++ 4 files changed, 190 insertions(+), 3 deletions(-) create mode 100644 internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go create mode 100644 internal/services/signalr/web_pubsub_shared_private_link_resource_test.go diff --git a/internal/services/signalr/web_pubsub_private_linked_service_data_source.go b/internal/services/signalr/web_pubsub_private_linked_service_data_source.go index 88c70dbeba46..23157a969537 100644 --- a/internal/services/signalr/web_pubsub_private_linked_service_data_source.go +++ b/internal/services/signalr/web_pubsub_private_linked_service_data_source.go @@ -2,10 +2,10 @@ package signalr import ( "fmt" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/parse" "time" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" diff --git a/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go b/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go new file mode 100644 index 000000000000..d2b4bac6ea1c --- /dev/null +++ b/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go @@ -0,0 +1,51 @@ +package signalr_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" +) + +type WebPubsubPrivateLinkedServiceDataSource struct {} + +func TestAccWebPubsubPrivateLinkedService_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_web_pubsub_private_link_resource", "test") + r := WebPubsubPrivateLinkedServiceDataSource{} + + data.DataSourceTest(t, []acceptance.TestStep{ + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).Key("shared_private_link_resource_types.#").Exists(), + check.That(data.ResourceName).Key("id").Exists(), + ), + }, + }) +} + +func (r WebPubsubPrivateLinkedServiceDataSource) basic(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_web_pubsub" "test" { + name = "acctestWebPubsub-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku = "Standard_S1" + capacity = 1 +} + +data "azurerm_web_pubsub_private_link_resource" "test" { + web_pubsub_id = azurerm_web_pubsub.test.id +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} diff --git a/internal/services/signalr/web_pubsub_shared_private_link_resource.go b/internal/services/signalr/web_pubsub_shared_private_link_resource.go index dc9ac60de424..b9d2ddfc63a5 100644 --- a/internal/services/signalr/web_pubsub_shared_private_link_resource.go +++ b/internal/services/signalr/web_pubsub_shared_private_link_resource.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + networkValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" @@ -54,8 +55,7 @@ func resourceWebpubsubSharedPrivateLinkService() *pluginsdk.Resource { "group_id": { Type: pluginsdk.TypeString, Required: true, - //todo check the validation func: which value is supported? - ValidateFunc: validation.StringIsNotEmpty, + ValidateFunc: networkValidate.PrivateLinkSubResourceName, }, "private_link_resource_id": { diff --git a/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go b/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go new file mode 100644 index 000000000000..92c8eaeee73e --- /dev/null +++ b/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go @@ -0,0 +1,136 @@ +package signalr_test + +import ( + "context" + "fmt" + "testing" + + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type WebPubsubSharedPrivateLinkResource struct{} + +func TestAccWebPubsubSharedPrivateLinkResource_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_web_pubsub_shared_private_link_resource", "test") + r := WebPubsubSharedPrivateLinkResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r)), + }, + data.ImportStep(), + }) +} + +func TestAccWebPubsubSharedPrivateLinkResource_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_web_pubsub_shared_private_link_resource", "test") + r := WebPubsubSharedPrivateLinkResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.RequiresImportErrorStep(r.requiresImport), + }) +} +func (r WebPubsubSharedPrivateLinkResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { + id, err := parse.WebPubsubSharedPrivateLinkResourceID(state.ID) + if err != nil { + return nil, err + } + + resp, err := clients.SignalR.WebPubsubSharedPrivateLinkResourceClient.Get(ctx, id.SharedPrivateLinkResourceName, id.ResourceGroup, id.WebPubSubName) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return utils.Bool(false), nil + } + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) + } + + return utils.Bool(true), nil +} + +func (r WebPubsubSharedPrivateLinkResource) basic(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_key_vault" "test" { + name = "vault%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + tenant_id = data.azurerm_client_config.current.tenant_id + sku_name = "standard" + soft_delete_retention_days = 7 + + access_policy { + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = data.azurerm_client_config.current.object_id + + certificate_permissions = [ + "managecontacts", + ] + + key_permissions = [ + "create", + ] + + secret_permissions = [ + "set", + ] + } +} + +resource "azurerm_web_pubsub_shared_private_link_resource" "test" { + name = "acctest-%d" + web_pubsub_id = azurerm_web_pubsub.test.id + group_id = "sites" + private_link_resource_id = azurerm_key_vault.test.id +} +`, template, data.RandomInteger, data.RandomInteger) +} + +func (r WebPubsubSharedPrivateLinkResource) requiresImport(data acceptance.TestData) string { + config := r.basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_web_pubsub_shared_private_link_resource" "import" { + name = azurerm_web_pubsub_shared_private_link_resource.test.name + web_pubsub_id = azurerm_web_pubsub_shared_private_link_resource.test.web_pubsub_id + group_id = azurerm_web_pubsub_shared_private_link_resource.group_id + private_link_resource_id = azurerm_web_pubsub_shared_private_link_resource.private_link_resource_id +} +`, config) +} + +func (r WebPubsubSharedPrivateLinkResource) template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-wps-%d" + location = "%s" +} + +resource "azurerm_web_pubsub" "test" { + name = "acctestWebPubsub-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku = "Standard_S1" + capacity = 1 +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} From f09cfaca67cb2ebe55a613e1aba9b81e5a0dc7ca Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 22 Feb 2022 16:42:19 +0800 Subject: [PATCH 04/12] private link --- internal/services/signalr/resourceids.go | 1 - ...bsub_private_linked_service_data_source.go | 4 +- ...private_linked_service_data_source_test.go | 4 +- ...web_pubsub_shared_private_link_resource.go | 16 +-- ...ubsub_shared_private_link_resource_test.go | 18 +-- ...pubsub_private_link_resource.html.markdown | 58 ++++++++++ ...b_pubsub_shared_private_link.html.markdown | 105 ++++++++++++++++++ 7 files changed, 185 insertions(+), 21 deletions(-) create mode 100644 website/docs/d/web_pubsub_private_link_resource.html.markdown create mode 100644 website/docs/r/web_pubsub_shared_private_link.html.markdown diff --git a/internal/services/signalr/resourceids.go b/internal/services/signalr/resourceids.go index a5953e9466b2..5c1d1add1a90 100644 --- a/internal/services/signalr/resourceids.go +++ b/internal/services/signalr/resourceids.go @@ -3,4 +3,3 @@ package signalr //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubHub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/hubs/Webpubsubhub1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubSharedPrivateLinkResource -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1 - diff --git a/internal/services/signalr/web_pubsub_private_linked_service_data_source.go b/internal/services/signalr/web_pubsub_private_linked_service_data_source.go index 23157a969537..48cac17565bb 100644 --- a/internal/services/signalr/web_pubsub_private_linked_service_data_source.go +++ b/internal/services/signalr/web_pubsub_private_linked_service_data_source.go @@ -31,7 +31,7 @@ func dataSourceWebPubsubPrivateLinkResource() *pluginsdk.Resource { Computed: true, Elem: &pluginsdk.Resource{ Schema: map[string]*pluginsdk.Schema{ - "group_id": { + "subresource_name": { Type: pluginsdk.TypeString, Computed: true, }, @@ -77,7 +77,7 @@ func dataSourceWebPubsubPrivateLinkResourceRead(d *pluginsdk.ResourceData, meta item := make(map[string]interface{}) if props := resource.Properties; props != nil { if props.GroupID != nil { - item["group_id"] = props.GroupID + item["subresource_name"] = props.GroupID } if props.Description != nil { item["description"] = props.Description diff --git a/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go b/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go index d2b4bac6ea1c..130af81390c1 100644 --- a/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go +++ b/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" ) -type WebPubsubPrivateLinkedServiceDataSource struct {} +type WebPubsubPrivateLinkedServiceDataSource struct{} func TestAccWebPubsubPrivateLinkedService_basic(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_web_pubsub_private_link_resource", "test") @@ -20,7 +20,7 @@ func TestAccWebPubsubPrivateLinkedService_basic(t *testing.T) { Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).Key("shared_private_link_resource_types.#").Exists(), check.That(data.ResourceName).Key("id").Exists(), - ), + ), }, }) } diff --git a/internal/services/signalr/web_pubsub_shared_private_link_resource.go b/internal/services/signalr/web_pubsub_shared_private_link_resource.go index b9d2ddfc63a5..8cfdb88fadbd 100644 --- a/internal/services/signalr/web_pubsub_shared_private_link_resource.go +++ b/internal/services/signalr/web_pubsub_shared_private_link_resource.go @@ -52,13 +52,13 @@ func resourceWebpubsubSharedPrivateLinkService() *pluginsdk.Resource { ValidateFunc: validate.WebPubsubID, }, - "group_id": { - Type: pluginsdk.TypeString, - Required: true, + "subresource_name": { + Type: pluginsdk.TypeString, + Required: true, ValidateFunc: networkValidate.PrivateLinkSubResourceName, }, - "private_link_resource_id": { + "target_resource_id": { Type: pluginsdk.TypeString, Required: true, ValidateFunc: azure.ValidateResourceID, @@ -105,8 +105,8 @@ func resourceWebPubsubSharedPrivateLinkServiceCreateUpdate(d *pluginsdk.Resource parameters := webpubsub.SharedPrivateLinkResource{ SharedPrivateLinkResourceProperties: &webpubsub.SharedPrivateLinkResourceProperties{ - GroupID: utils.String(d.Get("group_id").(string)), - PrivateLinkResourceID: utils.String(d.Get("private_link_resource_id").(string)), + GroupID: utils.String(d.Get("subresource_name").(string)), + PrivateLinkResourceID: utils.String(d.Get("target_resource_id").(string)), }, } @@ -147,11 +147,11 @@ func resourceWebPubsubSharedPrivateLinkServiceRead(d *pluginsdk.ResourceData, me if props := resp.SharedPrivateLinkResourceProperties; props != nil { if props.GroupID != nil { - d.Set("group_id", props.GroupID) + d.Set("subresource_name", props.GroupID) } if props.PrivateLinkResourceID != nil { - d.Set("private_link_resource_id", props.PrivateLinkResourceID) + d.Set("target_resource_id", props.PrivateLinkResourceID) } if props.RequestMessage != nil { diff --git a/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go b/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go index 92c8eaeee73e..2c14c1bea544 100644 --- a/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go +++ b/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go @@ -92,10 +92,10 @@ resource "azurerm_key_vault" "test" { } resource "azurerm_web_pubsub_shared_private_link_resource" "test" { - name = "acctest-%d" - web_pubsub_id = azurerm_web_pubsub.test.id - group_id = "sites" - private_link_resource_id = azurerm_key_vault.test.id + name = "acctest-%d" + web_pubsub_id = azurerm_web_pubsub.test.id + subresource_name = "vault" + target_resource_id = azurerm_key_vault.test.id } `, template, data.RandomInteger, data.RandomInteger) } @@ -106,10 +106,10 @@ func (r WebPubsubSharedPrivateLinkResource) requiresImport(data acceptance.TestD %s resource "azurerm_web_pubsub_shared_private_link_resource" "import" { - name = azurerm_web_pubsub_shared_private_link_resource.test.name - web_pubsub_id = azurerm_web_pubsub_shared_private_link_resource.test.web_pubsub_id - group_id = azurerm_web_pubsub_shared_private_link_resource.group_id - private_link_resource_id = azurerm_web_pubsub_shared_private_link_resource.private_link_resource_id + name = azurerm_web_pubsub_shared_private_link_resource.test.name + web_pubsub_id = azurerm_web_pubsub_shared_private_link_resource.test.web_pubsub_id + subresource_name = azurerm_web_pubsub_shared_private_link_resource.test.subresource_name + target_resource_id = azurerm_web_pubsub_shared_private_link_resource.test.target_resource_id } `, config) } @@ -120,6 +120,8 @@ provider "azurerm" { features {} } +data "azurerm_client_config" "current" {} + resource "azurerm_resource_group" "test" { name = "acctestRG-wps-%d" location = "%s" diff --git a/website/docs/d/web_pubsub_private_link_resource.html.markdown b/website/docs/d/web_pubsub_private_link_resource.html.markdown new file mode 100644 index 000000000000..14ea73638315 --- /dev/null +++ b/website/docs/d/web_pubsub_private_link_resource.html.markdown @@ -0,0 +1,58 @@ +--- +subcategory: "Web PubSub" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_web_pubsub_private_link_resource" +description: |- + Gets information about the Private Link Resource supported by the Web Pubsub Resource. +--- + +# Data Source: azurerm_web_pubsub_private_link_resource + +Use this data source to access information about the Private Link Resource supported by the Web Pubsub Resource. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_web_pubsub" "test" { + name = "acctestWebPubsub-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku = "Standard_S1" + capacity = 1 +} + +data "azurerm_web_pubsub_private_link_resource" "test" { + web_pubsub_id = azurerm_web_pubsub.test.id +} +``` + +## Argument Reference + +* `web_pubsub_id` - The ID of an existing Web Pubsub Resource which Private Link Resource should be retrieved for. + +## Attributes Reference + +* `id` - The ID of the existing Web Pubsub Resource which supports the retrieved Private Link Resource list. + +* `shared_private_link_resource_types` - A `shared_private_link_resource_types` block as defined below. + +--- + +A `shared_private_link_resource_types` block exports the following: + +* `subresource_name` - The name for the resource that has been onboarded to private link service. + +* `description` - The description of the resource type that has been onboarded to private link service. + + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `read` - (Defaults to 5 minutes) Used when retrieving the Private Link Resource. + diff --git a/website/docs/r/web_pubsub_shared_private_link.html.markdown b/website/docs/r/web_pubsub_shared_private_link.html.markdown new file mode 100644 index 000000000000..62e258526792 --- /dev/null +++ b/website/docs/r/web_pubsub_shared_private_link.html.markdown @@ -0,0 +1,105 @@ +--- +subcategory: "Web PubSub" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_web_pubsub_shared_private_link_resource" +description: |- + Manages the Shared Private Link Resource for a Web Pubsub service. +--- + +# azurerm_web_pubsub_shared_private_link_resource + +Manages the Shared Private Link Resource for a Web Pubsub service. + +## Example Usage + +```hcl +data "azurerm_client_config" "current" {} + +resource "azurerm_resource_group" "test" { + name = "terraform-webpubsub" + location = "east us" +} + +resource "azurerm_key_vault" "test" { + name = "examplekeyvault" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + tenant_id = data.azurerm_client_config.current.tenant_id + sku_name = "standard" + soft_delete_retention_days = 7 + + access_policy { + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = data.azurerm_client_config.current.object_id + + certificate_permissions = [ + "managecontacts", + ] + + key_permissions = [ + "create", + ] + + secret_permissions = [ + "set", + ] + } +} + +resource "azurerm_web_pubsub" "test" { + name = "tfex-webpubsub" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku = "Standard_S1" + capacity = 1 +} + +resource "azurerm_web_pubsub_shared_private_link_resource" "test" { + name = "tfex-webpubsub-splr" + web_pubsub_id = azurerm_web_pubsub.test.id + group_id = "sites" + private_link_resource_id = azurerm_key_vault.test.id +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the Web Pubsub Shared Private Link Resource. Changing this forces a new resource to be created. + +* `web_pubsub_id` - (Required) Specify the id of the Web Pubsub. Changing this forces a new resource to be created. + +* `subresource_name` - (Required) Specifies the sub resource name which the Web Pubsub Private Endpoint is able to connect to. Changing this forces a new resource to be created. + +-> **NOTE:** The available sub resource can be retrieved by using `azurerm_web_pubsub_private_link_resource` data source. + +* `target_resource_id` - (Required) The ID of the Shared Private Link Enabled Remote Resource which this Web Pubsub Private Endpoint should be connected to. Changing this forces a new resource to be created. + +-> **NOTE:** The sub resource name should match with the type of the target resource id that's being specified. + +* `request_message` - (Optional) The request message for requesting approval of the Shared Private Link Enabled Remote Resource. + +## Attributes Reference: + +The following attributes are exported: + +* `id` - The ID of the Web Pubsub Shared Private Link resource. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Web Pubsub Shared Private Link Resource. +* `update` - (Defaults to 30 minutes) Used when updating the Web Pubsub Shared Private Link Resource. +* `read` - (Defaults to 5 minutes) Used when retrieving the Web Pubsub Shared Private Link Resource. +* `delete` - (Defaults to 30 minutes) Used when deleting the Web Pubsub Shared Private Link Resource. + +## Import + +Web Pubsub Shared Private Link Resource can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_web_pubsub_hub.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.SignalRService/webPubsub/webpubsub1/sharedPrivateLinkResources/resource1 +``` + From dd8e725345dbdff966570b87782aa4a887f258fb Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 22 Feb 2022 20:21:56 +0800 Subject: [PATCH 05/12] private link resource --- ...private_linked_service_data_source_test.go | 2 +- ...web_pubsub_shared_private_link_resource.go | 2 ++ ...pubsub_private_link_resource.html.markdown | 8 ++--- ...b_pubsub_shared_private_link.html.markdown | 36 ++++++++++--------- 4 files changed, 26 insertions(+), 22 deletions(-) diff --git a/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go b/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go index 130af81390c1..c8fec361f7e6 100644 --- a/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go +++ b/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go @@ -11,7 +11,7 @@ import ( type WebPubsubPrivateLinkedServiceDataSource struct{} func TestAccWebPubsubPrivateLinkedService_basic(t *testing.T) { - data := acceptance.BuildTestData(t, "azurerm_web_pubsub_private_link_resource", "test") + data := acceptance.BuildTestData(t, "data.azurerm_web_pubsub_private_link_resource", "test") r := WebPubsubPrivateLinkedServiceDataSource{} data.DataSourceTest(t, []acceptance.TestStep{ diff --git a/internal/services/signalr/web_pubsub_shared_private_link_resource.go b/internal/services/signalr/web_pubsub_shared_private_link_resource.go index 8cfdb88fadbd..85e78ee08f08 100644 --- a/internal/services/signalr/web_pubsub_shared_private_link_resource.go +++ b/internal/services/signalr/web_pubsub_shared_private_link_resource.go @@ -55,12 +55,14 @@ func resourceWebpubsubSharedPrivateLinkService() *pluginsdk.Resource { "subresource_name": { Type: pluginsdk.TypeString, Required: true, + ForceNew: true, ValidateFunc: networkValidate.PrivateLinkSubResourceName, }, "target_resource_id": { Type: pluginsdk.TypeString, Required: true, + ForceNew: true, ValidateFunc: azure.ValidateResourceID, }, diff --git a/website/docs/d/web_pubsub_private_link_resource.html.markdown b/website/docs/d/web_pubsub_private_link_resource.html.markdown index 14ea73638315..0553874e3fc6 100644 --- a/website/docs/d/web_pubsub_private_link_resource.html.markdown +++ b/website/docs/d/web_pubsub_private_link_resource.html.markdown @@ -14,12 +14,12 @@ Use this data source to access information about the Private Link Resource suppo ```hcl resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" + name = "terraform-webpubsub" + location = "east us" } resource "azurerm_web_pubsub" "test" { - name = "acctestWebPubsub-%d" + name = "tfex-webpubsub" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name sku = "Standard_S1" @@ -37,7 +37,7 @@ data "azurerm_web_pubsub_private_link_resource" "test" { ## Attributes Reference -* `id` - The ID of the existing Web Pubsub Resource which supports the retrieved Private Link Resource list. +* `id` - The ID of an existing Web Pubsub Resource which supports the retrieved Private Link Resource list. * `shared_private_link_resource_types` - A `shared_private_link_resource_types` block as defined below. diff --git a/website/docs/r/web_pubsub_shared_private_link.html.markdown b/website/docs/r/web_pubsub_shared_private_link.html.markdown index 62e258526792..f5b0d5862f69 100644 --- a/website/docs/r/web_pubsub_shared_private_link.html.markdown +++ b/website/docs/r/web_pubsub_shared_private_link.html.markdown @@ -15,15 +15,15 @@ Manages the Shared Private Link Resource for a Web Pubsub service. ```hcl data "azurerm_client_config" "current" {} -resource "azurerm_resource_group" "test" { +resource "azurerm_resource_group" "example" { name = "terraform-webpubsub" location = "east us" } -resource "azurerm_key_vault" "test" { +resource "azurerm_key_vault" "example" { name = "examplekeyvault" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name tenant_id = data.azurerm_client_config.current.tenant_id sku_name = "standard" soft_delete_retention_days = 7 @@ -46,19 +46,19 @@ resource "azurerm_key_vault" "test" { } } -resource "azurerm_web_pubsub" "test" { +resource "azurerm_web_pubsub" "example" { name = "tfex-webpubsub" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name sku = "Standard_S1" capacity = 1 } -resource "azurerm_web_pubsub_shared_private_link_resource" "test" { - name = "tfex-webpubsub-splr" - web_pubsub_id = azurerm_web_pubsub.test.id - group_id = "sites" - private_link_resource_id = azurerm_key_vault.test.id +resource "azurerm_web_pubsub_shared_private_link_resource" "example" { + name = "tfex-webpubsub-splr" + web_pubsub_id = azurerm_web_pubsub.example.id + subresource_name = "vault" + target_resource_id = azurerm_key_vault.example.id } ``` @@ -66,19 +66,19 @@ resource "azurerm_web_pubsub_shared_private_link_resource" "test" { The following arguments are supported: -* `name` - (Required) The name of the Web Pubsub Shared Private Link Resource. Changing this forces a new resource to be created. +* `name` - (Required) Specify the name of the Web Pubsub Shared Private Link Resource. Changing this forces a new resource to be created. * `web_pubsub_id` - (Required) Specify the id of the Web Pubsub. Changing this forces a new resource to be created. -* `subresource_name` - (Required) Specifies the sub resource name which the Web Pubsub Private Endpoint is able to connect to. Changing this forces a new resource to be created. +* `subresource_name` - (Required) Specify the sub resource name which the Web Pubsub Private Endpoint is able to connect to. Changing this forces a new resource to be created. -> **NOTE:** The available sub resource can be retrieved by using `azurerm_web_pubsub_private_link_resource` data source. -* `target_resource_id` - (Required) The ID of the Shared Private Link Enabled Remote Resource which this Web Pubsub Private Endpoint should be connected to. Changing this forces a new resource to be created. +* `target_resource_id` - (Required) Specify the ID of the Shared Private Link Enabled Remote Resource which this Web Pubsub Private Endpoint should be connected to. Changing this forces a new resource to be created. -> **NOTE:** The sub resource name should match with the type of the target resource id that's being specified. -* `request_message` - (Optional) The request message for requesting approval of the Shared Private Link Enabled Remote Resource. +* `request_message` - (Optional) Specify the request message for requesting approval of the Shared Private Link Enabled Remote Resource. ## Attributes Reference: @@ -86,6 +86,8 @@ The following attributes are exported: * `id` - The ID of the Web Pubsub Shared Private Link resource. +* `status` - The status of a private endpoint connection. Possible values are Pending, Approved, Rejected or Disconnected. + ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: @@ -100,6 +102,6 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d Web Pubsub Shared Private Link Resource can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_web_pubsub_hub.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.SignalRService/webPubsub/webpubsub1/sharedPrivateLinkResources/resource1 +terraform import azurerm_web_pubsub_shared_private_link_resource.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.SignalRService/webPubsub/webpubsub1/sharedPrivateLinkResources/resource1 ``` From 880f286ab826bbde9446a8fbfcdd082b728336b1 Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 22 Feb 2022 22:43:03 +0800 Subject: [PATCH 06/12] fmt --- .../signalr/web_pubsub_private_linked_service_data_source.go | 2 +- .../web_pubsub_private_linked_service_data_source_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/services/signalr/web_pubsub_private_linked_service_data_source.go b/internal/services/signalr/web_pubsub_private_linked_service_data_source.go index 48cac17565bb..76c24b41d575 100644 --- a/internal/services/signalr/web_pubsub_private_linked_service_data_source.go +++ b/internal/services/signalr/web_pubsub_private_linked_service_data_source.go @@ -27,7 +27,7 @@ func dataSourceWebPubsubPrivateLinkResource() *pluginsdk.Resource { }, "shared_private_link_resource_types": { - Type: pluginsdk.TypeSet, + Type: pluginsdk.TypeList, Computed: true, Elem: &pluginsdk.Resource{ Schema: map[string]*pluginsdk.Schema{ diff --git a/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go b/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go index c8fec361f7e6..c9a50191d816 100644 --- a/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go +++ b/internal/services/signalr/web_pubsub_private_linked_service_data_source_test.go @@ -45,7 +45,7 @@ resource "azurerm_web_pubsub" "test" { } data "azurerm_web_pubsub_private_link_resource" "test" { - web_pubsub_id = azurerm_web_pubsub.test.id + web_pubsub_id = azurerm_web_pubsub.test.id } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } From ea3aead77abc9a09c37e9bf382c40d7f798a3500 Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 5 Jul 2022 16:09:56 +0800 Subject: [PATCH 07/12] =?UTF-8?q?=C3=A2=C2=80update=20resource=20id=20per?= =?UTF-8?q?=20comment?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/services/signalr/resourceids.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/services/signalr/resourceids.go b/internal/services/signalr/resourceids.go index 5c1d1add1a90..c0a0850c9c54 100644 --- a/internal/services/signalr/resourceids.go +++ b/internal/services/signalr/resourceids.go @@ -2,4 +2,4 @@ package signalr //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubHub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/hubs/Webpubsubhub1 -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubSharedPrivateLinkResource -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1 +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubSharedPrivateLinkResource -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1 From 3f7a0757880b5bd679c6085a7718d016fbb67dc0 Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 5 Jul 2022 16:42:06 +0800 Subject: [PATCH 08/12] update ids --- .../web_pubsub_shared_private_link_resource.go | 4 ++-- ...web_pubsub_shared_private_link_resource_test.go | 14 +++++++------- ..._pubsub_shared_private_link_resource_id_test.go | 12 ++++++------ 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go index 357c54980146..4d7958bc9372 100644 --- a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go +++ b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go @@ -36,7 +36,7 @@ func (id WebPubsubSharedPrivateLinkResourceId) String() string { } func (id WebPubsubSharedPrivateLinkResourceId) ID() string { - fmtString := "/subscriptions/%s/resourcegroups/%s/providers/Microsoft.SignalRService/WebPubSub/%s/sharedPrivateLinkResources/%s" + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/WebPubSub/%s/sharedPrivateLinkResources/%s" return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.WebPubSubName, id.SharedPrivateLinkResourceName) } @@ -57,7 +57,7 @@ func WebPubsubSharedPrivateLinkResourceID(input string) (*WebPubsubSharedPrivate } if resourceId.ResourceGroup == "" { - return nil, fmt.Errorf("ID was missing the 'resourcegroups' element") + return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") } if resourceId.WebPubSubName, err = id.PopSegment("WebPubSub"); err != nil { diff --git a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go index 63d8ed343f17..7d94bdce4738 100644 --- a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go +++ b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go @@ -12,7 +12,7 @@ var _ resourceids.Id = WebPubsubSharedPrivateLinkResourceId{} func TestWebPubsubSharedPrivateLinkResourceIDFormatter(t *testing.T) { actual := NewWebPubsubSharedPrivateLinkResourceID("12345678-1234-9876-4563-123456789012", "resGroup1", "Webpubsub1", "resource1").ID() - expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1" + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1" if actual != expected { t.Fatalf("Expected %q but got %q", expected, actual) } @@ -51,37 +51,37 @@ func TestWebPubsubSharedPrivateLinkResourceID(t *testing.T) { { // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", Error: true, }, { // missing WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/", Error: true, }, { // missing value for WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", Error: true, }, { // missing SharedPrivateLinkResourceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", Error: true, }, { // missing value for SharedPrivateLinkResourceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/", Error: true, }, { // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", Expected: &WebPubsubSharedPrivateLinkResourceId{ SubscriptionId: "12345678-1234-9876-4563-123456789012", ResourceGroup: "resGroup1", diff --git a/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go b/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go index 4c79cbf3a923..70cc51a2da70 100644 --- a/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go +++ b/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go @@ -36,37 +36,37 @@ func TestWebPubsubSharedPrivateLinkResourceID(t *testing.T) { { // missing value for ResourceGroup - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", Valid: false, }, { // missing WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/", Valid: false, }, { // missing value for WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", Valid: false, }, { // missing SharedPrivateLinkResourceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", Valid: false, }, { // missing value for SharedPrivateLinkResourceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/", Valid: false, }, { // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourcegroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", Valid: true, }, From 22dca08b687bcc18494af14e56a872511593742f Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 19 Jul 2022 14:44:02 +0800 Subject: [PATCH 09/12] update upstream --- .teamcity/components/generated/services.kt | 1 + CHANGELOG.md | 91 +- DEVELOPER.md | 4 + README.md | 4 +- contributing/README.md | 2 +- contributing/topics/maintainer-changelog.md | 2 + go.mod | 59 +- go.sum | 298 +- helpers/azure/resource_group.go | 1 - internal/clients/client.go | 3 + internal/provider/services.go | 4 + internal/sdk/resource.go | 12 +- .../aadb2c/aadb2c_directory_resource.go | 1 - .../apimanagement/api_management_resource.go | 2 +- .../app_configuration_data_source.go | 2 +- .../app_configuration_resource.go | 5 +- .../app_configuration_resource_test.go | 2 +- .../appconfiguration/client/client.go | 2 +- ...ion_insights_workbook_template_resource.go | 433 + ...nsights_workbook_template_resource_test.go | 320 + .../applicationinsights/client/client.go | 6 + .../applicationinsights/registration.go | 17 +- .../services/appservice/helpers/fx_strings.go | 2 +- .../appservice/helpers/web_app_schema.go | 39 +- .../linux_function_app_data_source.go | 22 +- .../linux_function_app_data_source_test.go | 1 + .../appservice/linux_function_app_resource.go | 9 +- .../linux_function_app_resource_test.go | 42 + .../linux_function_app_slot_resource.go | 8 +- .../linux_function_app_slot_resource_test.go | 39 + .../appservice/linux_web_app_resource.go | 26 +- .../appservice/linux_web_app_resource_test.go | 50 + .../appservice/linux_web_app_slot_resource.go | 4 +- .../windows_function_app_data_source.go | 1 + .../windows_function_app_data_source_test.go | 1 + .../windows_function_app_resource.go | 4 +- .../windows_function_app_slot_resource.go | 4 +- .../appservice/windows_web_app_resource.go | 31 +- .../windows_web_app_resource_test.go | 51 + .../windows_web_app_slot_resource.go | 8 +- .../attestation_provider_resource.go | 3 +- .../cdn/cdn_frontdoor_endpoint_data_source.go | 1 - .../cdn/cdn_frontdoor_endpoint_resource.go | 3 +- .../compute/availability_set_data_source.go | 62 +- .../compute/availability_set_resource.go | 103 +- .../compute/availability_set_resource_test.go | 18 +- internal/services/compute/client/client.go | 120 +- .../compute/gallery_application_resource.go | 362 + .../gallery_application_resource_test.go | 519 + .../gallery_application_version_resource.go | 568 + ...llery_application_version_resource_test.go | 678 ++ .../compute/linux_virtual_machine_resource.go | 54 +- ...x_virtual_machine_resource_scaling_test.go | 277 + ...machine_scale_set_disk_os_resource_test.go | 61 + ...inux_virtual_machine_scale_set_resource.go | 30 + ...machine_scale_set_scaling_resource_test.go | 79 + .../services/compute/managed_disk_resource.go | 3 +- .../orchestrated_virtual_machine_scale_set.go | 17 +- ...machine_scale_set_disk_os_resource_test.go | 107 + ...ated_virtual_machine_scale_set_resource.go | 8 +- .../compute/parse/gallery_application.go | 75 + .../compute/parse/gallery_application_test.go | 128 + .../parse/gallery_application_version.go | 81 + .../parse/gallery_application_version_test.go | 144 + internal/services/compute/registration.go | 12 + internal/services/compute/resourceids.go | 3 +- .../compute/shared_image_data_source_test.go | 4 +- .../services/compute/shared_image_resource.go | 154 + .../compute/shared_image_resource_test.go | 325 +- .../shared_image_version_data_source.go | 13 +- .../compute/ssh_public_key_data_source.go | 39 +- .../compute/ssh_public_key_resource.go | 136 +- .../compute/ssh_public_key_resource_test.go | 10 +- internal/services/compute/validate/compute.go | 25 + .../services/compute/validate/compute_test.go | 110 + .../validate/gallery_application_id.go | 23 + .../validate/gallery_application_id_test.go | 88 + .../gallery_application_version_id.go | 23 + .../gallery_application_version_id_test.go | 100 + .../compute/virtual_machine_scale_set.go | 27 +- .../windows_virtual_machine_resource.go | 54 +- ...s_virtual_machine_resource_scaling_test.go | 261 + ...machine_scale_set_disk_os_resource_test.go | 59 + ...dows_virtual_machine_scale_set_resource.go | 39 +- ...machine_scale_set_scaling_resource_test.go | 77 + internal/services/containers/client/client.go | 10 +- .../containers/container_group_data_source.go | 34 +- .../containers/container_group_resource.go | 676 +- .../container_group_resource_test.go | 24 +- ...kubernetes_cluster_addons_resource_test.go | 21 +- ...ubernetes_cluster_network_resource_test.go | 8 + .../kubernetes_cluster_node_pool_resource.go | 24 + ...ernetes_cluster_node_pool_resource_test.go | 172 + .../kubernetes_cluster_other_resource_test.go | 79 + .../containers/kubernetes_cluster_resource.go | 4 +- .../kubernetes_cluster_resource_test.go | 78 + .../kubernetes_cluster_upgrade_test.go | 4 +- .../containers/kubernetes_nodepool.go | 91 +- internal/services/containers/probe.go | 8 + internal/services/containers/resourceids.go | 1 - .../cosmos/cosmosdb_account_resource.go | 3 +- .../cosmosdb_cassandra_datacenter_resource.go | 105 +- ...osdb_cassandra_datacenter_resource_test.go | 263 +- .../cosmosdb_cassandra_resource_test.go | 4 +- internal/services/databricks/client/client.go | 2 +- ...atabricks_customer_managed_key_resource.go | 78 +- ...icks_customer_managed_key_resource_test.go | 2 +- .../databricks_workspace_data_source.go | 2 +- ...private_endpoint_connection_data_source.go | 2 +- .../databricks_workspace_resource.go | 5 +- .../databricks_workspace_resource_test.go | 2 +- .../migration/customer_managed_key.go | 101 + ...inked_service_azure_databricks_resource.go | 4 +- ...ctory_managed_private_endpoint_resource.go | 1 + .../data_share_account_data_source.go | 1 - ...workspace_application_group_association.go | 1 - ...tual_desktop_scaling_plan_resource_test.go | 3 +- .../dev_test_lab_schedule_resource.go | 8 +- .../eventgrid/parse/event_subscription.go | 1 - internal/services/eventhub/client/client.go | 18 +- ...eventhub_authorization_rule_data_source.go | 4 +- .../eventhub_authorization_rule_resource.go | 10 +- ...enthub_authorization_rule_resource_test.go | 2 +- .../eventhub/eventhub_cluster_data_source.go | 2 +- .../eventhub/eventhub_cluster_resource.go | 2 +- .../eventhub_cluster_resource_test.go | 2 +- .../eventhub_consumer_group_data_source.go | 2 +- .../eventhub_consumer_group_resource.go | 2 +- .../eventhub_consumer_group_resource_test.go | 2 +- .../services/eventhub/eventhub_data_source.go | 2 +- ...amespace_authorization_rule_data_source.go | 2 +- ...b_namespace_authorization_rule_resource.go | 2 +- ...espace_authorization_rule_resource_test.go | 2 +- ...namespace_customer_managed_key_resource.go | 2 +- ...pace_customer_managed_key_resource_test.go | 2 +- .../eventhub_namespace_data_source.go | 4 +- ...space_disaster_recovery_config_resource.go | 4 +- ..._disaster_recovery_config_resource_test.go | 2 +- .../eventhub/eventhub_namespace_resource.go | 51 +- .../eventhub_namespace_resource_test.go | 2 +- .../services/eventhub/eventhub_resource.go | 7 +- .../eventhub/eventhub_resource_test.go | 2 +- .../eventhub/migration/consumer_group.go | 2 +- .../migration/eventhub_authorization_rule.go | 60 + .../firewall/firewall_policy_resource.go | 4 +- .../firewall/firewall_policy_resource_test.go | 33 +- .../services/firewall/firewall_resource.go | 7 +- internal/services/firewall/testdata/HOWTO.md | 8 +- internal/services/firewall/testdata/cert.pem | 40 +- .../firewall/testdata/certificate.pfx | Bin 2517 -> 2525 bytes internal/services/firewall/testdata/key.pem | 52 +- .../services/firewall/testdata/openssl.cnf | 20 + internal/services/fluidrelay/client/client.go | 19 + .../fluid_relay_servers_resource.go | 271 + .../fluid_relay_servers_resource_test.go | 301 + .../services/fluidrelay/parse/fluid_relay.go | 69 + .../fluidrelay/parse/fluid_relay_servers.go | 69 + .../parse/fluid_relay_servers_test.go | 112 + .../fluidrelay/parse/fluid_relay_test.go | 112 + internal/services/fluidrelay/registration.go | 29 + internal/services/fluidrelay/resourceids.go | 4 + .../validate/fluid_relay_servers_id.go | 23 + .../validate/fluid_relay_servers_id_test.go | 76 + .../fluidrelay/validate/server_name.go | 21 + .../fluidrelay/validate/server_name_test.go | 63 + .../hdinsight_kafka_cluster_resource.go | 12 + .../hdinsight_kafka_cluster_resource_test.go | 5 + .../key_vault_access_policy_resource.go | 3 +- .../key_vault_access_policy_resource_test.go | 3 +- .../key_vault_certificate_resource.go | 56 +- internal/services/kusto/client/client.go | 2 +- internal/services/kusto/identity.go | 2 +- ...ttached_database_configuration_resource.go | 2 +- ...o_cluster_customer_managed_key_resource.go | 2 +- ...o_cluster_principal_assignment_resource.go | 2 +- .../services/kusto/kusto_cluster_resource.go | 22 +- .../kusto/kusto_cluster_resource_test.go | 11 +- .../kusto/kusto_data_connection_import.go | 2 +- ..._database_principal_assignment_resource.go | 2 +- .../services/kusto/kusto_database_resource.go | 2 +- .../kusto/kusto_database_script_resource.go | 55 +- .../kusto_database_script_resource_test.go | 40 +- ...usto_eventgrid_data_connection_resource.go | 47 +- ...eventgrid_data_connection_resource_test.go | 83 +- ...kusto_eventhub_data_connection_resource.go | 20 +- ..._eventhub_data_connection_resource_test.go | 34 + .../kusto_iothub_data_connection_resource.go | 18 +- ...to_iothub_data_connection_resource_test.go | 2 + internal/services/lighthouse/client/client.go | 19 +- .../lighthouse_assignment_resource.go | 78 +- .../lighthouse_assignment_resource_test.go | 13 +- .../lighthouse_definition_resource.go | 171 +- .../lighthouse_definition_resource_test.go | 10 +- .../backend_address_pool_address_resource.go | 101 +- .../backend_address_pool_data_source.go | 68 +- .../backend_address_pool_resource.go | 21 + .../loadbalancer_nat_rule_resource_test.go | 111 + .../loadbalancer/loadbalancer_resource.go | 12 +- .../loadbalancer/nat_rule_resource.go | 68 +- .../services/loadbalancer/rule_resource.go | 5 +- ...s_cluster_customer_managed_key_resource.go | 3 +- .../log_analytics_cluster_resource.go | 3 +- .../log_analytics_saved_search_resource.go | 3 +- .../migration/saved_search_v0_to_v1.go | 1 - .../logic/logic_app_standard_resource.go | 6 +- internal/services/logz/client/client.go | 13 +- internal/services/logz/logz_common.go | 97 + .../services/logz/logz_monitor_resource.go | 71 +- .../logz/logz_monitor_resource_test.go | 36 +- .../logz/logz_sub_account_resource.go | 246 + .../logz/logz_sub_account_resource_test.go | 224 + .../logz/logz_tag_rule_resource_test.go | 15 +- .../services/logz/parse/logz_sub_account.go | 75 + .../logz/parse/logz_sub_account_test.go | 128 + internal/services/logz/registration.go | 5 +- internal/services/logz/resourceids.go | 1 + .../logz/validate/logz_monitor_name.go | 14 + .../logz/validate/logz_sub_account_id.go | 23 + .../logz/validate/logz_sub_account_id_test.go | 88 + .../services/maintenance/client/client.go | 5 + ..._maintenance_configurations_data_source.go | 222 + ...tenance_configurations_data_source_test.go | 84 + internal/services/maintenance/registration.go | 3 +- ...monitor_aad_diagnostic_setting_resource.go | 2 +- .../monitor_action_group_data_source.go | 4 +- .../monitor/monitor_action_group_resource.go | 11 +- .../monitor_diagnostic_setting_resource.go | 2 +- .../monitor/monitor_metric_alert_resource.go | 3 + .../mssql/mssql_failover_group_resource.go | 3 +- ...anaged_instance_failover_group_resource.go | 27 + ...d_instance_failover_group_resource_test.go | 2 - .../mssql/mssql_managed_instance_resource.go | 2 + .../mssql_server_dns_alias_resource_test.go | 3 +- .../services/mssql/mssql_server_resource.go | 2 +- internal/services/netapp/client/client.go | 42 +- .../netapp/netapp_account_data_source.go | 19 +- .../netapp/netapp_account_resource.go | 100 +- .../netapp/netapp_account_resource_test.go | 37 +- .../netapp/netapp_pool_data_source.go | 29 +- .../services/netapp/netapp_pool_resource.go | 141 +- .../netapp/netapp_pool_resource_test.go | 54 +- .../netapp/netapp_snapshot_data_source.go | 22 +- .../netapp_snapshot_policy_data_source.go | 21 +- .../netapp/netapp_snapshot_policy_resource.go | 236 +- .../netapp/netapp_snapshot_policy_test.go | 8 +- .../netapp/netapp_snapshot_resource.go | 68 +- .../netapp/netapp_snapshot_resource_test.go | 10 +- .../netapp/netapp_volume_data_source.go | 29 +- .../services/netapp/netapp_volume_resource.go | 463 +- .../netapp/netapp_volume_resource_test.go | 71 +- .../application_gateway_data_source.go | 1 - .../network/application_gateway_resource.go | 2 +- .../application_gateway_resource_test.go | 235 +- ...ork_security_group_association_resource.go | 3 +- ...ecurity_group_association_resource_test.go | 3 +- .../network/network_interface_resource.go | 3 +- .../network/private_endpoint_resource.go | 2 +- internal/services/network/subnet_resource.go | 1 + .../virtual_network_gateway_resource.go | 3 +- .../network/virtual_network_resource.go | 3 +- .../policy/assignment_base_resource.go | 3 +- .../assignment_subscription_resource_test.go | 11 +- internal/services/policy/client/client.go | 10 +- .../policy/remediation_management_group.go | 123 +- .../remediation_management_group_test.go | 19 +- .../services/policy/remediation_resource.go | 150 +- .../policy/remediation_resource_group.go | 101 +- .../policy/remediation_resource_group_test.go | 13 +- .../policy/remediation_resource_test.go | 13 +- .../policy/remediation_subscription.go | 103 +- .../policy/remediation_subscription_test.go | 13 +- internal/services/portal/client/client.go | 6 - .../portal/legacy_dashboard_resource.go | 79 +- .../portal/legacy_dashboard_resource_test.go | 8 +- .../portal_tenant_configuration_resource.go | 3 +- ...rtal_tenant_configuration_resource_test.go | 3 +- ...ible_server_configuration_resource_test.go | 23 + .../resource/template_deployment_common.go | 16 + ..._center_auto_provisioning_resource_test.go | 3 +- ...erver_vulnerability_assessment_resource.go | 3 +- internal/services/servicebus/client/client.go | 59 +- internal/services/servicebus/internal.go | 62 +- .../migration/namespace_network_rule_set.go | 4 +- .../servicebus/migration/subscription.go | 4 +- ...amespace_authorization_rule_data_source.go | 42 +- ...s_namespace_authorization_rule_resource.go | 107 +- ...espace_authorization_rule_resource_test.go | 10 +- .../servicebus_namespace_data_source.go | 43 +- ...ce_disaster_recovery_config_data_source.go | 48 +- ...space_disaster_recovery_config_resource.go | 109 +- ...namespace_disaster_recovery_config_test.go | 10 +- ...bus_namespace_network_rule_set_resource.go | 155 +- ...amespace_network_rule_set_resource_test.go | 8 +- .../servicebus_namespace_resource.go | 262 +- .../servicebus_namespace_resource_test.go | 8 +- ...us_queue_authorization_rule_data_source.go | 64 +- ...cebus_queue_authorization_rule_resource.go | 147 +- ..._queue_authorization_rule_resource_test.go | 10 +- .../servicebus_queue_data_source.go | 104 +- .../servicebus/servicebus_queue_resource.go | 226 +- .../servicebus_queue_resource_test.go | 50 +- .../servicebus_subscription_data_source.go | 53 +- .../servicebus_subscription_resource.go | 104 +- .../servicebus_subscription_resource_test.go | 10 +- .../servicebus_subscription_rule_resource.go | 164 +- ...vicebus_subscription_rule_resource_test.go | 10 +- ...us_topic_authorization_rule_data_source.go | 53 +- ...cebus_topic_authorization_rule_resource.go | 139 +- ..._topic_authorization_rule_resource_test.go | 10 +- .../servicebus_topic_data_source.go | 97 +- .../servicebus/servicebus_topic_resource.go | 175 +- .../servicebus_topic_resource_test.go | 10 +- internal/services/servicebus/transition.go | 23 + .../signalr/migration/network_acl_v0_to_v1.go | 2 +- .../signalr/migration/service_v0_to_v1.go | 2 +- .../signalr/signalr_service_data_source.go | 2 +- .../signalr_service_network_acl_resource.go | 8 +- ...gnalr_service_network_acl_resource_test.go | 2 +- .../signalr/signalr_service_resource.go | 153 +- .../signalr/signalr_service_resource_test.go | 85 +- .../services/signalr/web_pubsub_resource.go | 3 +- .../services/springcloud/client/client.go | 2 +- ...spring_cloud_active_deployment_resource.go | 2 +- ...cloud_api_portal_custom_domain_resource.go | 2 +- .../spring_cloud_api_portal_resource.go | 2 +- ...cloud_app_cosmosdb_association_resource.go | 2 +- ...ng_cloud_app_mysql_association_resource.go | 2 +- ...ng_cloud_app_redis_association_resource.go | 2 +- .../springcloud/spring_cloud_app_resource.go | 2 +- .../spring_cloud_app_resource_test.go | 10 + .../spring_cloud_build_deployment_resource.go | 41 +- ...ng_cloud_build_deployment_resource_test.go | 49 + ...pring_cloud_build_pack_binding_resource.go | 2 +- .../spring_cloud_builder_resource.go | 2 +- .../spring_cloud_certificate_resource.go | 2 +- ...ng_cloud_configuration_service_resource.go | 2 +- ...ing_cloud_container_deployment_resource.go | 41 +- ...loud_container_deployment_resource_test.go | 52 +- .../spring_cloud_custom_domain_resource.go | 2 +- ...ng_cloud_gateway_custom_domain_resource.go | 2 +- .../spring_cloud_gateway_resource.go | 24 +- ...ing_cloud_gateway_route_config_resource.go | 4 +- .../spring_cloud_java_deployment_resource.go | 24 +- .../spring_cloud_service_resource.go | 2 +- .../spring_cloud_storage_resource.go | 2 +- internal/services/storage/client/client.go | 6 +- .../storage/parse/object_replication.go | 2 +- .../storage/parse/object_replication_test.go | 2 +- .../storage_management_policy_data_source.go | 14 +- .../storage_object_replication_resource.go | 2 +- .../stream_analytics_output_blob_resource.go | 45 +- ...eam_analytics_output_blob_resource_test.go | 62 +- ...apse_integration_runtime_azure_resource.go | 13 +- ...integration_runtime_azure_resource_test.go | 26 + .../trafficmanager/azure_endpoint_resource.go | 8 +- .../azure_endpoint_resource_test.go | 59 + .../external_endpoint_resource.go | 8 +- .../external_endpoint_resource_test.go | 51 + .../nested_endpoint_resource.go | 8 +- .../nested_endpoint_resource_test.go | 69 + internal/services/web/app_service.go | 3 +- .../web/app_service_environment_resource.go | 3 +- .../app_service_hybrid_connection_resource.go | 3 +- .../services/web/function_app_resource.go | 3 +- test/main.tf | 96 + .../kusto/mgmt/2022-02-01/kusto/CHANGELOG.md | 2 + .../kusto/mgmt/2022-02-01/kusto/_meta.json | 11 + .../kusto/attacheddatabaseconfigurations.go | 449 + .../kusto/mgmt/2022-02-01/kusto/client.go | 42 + .../kusto/clusterprincipalassignments.go | 446 + .../kusto/mgmt/2022-02-01/kusto/clusters.go | 1525 +++ .../kusto/databaseprincipalassignments.go | 456 + .../kusto/mgmt/2022-02-01/kusto/databases.go | 761 ++ .../mgmt/2022-02-01/kusto/dataconnections.go | 618 ++ .../kusto/mgmt/2022-02-01/kusto/enums.go | 668 ++ .../kusto/managedprivateendpoints.go | 534 + .../kusto/mgmt/2022-02-01/kusto/models.go | 4819 ++++++++ .../kusto/mgmt/2022-02-01/kusto/operations.go | 142 + .../2022-02-01/kusto/operationsresults.go | 110 + .../kusto/operationsresultslocation.go | 109 + .../kusto/privateendpointconnections.go | 360 + .../2022-02-01/kusto/privatelinkresources.go | 188 + .../kusto/mgmt/2022-02-01/kusto/scripts.go | 536 + .../kusto/mgmt/2022-02-01/kusto/version.go | 19 + .../mgmt/2021-08-01/network/CHANGELOG.md | 7 + .../mgmt/2021-08-01/network/_meta.json | 2 +- .../network/mgmt/2021-08-01/network/client.go | 2 +- .../2021-08-01/network/interfacesgroup.go | 16 +- .../network/mgmt/2021-08-01/network/models.go | 5 + .../2021-08-01/network/publicipaddresses.go | 12 +- .../appplatform/CHANGELOG.md | 2 + .../2022-05-01-preview/appplatform/_meta.json | 11 + .../appplatform/apiportalcustomdomains.go | 404 + .../appplatform/apiportals.go | 484 + .../2022-05-01-preview/appplatform/apps.go | 760 ++ .../appplatform/bindings.go | 490 + .../appplatform/buildpackbinding.go | 412 + .../appplatform/buildservice.go | 1203 ++ .../appplatform/buildserviceagentpool.go | 321 + .../appplatform/buildservicebuilder.go | 404 + .../appplatform/certificates.go | 395 + .../2022-05-01-preview/appplatform/client.go | 41 + .../appplatform/configservers.go | 376 + .../appplatform/configurationservices.go | 482 + .../appplatform/customdomains.go | 490 + .../appplatform/deployments.go | 1221 ++ .../2022-05-01-preview/appplatform/enums.go | 710 ++ .../appplatform/gatewaycustomdomains.go | 404 + .../appplatform/gatewayrouteconfigs.go | 405 + .../appplatform/gateways.go | 484 + .../2022-05-01-preview/appplatform/models.go | 9834 +++++++++++++++++ .../appplatform/monitoringsettings.go | 287 + .../appplatform/operations.go | 140 + .../appplatform/runtimeversions.go | 98 + .../appplatform/serviceregistries.go | 393 + .../appplatform/services.go | 1136 ++ .../2022-05-01-preview/appplatform/skus.go | 144 + .../appplatform/storages.go | 395 + .../2022-05-01-preview/appplatform/version.go | 19 + .../Azure/azure-sdk-for-go/version/version.go | 2 +- vendor/github.com/fatih/color/README.md | 2 +- .../golang/protobuf/jsonpb/decode.go | 524 + .../golang/protobuf/jsonpb/encode.go | 559 + .../github.com/golang/protobuf/jsonpb/json.go | 69 + .../authentication/environment.go | 6 + .../lang/response/response.go | 10 +- .../2022-05-01/configurationstores/README.md | 154 + .../2022-05-01/configurationstores/client.go | 18 + .../configurationstores/constants.go | 164 + .../id_configurationstore.go | 124 + .../method_create_autorest.go | 79 + .../method_delete_autorest.go | 78 + .../method_get_autorest.go | 67 + .../method_list_autorest.go | 187 + .../method_listbyresourcegroup_autorest.go | 187 + .../method_listkeys_autorest.go | 186 + .../method_regeneratekey_autorest.go | 69 + .../method_update_autorest.go | 79 + .../configurationstores/model_apikey.go | 31 + .../model_configurationstore.go | 21 + .../model_configurationstoreproperties.go | 35 + ...gurationstorepropertiesupdateparameters.go | 11 + ...odel_configurationstoreupdateparameters.go | 15 + .../model_encryptionproperties.go | 8 + .../model_keyvaultproperties.go | 9 + .../model_privateendpoint.go | 8 + ...del_privateendpointconnectionproperties.go | 10 + ...odel_privateendpointconnectionreference.go | 11 + ...model_privatelinkserviceconnectionstate.go | 10 + .../model_regeneratekeyparameters.go | 8 + .../configurationstores/model_sku.go | 8 + .../configurationstores/predicates.go | 67 + .../2022-05-01/configurationstores/version.go | 12 + .../2020-11-20/applicationinsights/README.md | 110 + .../2020-11-20/applicationinsights/client.go | 18 + .../id_workbooktemplate.go | 124 + ...orkbooktemplatescreateorupdate_autorest.go | 68 + ...method_workbooktemplatesdelete_autorest.go | 65 + .../method_workbooktemplatesget_autorest.go | 67 + ...oktemplateslistbyresourcegroup_autorest.go | 69 + ...method_workbooktemplatesupdate_autorest.go | 68 + .../model_workbooktemplate.go | 13 + .../model_workbooktemplategallery.go | 12 + .../model_workbooktemplatelocalizedgallery.go | 9 + .../model_workbooktemplateproperties.go | 12 + .../model_workbooktemplateslistresult.go | 8 + .../model_workbooktemplateupdateparameters.go | 9 + .../2020-11-20/applicationinsights/version.go | 12 + .../2021-11-01/availabilitysets/README.md | 144 + .../2021-11-01/availabilitysets/client.go | 18 + .../2021-11-01/availabilitysets/constants.go | 37 + .../availabilitysets/id_availabilityset.go | 124 + .../method_createorupdate_autorest.go | 68 + .../method_delete_autorest.go | 65 + .../availabilitysets/method_get_autorest.go | 67 + .../availabilitysets/method_list_autorest.go | 187 + .../method_listavailablesizes_autorest.go | 68 + .../method_listbysubscription_autorest.go | 216 + .../method_update_autorest.go | 68 + .../availabilitysets/model_availabilityset.go | 14 + .../model_availabilitysetproperties.go | 12 + .../model_availabilitysetupdate.go | 10 + .../model_instanceviewstatus.go | 30 + .../2021-11-01/availabilitysets/model_sku.go | 10 + .../availabilitysets/model_subresource.go | 8 + .../model_virtualmachinesize.go | 13 + .../model_virtualmachinesizelistresult.go | 8 + .../2021-11-01/availabilitysets/predicates.go | 29 + .../2021-11-01/availabilitysets/version.go | 12 + .../2021-11-01/sshpublickeys/README.md | 144 + .../2021-11-01/sshpublickeys/client.go | 18 + .../sshpublickeys/id_sshpublickey.go | 124 + .../sshpublickeys/method_create_autorest.go | 68 + .../sshpublickeys/method_delete_autorest.go | 65 + .../method_generatekeypair_autorest.go | 68 + .../sshpublickeys/method_get_autorest.go | 67 + .../method_listbyresourcegroup_autorest.go | 187 + .../method_listbysubscription_autorest.go | 187 + .../sshpublickeys/method_update_autorest.go | 68 + ...model_sshpublickeygeneratekeypairresult.go | 10 + .../model_sshpublickeyresource.go | 13 + .../model_sshpublickeyresourceproperties.go | 8 + .../model_sshpublickeyupdateresource.go | 9 + .../2021-11-01/sshpublickeys/predicates.go | 29 + .../2021-11-01/sshpublickeys/version.go | 12 + .../2021-03-01/containerinstance/README.md | 263 + .../2021-03-01/containerinstance/client.go | 18 + .../2021-03-01/containerinstance/constants.go | 264 + .../containerinstance/id_container.go | 137 + .../containerinstance/id_containergroup.go | 124 + .../containerinstance/id_location.go | 111 + ..._containergroupscreateorupdate_autorest.go | 79 + .../method_containergroupsdelete_autorest.go | 78 + .../method_containergroupsget_autorest.go | 67 + .../method_containergroupslist_autorest.go | 187 + ...ainergroupslistbyresourcegroup_autorest.go | 187 + .../method_containergroupsrestart_autorest.go | 78 + .../method_containergroupsstart_autorest.go | 78 + .../method_containergroupsstop_autorest.go | 66 + .../method_containergroupsupdate_autorest.go | 68 + .../method_containersattach_autorest.go | 68 + ...ethod_containersexecutecommand_autorest.go | 69 + .../method_containerslistlogs_autorest.go | 102 + ...ethod_locationlistcachedimages_autorest.go | 186 + ...ethod_locationlistcapabilities_autorest.go | 186 + .../method_locationlistusage_autorest.go | 68 + .../model_azurefilevolume.go | 11 + .../containerinstance/model_cachedimages.go | 9 + .../containerinstance/model_capabilities.go | 13 + .../model_capabilitiescapabilities.go | 10 + .../containerinstance/model_container.go | 9 + .../model_containerattachresponse.go | 9 + .../containerinstance/model_containerexec.go | 8 + .../model_containerexecrequest.go | 9 + .../model_containerexecrequestterminalsize.go | 9 + .../model_containerexecresponse.go | 9 + .../containerinstance/model_containergroup.go | 18 + .../model_containergroupdiagnostics.go | 8 + .../model_containergroupnetworkprofile.go | 8 + .../model_containergroupproperties.go | 21 + ...el_containergrouppropertiesinstanceview.go | 9 + .../model_containerhttpget.go | 11 + .../containerinstance/model_containerport.go | 9 + .../containerinstance/model_containerprobe.go | 14 + .../model_containerproperties.go | 16 + .../model_containerpropertiesinstanceview.go | 11 + .../containerinstance/model_containerstate.go | 42 + .../model_dnsconfiguration.go | 10 + .../model_encryptionproperties.go | 10 + .../model_environmentvariable.go | 10 + .../containerinstance/model_event.go | 43 + .../containerinstance/model_gitrepovolume.go | 10 + .../containerinstance/model_gpuresource.go | 9 + .../containerinstance/model_httpheader.go | 9 + .../model_imageregistrycredential.go | 10 + .../model_initcontainerdefinition.go | 9 + ...model_initcontainerpropertiesdefinition.go | 12 + ...ntainerpropertiesdefinitioninstanceview.go | 11 + .../containerinstance/model_ipaddress.go | 12 + .../containerinstance/model_loganalytics.go | 12 + .../containerinstance/model_logs.go | 8 + .../containerinstance/model_port.go | 9 + .../containerinstance/model_resource.go | 12 + .../containerinstance/model_resourcelimits.go | 10 + .../model_resourcerequests.go | 10 + .../model_resourcerequirements.go | 9 + .../containerinstance/model_usage.go | 11 + .../model_usagelistresult.go | 8 + .../containerinstance/model_usagename.go | 9 + .../containerinstance/model_volume.go | 12 + .../containerinstance/model_volumemount.go | 10 + .../containerinstance/predicates.go | 80 + .../2021-03-01/containerinstance/version.go | 12 + .../2021-04-01-preview/workspaces/README.md | 116 + .../2021-04-01-preview/workspaces/client.go | 18 + .../workspaces/constants.go | 275 + .../workspaces/id_workspace.go | 124 + .../method_createorupdate_autorest.go | 79 + .../workspaces/method_delete_autorest.go | 78 + .../workspaces/method_get_autorest.go | 67 + .../method_listbyresourcegroup_autorest.go | 187 + .../method_listbysubscription_autorest.go | 187 + .../workspaces/method_update_autorest.go | 79 + .../workspaces/model_createdby.go | 10 + .../workspaces/model_encryption.go | 11 + .../model_encryptionentitiesdefinition.go | 8 + .../workspaces/model_encryptionv2.go | 9 + .../model_encryptionv2keyvaultproperties.go | 10 + .../model_managedidentityconfiguration.go | 10 + .../workspaces/model_privateendpoint.go | 8 + .../model_privateendpointconnection.go | 11 + ...del_privateendpointconnectionproperties.go | 10 + ...model_privatelinkserviceconnectionstate.go | 10 + .../workspaces/model_sku.go | 9 + .../workspaces/model_workspace.go | 19 + .../model_workspacecustombooleanparameter.go | 9 + .../model_workspacecustomobjectparameter.go | 9 + .../model_workspacecustomparameters.go | 23 + .../model_workspacecustomstringparameter.go | 9 + .../model_workspaceencryptionparameter.go | 9 + .../workspaces/model_workspaceproperties.go | 40 + .../model_workspacepropertiesencryption.go | 8 + .../model_workspaceproviderauthorization.go | 9 + .../workspaces/model_workspaceupdate.go | 8 + .../workspaces/predicates.go | 29 + .../2021-04-01-preview/workspaces/version.go | 12 + .../authorizationruleseventhubs/README.md | 95 + .../authorizationruleseventhubs/client.go | 18 + .../authorizationruleseventhubs/constants.go | 65 + .../id_eventhub.go | 137 + .../id_eventhubauthorizationrule.go | 150 + ...reateorupdateauthorizationrule_autorest.go | 68 + ...venthubslistauthorizationrules_autorest.go | 186 + .../method_eventhubslistkeys_autorest.go | 68 + ...method_eventhubsregeneratekeys_autorest.go | 69 + .../model_accesskeys.go | 14 + .../model_authorizationrule.go | 11 + .../model_authorizationruleproperties.go | 8 + .../model_regenerateaccesskeyparameters.go | 9 + .../authorizationruleseventhubs/predicates.go | 24 + .../authorizationruleseventhubs/version.go | 12 + .../authorizationrulesnamespaces/README.md | 127 + .../authorizationrulesnamespaces/client.go | 18 + .../authorizationrulesnamespaces/constants.go | 65 + .../id_authorizationrule.go | 137 + .../id_namespace.go | 124 + ...reateorupdateauthorizationrule_autorest.go | 68 + ...espacesdeleteauthorizationrule_autorest.go | 65 + ...namespacesgetauthorizationrule_autorest.go | 67 + ...mespaceslistauthorizationrules_autorest.go | 186 + .../method_namespaceslistkeys_autorest.go | 68 + ...ethod_namespacesregeneratekeys_autorest.go | 69 + .../model_accesskeys.go | 14 + .../model_authorizationrule.go | 11 + .../model_authorizationruleproperties.go | 8 + .../model_regenerateaccesskeyparameters.go | 9 + .../predicates.go | 24 + .../authorizationrulesnamespaces/version.go | 12 + .../README.md | 41 + .../client.go | 18 + .../constants.go | 46 + .../id_namespace.go | 124 + .../model_checknameavailabilityparameter.go | 8 + .../model_checknameavailabilityresult.go | 10 + .../version.go | 12 + .../2017-04-01/consumergroups/README.md | 90 + .../2017-04-01/consumergroups/client.go | 18 + .../consumergroups/id_consumergroup.go | 150 + .../2017-04-01/consumergroups/id_eventhub.go | 137 + .../method_createorupdate_autorest.go | 68 + .../consumergroups/method_delete_autorest.go | 65 + .../consumergroups/method_get_autorest.go | 67 + .../method_listbyeventhub_autorest.go | 220 + .../consumergroups/model_consumergroup.go | 11 + .../model_consumergroupproperties.go | 40 + .../2017-04-01/consumergroups/predicates.go | 24 + .../2017-04-01/consumergroups/version.go | 12 + .../disasterrecoveryconfigs/README.md | 122 + .../disasterrecoveryconfigs/client.go | 18 + .../disasterrecoveryconfigs/constants.go | 68 + .../id_disasterrecoveryconfig.go | 137 + .../disasterrecoveryconfigs/id_namespace.go | 124 + .../method_breakpairing_autorest.go | 66 + .../method_createorupdate_autorest.go | 68 + .../method_delete_autorest.go | 65 + .../method_failover_autorest.go | 66 + .../method_get_autorest.go | 67 + .../method_list_autorest.go | 186 + .../model_armdisasterrecovery.go | 11 + .../model_armdisasterrecoveryproperties.go | 12 + .../disasterrecoveryconfigs/predicates.go | 24 + .../disasterrecoveryconfigs/version.go | 12 + .../eventhub/2017-04-01/eventhubs/README.md | 122 + .../eventhub/2017-04-01/eventhubs/client.go | 18 + .../2017-04-01/eventhubs/constants.go | 114 + .../2017-04-01/eventhubs/id_eventhub.go | 137 + .../eventhubs/id_eventhubauthorizationrule.go | 150 + .../2017-04-01/eventhubs/id_namespace.go | 124 + .../method_createorupdate_autorest.go | 68 + .../eventhubs/method_delete_autorest.go | 65 + ...method_deleteauthorizationrule_autorest.go | 65 + .../eventhubs/method_get_autorest.go | 67 + .../method_getauthorizationrule_autorest.go | 67 + .../method_listbynamespace_autorest.go | 220 + .../eventhubs/model_authorizationrule.go | 11 + .../model_authorizationruleproperties.go | 8 + .../eventhubs/model_capturedescription.go | 13 + .../2017-04-01/eventhubs/model_destination.go | 9 + .../eventhubs/model_destinationproperties.go | 10 + .../2017-04-01/eventhubs/model_eventhub.go | 11 + .../eventhubs/model_eventhubproperties.go | 44 + .../2017-04-01/eventhubs/predicates.go | 24 + .../eventhub/2017-04-01/eventhubs/version.go | 12 + .../eventhubsclusters/README.md | 99 + .../eventhubsclusters/client.go | 18 + .../eventhubsclusters/constants.go | 31 + .../eventhubsclusters/id_cluster.go | 124 + .../method_clusterscreateorupdate_autorest.go | 79 + .../method_clustersdelete_autorest.go | 78 + .../method_clustersget_autorest.go | 67 + ...od_clusterslistbyresourcegroup_autorest.go | 187 + .../method_clustersupdate_autorest.go | 79 + .../eventhubsclusters/model_cluster.go | 14 + .../model_clusterproperties.go | 11 + .../eventhubsclusters/model_clustersku.go | 9 + .../eventhubsclusters/predicates.go | 29 + .../eventhubsclusters/version.go | 12 + .../networkrulesets/README.md | 57 + .../networkrulesets/client.go | 18 + .../networkrulesets/constants.go | 59 + .../networkrulesets/id_namespace.go | 124 + ...escreateorupdatenetworkruleset_autorest.go | 69 + ...od_namespacesgetnetworkruleset_autorest.go | 68 + .../networkrulesets/model_networkruleset.go | 11 + .../model_networkrulesetproperties.go | 11 + .../networkrulesets/model_nwrulesetiprules.go | 9 + .../model_nwrulesetvirtualnetworkrules.go | 9 + .../networkrulesets/model_subnet.go | 8 + .../networkrulesets/version.go | 12 + .../2021-01-01-preview/namespaces/README.md | 120 + .../2021-01-01-preview/namespaces/client.go | 18 + .../namespaces/constants.go | 167 + .../namespaces/id_namespace.go | 124 + .../method_createorupdate_autorest.go | 79 + .../namespaces/method_delete_autorest.go | 78 + .../namespaces/method_get_autorest.go | 67 + .../namespaces/method_list_autorest.go | 187 + .../method_listbyresourcegroup_autorest.go | 187 + .../namespaces/method_update_autorest.go | 68 + .../namespaces/model_connectionstate.go | 9 + .../namespaces/model_ehnamespace.go | 21 + .../namespaces/model_ehnamespaceproperties.go | 50 + .../namespaces/model_encryption.go | 10 + .../namespaces/model_keyvaultproperties.go | 11 + .../namespaces/model_privateendpoint.go | 8 + .../model_privateendpointconnection.go | 16 + ...del_privateendpointconnectionproperties.go | 10 + .../namespaces/model_sku.go | 10 + .../model_userassignedidentityproperties.go | 8 + .../namespaces/predicates.go | 29 + .../2021-01-01-preview/namespaces/version.go | 12 + .../2022-05-26/fluidrelayservers/README.md | 181 + .../2022-05-26/fluidrelayservers/client.go | 18 + .../2022-05-26/fluidrelayservers/constants.go | 121 + .../fluidrelayservers/id_fluidrelayserver.go | 124 + .../method_createorupdate_autorest.go | 68 + .../method_delete_autorest.go | 65 + .../fluidrelayservers/method_get_autorest.go | 67 + .../method_getkeys_autorest.go | 68 + .../method_listbyresourcegroup_autorest.go | 187 + .../method_listbysubscription_autorest.go | 187 + .../method_listkeys_autorest.go | 68 + .../method_regeneratekey_autorest.go | 69 + .../method_update_autorest.go | 68 + ..._customermanagedkeyencryptionproperties.go | 9 + ...ptionpropertieskeyencryptionkeyidentity.go | 9 + .../model_encryptionproperties.go | 8 + .../model_fluidrelayendpoints.go | 10 + .../model_fluidrelayserver.go | 20 + .../model_fluidrelayserverkeys.go | 9 + .../model_fluidrelayserverproperties.go | 12 + .../model_fluidrelayserverupdate.go | 15 + .../model_fluidrelayserverupdateproperties.go | 8 + .../model_regeneratekeyrequest.go | 8 + .../fluidrelayservers/predicates.go | 29 + .../2022-05-26/fluidrelayservers/version.go | 12 + .../registrationassignments/README.md | 82 + .../registrationassignments/client.go | 18 + .../registrationassignments/constants.go | 64 + .../id_scopedregistrationassignment.go | 110 + .../method_createorupdate_autorest.go | 79 + .../method_delete_autorest.go | 78 + .../method_get_autorest.go | 96 + .../method_list_autorest.go | 216 + .../model_authorization.go | 11 + .../registrationassignments/model_plan.go | 11 + .../model_registrationassignment.go | 11 + .../model_registrationassignmentproperties.go | 10 + ...ignmentpropertiesregistrationdefinition.go | 12 + .../registrationassignments/predicates.go | 24 + .../registrationassignments/version.go | 12 + .../registrationdefinitions/README.md | 86 + .../registrationdefinitions/client.go | 18 + .../registrationdefinitions/constants.go | 64 + .../id_scopedregistrationdefinition.go | 110 + .../method_createorupdate_autorest.go | 79 + .../method_delete_autorest.go | 65 + .../method_get_autorest.go | 67 + .../method_list_autorest.go | 187 + .../model_authorization.go | 11 + .../registrationdefinitions/model_plan.go | 11 + .../model_registrationdefinition.go | 12 + .../model_registrationdefinitionproperties.go | 13 + .../registrationdefinitions/predicates.go | 24 + .../registrationdefinitions/version.go | 12 + .../netapp/2021-10-01/capacitypools/README.md | 99 + .../netapp/2021-10-01/capacitypools/client.go | 18 + .../2021-10-01/capacitypools/constants.go | 96 + .../capacitypools/id_capacitypool.go | 137 + .../capacitypools/id_netappaccount.go | 124 + .../method_poolscreateorupdate_autorest.go | 79 + .../method_poolsdelete_autorest.go | 78 + .../capacitypools/method_poolsget_autorest.go | 67 + .../method_poolslist_autorest.go | 186 + .../method_poolsupdate_autorest.go | 79 + .../capacitypools/model_capacitypool.go | 19 + .../capacitypools/model_capacitypoolpatch.go | 13 + .../model_poolpatchproperties.go | 9 + .../capacitypools/model_poolproperties.go | 16 + .../2021-10-01/capacitypools/predicates.go | 34 + .../2021-10-01/capacitypools/version.go | 12 + .../2021-10-01/netappaccounts/README.md | 116 + .../2021-10-01/netappaccounts/client.go | 18 + .../2021-10-01/netappaccounts/constants.go | 43 + .../netappaccounts/id_netappaccount.go | 124 + .../method_accountscreateorupdate_autorest.go | 79 + .../method_accountsdelete_autorest.go | 78 + .../method_accountsget_autorest.go | 67 + .../method_accountslist_autorest.go | 187 + ...hod_accountslistbysubscription_autorest.go | 187 + .../method_accountsupdate_autorest.go | 79 + .../netappaccounts/model_accountencryption.go | 8 + .../netappaccounts/model_accountproperties.go | 10 + .../netappaccounts/model_activedirectory.go | 29 + .../model_ldapsearchscopeopt.go | 10 + .../netappaccounts/model_netappaccount.go | 19 + .../model_netappaccountpatch.go | 13 + .../2021-10-01/netappaccounts/predicates.go | 34 + .../2021-10-01/netappaccounts/version.go | 12 + .../2021-10-01/snapshotpolicy/README.md | 102 + .../2021-10-01/snapshotpolicy/client.go | 18 + .../snapshotpolicy/id_netappaccount.go | 124 + .../snapshotpolicy/id_snapshotpolicies.go | 137 + .../method_snapshotpoliciescreate_autorest.go | 68 + .../method_snapshotpoliciesdelete_autorest.go | 78 + .../method_snapshotpoliciesget_autorest.go | 67 + .../method_snapshotpolicieslist_autorest.go | 68 + .../method_snapshotpoliciesupdate_autorest.go | 79 + .../snapshotpolicy/model_dailyschedule.go | 11 + .../snapshotpolicy/model_hourlyschedule.go | 10 + .../snapshotpolicy/model_monthlyschedule.go | 12 + .../model_snapshotpolicieslist.go | 8 + .../snapshotpolicy/model_snapshotpolicy.go | 19 + .../model_snapshotpolicypatch.go | 13 + .../model_snapshotpolicyproperties.go | 13 + .../snapshotpolicy/model_weeklyschedule.go | 12 + .../2021-10-01/snapshotpolicy/version.go | 12 + .../netapp/2021-10-01/snapshots/README.md | 111 + .../netapp/2021-10-01/snapshots/client.go | 18 + .../2021-10-01/snapshots/id_snapshot.go | 163 + .../netapp/2021-10-01/snapshots/id_volume.go | 150 + .../snapshots/method_create_autorest.go | 79 + .../snapshots/method_delete_autorest.go | 78 + .../snapshots/method_get_autorest.go | 67 + .../snapshots/method_list_autorest.go | 68 + .../snapshots/method_restorefiles_autorest.go | 79 + .../snapshots/method_update_autorest.go | 79 + .../2021-10-01/snapshots/model_snapshot.go | 12 + .../snapshots/model_snapshotproperties.go | 28 + .../snapshots/model_snapshotrestorefiles.go | 9 + .../snapshots/model_snapshotslist.go | 8 + .../netapp/2021-10-01/snapshots/version.go | 12 + .../netapp/2021-10-01/volumes/README.md | 99 + .../netapp/2021-10-01/volumes/client.go | 18 + .../netapp/2021-10-01/volumes/constants.go | 270 + .../2021-10-01/volumes/id_capacitypool.go | 137 + .../netapp/2021-10-01/volumes/id_volume.go | 150 + .../volumes/method_createorupdate_autorest.go | 79 + .../volumes/method_delete_autorest.go | 107 + .../2021-10-01/volumes/method_get_autorest.go | 67 + .../volumes/method_list_autorest.go | 186 + .../volumes/method_update_autorest.go | 79 + .../volumes/model_exportpolicyrule.go | 22 + .../volumes/model_mounttargetproperties.go | 11 + .../volumes/model_placementkeyvaluepairs.go | 9 + .../volumes/model_replicationobject.go | 12 + .../netapp/2021-10-01/volumes/model_volume.go | 19 + .../volumes/model_volumebackupproperties.go | 11 + .../2021-10-01/volumes/model_volumepatch.go | 13 + .../volumes/model_volumepatchproperties.go | 16 + ...del_volumepatchpropertiesdataprotection.go | 9 + ...model_volumepatchpropertiesexportpolicy.go | 8 + .../volumes/model_volumeproperties.go | 49 + .../model_volumepropertiesdataprotection.go | 10 + .../model_volumepropertiesexportpolicy.go | 8 + .../volumes/model_volumesnapshotproperties.go | 8 + .../netapp/2021-10-01/volumes/predicates.go | 34 + .../netapp/2021-10-01/volumes/version.go | 12 + .../2021-10-01/volumesreplication/README.md | 106 + .../2021-10-01/volumesreplication/client.go | 18 + .../volumesreplication/constants.go | 65 + .../volumesreplication/id_volume.go | 150 + ...od_volumesauthorizereplication_autorest.go | 79 + ...method_volumesbreakreplication_autorest.go | 79 + ...ethod_volumesdeletereplication_autorest.go | 78 + ...volumesreinitializereplication_autorest.go | 78 + ...ethod_volumesreplicationstatus_autorest.go | 68 + ...ethod_volumesresyncreplication_autorest.go | 78 + .../model_authorizerequest.go | 8 + .../model_breakreplicationrequest.go | 8 + .../model_replicationstatus.go | 12 + .../2021-10-01/volumesreplication/version.go | 12 + .../2021-10-01/policyinsights/README.md | 432 + .../2021-10-01/policyinsights/client.go | 18 + .../2021-10-01/policyinsights/constants.go | 34 + .../policyinsights/id_managementgroup.go | 98 + .../policyinsights/id_providerremediation.go | 124 + .../id_providers2remediation.go | 113 + .../policyinsights/id_remediation.go | 111 + .../policyinsights/id_scopedremediation.go | 110 + ...iationscancelatmanagementgroup_autorest.go | 68 + ...d_remediationscancelatresource_autorest.go | 68 + ...ediationscancelatresourcegroup_autorest.go | 68 + ...mediationscancelatsubscription_autorest.go | 68 + ...reateorupdateatmanagementgroup_autorest.go | 68 + ...ationscreateorupdateatresource_autorest.go | 68 + ...screateorupdateatresourcegroup_autorest.go | 68 + ...nscreateorupdateatsubscription_autorest.go | 68 + ...iationsdeleteatmanagementgroup_autorest.go | 67 + ...d_remediationsdeleteatresource_autorest.go | 67 + ...ediationsdeleteatresourcegroup_autorest.go | 67 + ...mediationsdeleteatsubscription_autorest.go | 67 + ...mediationsgetatmanagementgroup_autorest.go | 67 + ...thod_remediationsgetatresource_autorest.go | 67 + ...remediationsgetatresourcegroup_autorest.go | 67 + ..._remediationsgetatsubscription_autorest.go | 67 + ...stdeploymentsatmanagementgroup_autorest.go | 215 + ...tionslistdeploymentsatresource_autorest.go | 215 + ...listdeploymentsatresourcegroup_autorest.go | 215 + ...slistdeploymentsatsubscription_autorest.go | 215 + ...diationslistformanagementgroup_autorest.go | 220 + ...od_remediationslistforresource_autorest.go | 221 + ...mediationslistforresourcegroup_autorest.go | 221 + ...emediationslistforsubscription_autorest.go | 221 + .../policyinsights/model_errordefinition.go | 12 + .../policyinsights/model_remediation.go | 16 + .../model_remediationdeployment.go | 44 + .../model_remediationdeploymentsummary.go | 10 + .../model_remediationfilters.go | 8 + .../model_remediationproperties.go | 50 + ...l_remediationpropertiesfailurethreshold.go | 8 + .../policyinsights/model_typederrorinfo.go | 9 + .../2021-10-01/policyinsights/predicates.go | 62 + .../2021-10-01/policyinsights/version.go | 12 + .../disasterrecoveryconfigs/README.md | 197 + .../disasterrecoveryconfigs/client.go | 18 + .../disasterrecoveryconfigs/constants.go | 139 + .../id_authorizationrule.go | 137 + .../id_disasterrecoveryconfig.go | 137 + .../disasterrecoveryconfigs/id_namespace.go | 124 + .../method_breakpairing_autorest.go | 66 + .../method_checknameavailability_autorest.go | 69 + .../method_createorupdate_autorest.go | 68 + .../method_delete_autorest.go | 65 + .../method_failover_autorest.go | 67 + .../method_get_autorest.go | 67 + .../method_getauthorizationrule_autorest.go | 67 + .../method_list_autorest.go | 186 + .../method_listauthorizationrules_autorest.go | 186 + .../method_listkeys_autorest.go | 68 + .../model_accesskeys.go | 14 + .../model_armdisasterrecovery.go | 16 + .../model_armdisasterrecoveryproperties.go | 12 + .../model_checknameavailability.go | 8 + .../model_checknameavailabilityresult.go | 10 + .../model_failoverproperties.go | 8 + .../model_failoverpropertiesproperties.go | 8 + .../model_sbauthorizationrule.go | 16 + .../model_sbauthorizationruleproperties.go | 8 + .../disasterrecoveryconfigs/predicates.go | 47 + .../disasterrecoveryconfigs/version.go | 12 + .../2021-06-01-preview/namespaces/README.md | 195 + .../2021-06-01-preview/namespaces/client.go | 18 + .../namespaces/constants.go | 288 + .../namespaces/id_namespace.go | 124 + .../method_checknameavailability_autorest.go | 70 + .../method_createorupdate_autorest.go | 79 + ...d_createorupdatenetworkruleset_autorest.go | 69 + .../namespaces/method_delete_autorest.go | 78 + .../namespaces/method_get_autorest.go | 67 + .../method_getnetworkruleset_autorest.go | 68 + .../namespaces/method_list_autorest.go | 187 + .../method_listbyresourcegroup_autorest.go | 187 + .../method_listnetworkrulesets_autorest.go | 186 + .../namespaces/method_update_autorest.go | 68 + .../namespaces/model_checknameavailability.go | 8 + .../model_checknameavailabilityresult.go | 10 + .../namespaces/model_connectionstate.go | 9 + .../namespaces/model_encryption.go | 10 + .../namespaces/model_keyvaultproperties.go | 11 + .../namespaces/model_networkruleset.go | 16 + .../model_networkrulesetproperties.go | 12 + .../namespaces/model_nwrulesetiprules.go | 9 + .../model_nwrulesetvirtualnetworkrules.go | 9 + .../namespaces/model_privateendpoint.go | 8 + .../model_privateendpointconnection.go | 16 + ...del_privateendpointconnectionproperties.go | 10 + .../namespaces/model_sbnamespace.go | 21 + .../namespaces/model_sbnamespaceproperties.go | 47 + .../model_sbnamespaceupdateparameters.go | 19 + .../namespaces/model_sbsku.go | 10 + .../namespaces/model_subnet.go | 8 + .../model_userassignedidentityproperties.go | 8 + .../namespaces/predicates.go | 52 + .../2021-06-01-preview/namespaces/version.go | 12 + .../namespacesauthorizationrule/README.md | 127 + .../namespacesauthorizationrule/client.go | 18 + .../namespacesauthorizationrule/constants.go | 65 + .../id_authorizationrule.go | 137 + .../id_namespace.go | 124 + ...reateorupdateauthorizationrule_autorest.go | 68 + ...espacesdeleteauthorizationrule_autorest.go | 65 + ...namespacesgetauthorizationrule_autorest.go | 67 + ...mespaceslistauthorizationrules_autorest.go | 186 + .../method_namespaceslistkeys_autorest.go | 68 + ...ethod_namespacesregeneratekeys_autorest.go | 69 + .../model_accesskeys.go | 14 + .../model_regenerateaccesskeyparameters.go | 9 + .../model_sbauthorizationrule.go | 16 + .../model_sbauthorizationruleproperties.go | 8 + .../namespacesauthorizationrule/predicates.go | 24 + .../namespacesauthorizationrule/version.go | 12 + .../2021-06-01-preview/queues/README.md | 90 + .../2021-06-01-preview/queues/client.go | 18 + .../2021-06-01-preview/queues/constants.go | 55 + .../2021-06-01-preview/queues/id_namespace.go | 124 + .../2021-06-01-preview/queues/id_queue.go | 137 + .../queues/method_createorupdate_autorest.go | 68 + .../queues/method_delete_autorest.go | 65 + .../queues/method_get_autorest.go | 67 + .../queues/method_listbynamespace_autorest.go | 220 + .../queues/model_messagecountdetails.go | 12 + .../queues/model_sbqueue.go | 16 + .../queues/model_sbqueueproperties.go | 71 + .../2021-06-01-preview/queues/predicates.go | 24 + .../2021-06-01-preview/queues/version.go | 12 + .../queuesauthorizationrule/README.md | 127 + .../queuesauthorizationrule/client.go | 18 + .../queuesauthorizationrule/constants.go | 65 + .../queuesauthorizationrule/id_queue.go | 137 + .../id_queueauthorizationrule.go | 150 + ...reateorupdateauthorizationrule_autorest.go | 68 + ..._queuesdeleteauthorizationrule_autorest.go | 65 + ...hod_queuesgetauthorizationrule_autorest.go | 67 + ...d_queueslistauthorizationrules_autorest.go | 186 + .../method_queueslistkeys_autorest.go | 68 + .../method_queuesregeneratekeys_autorest.go | 69 + .../model_accesskeys.go | 14 + .../model_regenerateaccesskeyparameters.go | 9 + .../model_sbauthorizationrule.go | 16 + .../model_sbauthorizationruleproperties.go | 8 + .../queuesauthorizationrule/predicates.go | 24 + .../queuesauthorizationrule/version.go | 12 + .../2021-06-01-preview/rules/README.md | 74 + .../2021-06-01-preview/rules/client.go | 18 + .../2021-06-01-preview/rules/constants.go | 34 + .../2021-06-01-preview/rules/id_rule.go | 163 + .../rules/id_subscriptions2.go | 150 + .../rules/method_createorupdate_autorest.go | 68 + .../rules/method_delete_autorest.go | 65 + .../method_listbysubscriptions_autorest.go | 220 + .../2021-06-01-preview/rules/model_action.go | 10 + .../rules/model_correlationfilter.go | 17 + .../2021-06-01-preview/rules/model_rule.go | 16 + .../rules/model_ruleproperties.go | 11 + .../rules/model_sqlfilter.go | 10 + .../2021-06-01-preview/rules/predicates.go | 24 + .../2021-06-01-preview/rules/version.go | 12 + .../subscriptions/README.md | 106 + .../subscriptions/client.go | 18 + .../subscriptions/constants.go | 83 + .../subscriptions/id_rule.go | 163 + .../subscriptions/id_subscriptions2.go | 150 + .../subscriptions/id_topic.go | 137 + .../method_createorupdate_autorest.go | 68 + .../subscriptions/method_delete_autorest.go | 65 + .../subscriptions/method_get_autorest.go | 67 + .../method_listbytopic_autorest.go | 220 + .../subscriptions/method_rulesget_autorest.go | 67 + .../subscriptions/model_action.go | 10 + .../subscriptions/model_correlationfilter.go | 17 + .../model_messagecountdetails.go | 12 + .../subscriptions/model_rule.go | 16 + .../subscriptions/model_ruleproperties.go | 11 + .../model_sbclientaffineproperties.go | 10 + .../subscriptions/model_sbsubscription.go | 16 + .../model_sbsubscriptionproperties.go | 68 + .../subscriptions/model_sqlfilter.go | 10 + .../subscriptions/predicates.go | 24 + .../subscriptions/version.go | 12 + .../2021-06-01-preview/topics/README.md | 90 + .../2021-06-01-preview/topics/client.go | 18 + .../2021-06-01-preview/topics/constants.go | 55 + .../2021-06-01-preview/topics/id_namespace.go | 124 + .../2021-06-01-preview/topics/id_topic.go | 137 + .../topics/method_createorupdate_autorest.go | 68 + .../topics/method_delete_autorest.go | 65 + .../topics/method_get_autorest.go | 67 + .../topics/method_listbynamespace_autorest.go | 220 + .../topics/model_messagecountdetails.go | 12 + .../topics/model_sbtopic.go | 16 + .../topics/model_sbtopicproperties.go | 66 + .../2021-06-01-preview/topics/predicates.go | 24 + .../2021-06-01-preview/topics/version.go | 12 + .../topicsauthorizationrule/README.md | 127 + .../topicsauthorizationrule/client.go | 18 + .../topicsauthorizationrule/constants.go | 65 + .../topicsauthorizationrule/id_topic.go | 137 + .../id_topicauthorizationrule.go | 150 + ...reateorupdateauthorizationrule_autorest.go | 68 + ..._topicsdeleteauthorizationrule_autorest.go | 65 + ...hod_topicsgetauthorizationrule_autorest.go | 67 + ...d_topicslistauthorizationrules_autorest.go | 186 + .../method_topicslistkeys_autorest.go | 68 + .../method_topicsregeneratekeys_autorest.go | 69 + .../model_accesskeys.go | 14 + .../model_regenerateaccesskeyparameters.go | 9 + .../model_sbauthorizationrule.go | 16 + .../model_sbauthorizationruleproperties.go | 8 + .../topicsauthorizationrule/predicates.go | 24 + .../topicsauthorizationrule/version.go | 12 + .../signalr/2022-02-01/signalr/README.md | 488 + .../signalr/2022-02-01/signalr/client.go | 18 + .../signalr/2022-02-01/signalr/constants.go | 374 + .../signalr/id_customcertificate.go | 137 + .../2022-02-01/signalr/id_customdomain.go | 137 + .../signalr/2022-02-01/signalr/id_location.go | 111 + .../signalr/id_privateendpointconnection.go | 137 + .../signalr/id_sharedprivatelinkresource.go | 137 + .../signalr/2022-02-01/signalr/id_signalr.go | 124 + .../method_checknameavailability_autorest.go | 69 + .../signalr/method_createorupdate_autorest.go | 79 + ...stomcertificatescreateorupdate_autorest.go | 79 + ...ethod_customcertificatesdelete_autorest.go | 65 + .../method_customcertificatesget_autorest.go | 67 + .../method_customcertificateslist_autorest.go | 186 + ...od_customdomainscreateorupdate_autorest.go | 79 + .../method_customdomainsdelete_autorest.go | 78 + .../method_customdomainsget_autorest.go | 67 + .../method_customdomainslist_autorest.go | 186 + .../signalr/method_delete_autorest.go | 78 + .../2022-02-01/signalr/method_get_autorest.go | 67 + .../method_listbyresourcegroup_autorest.go | 187 + .../method_listbysubscription_autorest.go | 187 + .../signalr/method_listkeys_autorest.go | 68 + .../signalr/method_listskus_autorest.go | 68 + ...ivateendpointconnectionsdelete_autorest.go | 78 + ..._privateendpointconnectionsget_autorest.go | 67 + ...privateendpointconnectionslist_autorest.go | 186 + ...ivateendpointconnectionsupdate_autorest.go | 68 + ...ethod_privatelinkresourceslist_autorest.go | 186 + .../signalr/method_regeneratekey_autorest.go | 79 + .../signalr/method_restart_autorest.go | 78 + ...atelinkresourcescreateorupdate_autorest.go | 79 + ...aredprivatelinkresourcesdelete_autorest.go | 78 + ..._sharedprivatelinkresourcesget_autorest.go | 67 + ...sharedprivatelinkresourceslist_autorest.go | 186 + .../signalr/method_update_autorest.go | 79 + .../signalr/method_usageslist_autorest.go | 186 + .../signalr/model_customcertificate.go | 16 + .../model_customcertificateproperties.go | 11 + .../2022-02-01/signalr/model_customdomain.go | 16 + .../signalr/model_customdomainproperties.go | 10 + .../signalr/model_livetracecategory.go | 9 + .../signalr/model_livetraceconfiguration.go | 9 + .../signalr/model_managedidentitysettings.go | 8 + .../signalr/model_nameavailability.go | 10 + .../model_nameavailabilityparameters.go | 9 + .../2022-02-01/signalr/model_networkacl.go | 9 + .../signalr/model_privateendpoint.go | 8 + .../signalr/model_privateendpointacl.go | 10 + .../model_privateendpointconnection.go | 16 + ...del_privateendpointconnectionproperties.go | 11 + .../signalr/model_privatelinkresource.go | 11 + .../model_privatelinkresourceproperties.go | 11 + ...model_privatelinkserviceconnectionstate.go | 10 + .../signalr/model_regeneratekeyparameters.go | 8 + .../signalr/model_resourcelogcategory.go | 9 + .../signalr/model_resourcelogconfiguration.go | 8 + .../signalr/model_resourcereference.go | 8 + .../2022-02-01/signalr/model_resourcesku.go | 12 + .../model_serverlessupstreamsettings.go | 8 + ..._shareableprivatelinkresourceproperties.go | 10 + .../model_shareableprivatelinkresourcetype.go | 9 + .../model_sharedprivatelinkresource.go | 16 + ...del_sharedprivatelinkresourceproperties.go | 12 + .../signalr/model_signalrcorssettings.go | 8 + .../signalr/model_signalrfeature.go | 10 + .../2022-02-01/signalr/model_signalrkeys.go | 11 + .../signalr/model_signalrnetworkacls.go | 10 + .../signalr/model_signalrproperties.go | 26 + .../signalr/model_signalrresource.go | 22 + .../signalr/model_signalrtlssettings.go | 8 + .../2022-02-01/signalr/model_signalrusage.go | 12 + .../signalr/model_signalrusagename.go | 9 + .../signalr/2022-02-01/signalr/model_sku.go | 10 + .../2022-02-01/signalr/model_skucapacity.go | 12 + .../2022-02-01/signalr/model_skulist.go | 9 + .../signalr/model_upstreamauthsettings.go | 9 + .../signalr/model_upstreamtemplate.go | 12 + .../signalr/2022-02-01/signalr/predicates.go | 172 + .../signalr/2022-02-01/signalr/version.go | 12 + .../objectreplicationpolicies/README.md | 89 + .../objectreplicationpolicies/client.go | 18 + .../id_objectreplicationpolicies.go | 137 + .../id_storageaccount.go | 124 + .../method_createorupdate_autorest.go | 68 + .../method_delete_autorest.go | 65 + .../method_get_autorest.go | 67 + .../method_list_autorest.go | 68 + .../model_objectreplicationpolicies.go | 8 + .../model_objectreplicationpolicy.go | 11 + .../model_objectreplicationpolicyfilter.go | 9 + ...model_objectreplicationpolicyproperties.go | 30 + .../model_objectreplicationpolicyrule.go | 11 + .../objectreplicationpolicies/version.go | 12 + .../github.com/hashicorp/go-hclog/README.md | 12 +- .../hashicorp/go-hclog/colorize_unix.go | 2 + .../hashicorp/go-hclog/colorize_windows.go | 7 +- .../github.com/hashicorp/go-hclog/global.go | 2 + .../hashicorp/go-hclog/interceptlogger.go | 7 +- .../hashicorp/go-hclog/intlogger.go | 64 +- .../github.com/hashicorp/go-hclog/logger.go | 24 + .../github.com/hashicorp/go-hclog/stdlog.go | 23 +- .../github.com/hashicorp/go-plugin/README.md | 5 +- .../github.com/hashicorp/go-plugin/client.go | 15 +- .../hashicorp/go-plugin/process_posix.go | 1 + .../hashicorp/go-plugin/process_windows.go | 1 + .../hashicorp/go-plugin/rpc_server.go | 6 +- .../github.com/hashicorp/go-plugin/server.go | 6 +- vendor/github.com/hashicorp/go-uuid/LICENSE | 2 + .../hashicorp/go-version/CHANGELOG.md | 15 +- .../github.com/hashicorp/go-version/README.md | 2 +- .../hashicorp/go-version/constraint.go | 6 + .../hashicorp/go-version/version.go | 17 + .../github.com/hashicorp/hc-install/README.md | 2 +- .../hashicorp/hc-install/fs/version.go | 97 + .../hashicorp/hc-install/product/vault.go | 54 + .../github.com/hashicorp/hcl/v2/CHANGELOG.md | 47 + .../github.com/hashicorp/hcl/v2/diagnostic.go | 43 + .../hashicorp/hcl/v2/diagnostic_typeparams.go | 39 + .../hashicorp/hcl/v2/hclsyntax/expression.go | 282 +- .../hcl/v2/hclsyntax/expression_template.go | 16 +- .../hashicorp/hcl/v2/hclsyntax/parser.go | 161 +- .../hcl/v2/hclsyntax/parser_template.go | 34 +- .../hashicorp/hcl/v2/hclsyntax/spec.md | 20 +- .../hashicorp/hcl/v2/hclsyntax/structure.go | 15 +- .../hashicorp/hcl/v2/hclsyntax/token.go | 26 +- vendor/github.com/hashicorp/hcl/v2/ops.go | 166 +- .../internal/version/version.go | 2 +- .../hashicorp/terraform-exec/tfexec/cmd.go | 54 +- .../terraform-exec/tfexec/cmd_default.go | 72 +- .../terraform-exec/tfexec/cmd_linux.go | 74 +- .../terraform-exec/tfexec/exit_errors.go | 35 +- .../terraform-exec/tfexec/force_unlock.go | 50 + .../hashicorp/terraform-exec/tfexec/graph.go | 85 + .../terraform-exec/tfexec/options.go | 54 +- .../terraform-exec/tfexec/state_pull.go | 55 + .../terraform-exec/tfexec/state_push.go | 67 + .../hashicorp/terraform-exec/tfexec/taint.go | 78 + .../terraform-exec/tfexec/terraform.go | 71 +- .../terraform-exec/tfexec/untaint.go | 78 + .../terraform-exec/tfexec/version.go | 5 + .../terraform-exec/tfexec/workspace_delete.go | 81 + .../terraform-exec/tfexec/workspace_show.go | 35 + .../hashicorp/terraform-json/config.go | 3 + .../hashicorp/terraform-json/plan.go | 13 + .../hashicorp/terraform-json/schemas.go | 7 + .../hashicorp/terraform-json/state.go | 28 + .../internal/logging/context.go | 89 + .../internal/logging/doc.go | 2 + .../internal/logging/environment_variables.go | 22 + .../internal/logging/keys.go | 53 + .../internal/logging/protocol.go | 27 + .../internal/logging/protocol_data.go | 108 + .../internal/logging/provider.go | 18 + .../tfprotov5/internal/diag/diagnostics.go | 82 + .../tfprotov5/internal/diag/doc.go | 3 + .../internal/tf5serverlogging/context_keys.go | 8 + .../internal/tf5serverlogging/doc.go | 3 + .../tf5serverlogging/downstream_request.go | 40 + .../internal/tfplugin5/tfplugin5.pb.go | 9 +- .../internal/tfplugin5/tfplugin5_grpc.pb.go | 25 +- .../terraform-plugin-go/tfprotov5/resource.go | 20 + .../terraform-plugin-go/tfprotov5/schema.go | 102 + .../tfprotov5/tf5server/server.go | 585 +- .../tfprotov6/internal/diag/diagnostics.go | 82 + .../tfprotov6/internal/diag/doc.go | 3 + .../tfprotov6/internal/fromproto/resource.go | 6 +- .../tfprotov6/internal/fromproto/schema.go | 4 +- .../internal/tf6serverlogging/context_keys.go | 8 + .../internal/tf6serverlogging/doc.go | 3 + .../tf6serverlogging/downstream_request.go | 40 + .../internal/tfplugin6/tfplugin6.pb.go | 684 +- .../internal/tfplugin6/tfplugin6.proto | 49 +- .../internal/tfplugin6/tfplugin6_grpc.pb.go | 4 + .../tfprotov6/internal/toproto/resource.go | 6 +- .../tfprotov6/internal/toproto/schema.go | 4 +- .../terraform-plugin-go/tfprotov6/resource.go | 17 + .../terraform-plugin-go/tfprotov6/schema.go | 159 +- .../tfprotov6/tf6server/server.go | 582 +- .../tftypes/attribute_path.go | 6 +- .../terraform-plugin-go/tftypes/diff.go | 3 + .../terraform-plugin-go/tftypes/list.go | 21 +- .../terraform-plugin-go/tftypes/map.go | 17 +- .../terraform-plugin-go/tftypes/object.go | 33 +- .../terraform-plugin-go/tftypes/primitive.go | 61 +- .../terraform-plugin-go/tftypes/set.go | 17 +- .../terraform-plugin-go/tftypes/tuple.go | 21 +- .../terraform-plugin-go/tftypes/type.go | 6 + .../terraform-plugin-go/tftypes/value.go | 15 +- .../terraform-plugin-go/tftypes/value_json.go | 32 +- .../tftypes/value_msgpack.go | 40 +- .../internal/hclogutils/args.go | 36 + .../internal/hclogutils/logger_options.go | 29 + .../internal/logging/log.go | 26 + .../internal/logging/options.go | 52 +- .../internal/logging/provider.go | 29 + .../internal/logging/sdk.go | 29 + .../internal/logging/sink.go | 51 + .../terraform-plugin-log/tflog/options.go | 14 + .../terraform-plugin-log/tflog/provider.go | 56 +- .../terraform-plugin-log/tflog/subsystem.go | 122 +- .../terraform-plugin-log/tfsdklog/options.go | 14 + .../terraform-plugin-log/tfsdklog/sdk.go | 102 +- .../terraform-plugin-log/tfsdklog/sink.go | 39 +- .../tfsdklog/subsystem.go | 122 +- .../v2/helper/acctest/random.go | 4 +- .../v2/helper/customdiff/computed.go | 17 +- .../v2/helper/customdiff/condition.go | 6 +- .../v2/helper/customdiff/force_new.go | 37 +- .../v2/helper/customdiff/validate.go | 6 +- .../v2/helper/logging/logging.go | 13 +- .../v2/helper/logging/transport.go | 2 +- .../helper/resource/environment_variables.go | 32 + .../v2/helper/resource/plugin.go | 172 +- .../v2/helper/resource/state_shim.go | 12 +- .../v2/helper/resource/testcase_providers.go | 56 + .../v2/helper/resource/testcase_validate.go | 85 + .../v2/helper/resource/testing.go | 645 +- .../v2/helper/resource/testing_config.go | 13 +- .../v2/helper/resource/testing_new.go | 280 +- .../v2/helper/resource/testing_new_config.go | 183 +- .../resource/testing_new_import_state.go | 89 +- .../v2/helper/resource/testing_sets.go | 160 +- .../v2/helper/resource/teststep_providers.go | 48 + .../v2/helper/resource/teststep_validate.go | 99 + .../v2/helper/schema/field_reader.go | 2 +- .../v2/helper/schema/field_reader_config.go | 6 +- .../v2/helper/schema/field_reader_diff.go | 4 +- .../v2/helper/schema/field_reader_map.go | 9 +- .../v2/helper/schema/field_writer_map.go | 27 +- .../v2/helper/schema/grpc_provider.go | 264 +- .../v2/helper/schema/provider.go | 30 +- .../v2/helper/schema/resource.go | 557 +- .../v2/helper/schema/resource_data.go | 2 +- .../v2/helper/schema/resource_diff.go | 50 +- .../v2/helper/schema/resource_timeout.go | 8 +- .../v2/helper/schema/schema.go | 403 +- .../v2/helper/schema/set.go | 4 +- .../v2/helper/structure/suppress_json_diff.go | 6 +- .../v2/helper/validation/map.go | 12 +- .../v2/helper/validation/meta.go | 17 +- .../v2/helper/validation/strings.go | 4 +- .../v2/helper/validation/testing.go | 30 - .../v2/helper/validation/time.go | 4 +- .../v2/internal/addrs/module_instance.go | 2 - .../v2/internal/configs/hcl2shim/flatmap.go | 6 +- .../v2/internal/logging/context.go | 75 + .../internal/logging/environment_variables.go | 24 + .../v2/internal/logging/helper_resource.go | 32 + .../v2/internal/logging/helper_schema.go | 32 + .../v2/internal/logging/keys.go | 54 + .../v2/internal/plugin/convert/diagnostics.go | 58 +- .../v2/internal/plugin/convert/schema.go | 35 +- .../v2/internal/plugintest/config.go | 22 +- .../plugintest/environment_variables.go | 108 + .../v2/internal/plugintest/guard.go | 47 +- .../v2/internal/plugintest/helper.go | 163 +- .../v2/internal/plugintest/util.go | 27 +- .../v2/internal/plugintest/working_dir.go | 204 +- .../terraform-plugin-sdk/v2/plugin/debug.go | 58 +- .../terraform-plugin-sdk/v2/plugin/serve.go | 182 +- .../terraform-plugin-sdk/v2/terraform/diff.go | 2 +- .../v2/terraform/resource.go | 4 +- .../v2/terraform/state.go | 38 +- .../v2/terraform/state_filter.go | 15 +- .../terraform-registry-address/.go-version | 2 +- .../terraform-registry-address/README.md | 173 +- .../terraform-registry-address/module.go | 251 + .../module_package.go | 58 + .../terraform-registry-address/provider.go | 203 +- .../github.com/mattn/go-colorable/README.md | 2 +- .../mattn/go-colorable/colorable_appengine.go | 1 + .../mattn/go-colorable/colorable_others.go | 4 +- .../mattn/go-colorable/colorable_windows.go | 14 +- .../mattn/go-colorable/noncolorable.go | 12 +- .../github.com/mattn/go-isatty/isatty_bsd.go | 1 + .../mattn/go-isatty/isatty_others.go | 1 + .../mattn/go-isatty/isatty_plan9.go | 1 + .../mattn/go-isatty/isatty_solaris.go | 4 +- .../mattn/go-isatty/isatty_tcgets.go | 1 + .../mattn/go-isatty/isatty_windows.go | 6 +- .../mitchellh/mapstructure/CHANGELOG.md | 27 +- .../mitchellh/mapstructure/decode_hooks.go | 25 +- .../mitchellh/mapstructure/mapstructure.go | 104 +- .../vmihailenco/msgpack/v4/.golangci.yml | 12 + .../vmihailenco/msgpack/v4/.travis.yml | 21 + .../vmihailenco/msgpack/v4/CHANGELOG.md | 24 + .../github.com/vmihailenco/msgpack/v4/LICENSE | 25 + .../vmihailenco/msgpack/v4/Makefile | 6 + .../vmihailenco/msgpack/v4/README.md | 72 + .../vmihailenco/msgpack/v4/appengine.go | 64 + .../vmihailenco/msgpack/v4/codes/codes.go | 90 + .../vmihailenco/msgpack/v4/decode.go | 617 ++ .../vmihailenco/msgpack/v4/decode_map.go | 350 + .../vmihailenco/msgpack/v4/decode_number.go | 307 + .../vmihailenco/msgpack/v4/decode_query.go | 158 + .../vmihailenco/msgpack/v4/decode_slice.go | 191 + .../vmihailenco/msgpack/v4/decode_string.go | 186 + .../vmihailenco/msgpack/v4/decode_value.go | 276 + .../vmihailenco/msgpack/v4/encode.go | 241 + .../vmihailenco/msgpack/v4/encode_map.go | 172 + .../vmihailenco/msgpack/v4/encode_number.go | 244 + .../vmihailenco/msgpack/v4/encode_slice.go | 131 + .../vmihailenco/msgpack/v4/encode_value.go | 216 + .../github.com/vmihailenco/msgpack/v4/ext.go | 244 + .../vmihailenco/msgpack/v4/intern.go | 236 + .../vmihailenco/msgpack/v4/msgpack.go | 17 + .../github.com/vmihailenco/msgpack/v4/safe.go | 13 + .../github.com/vmihailenco/msgpack/v4/time.go | 149 + .../vmihailenco/msgpack/v4/types.go | 382 + .../vmihailenco/msgpack/v4/unsafe.go | 22 + .../vmihailenco/tagparser/.travis.yml | 24 + .../github.com/vmihailenco/tagparser/LICENSE | 25 + .../github.com/vmihailenco/tagparser/Makefile | 8 + .../vmihailenco/tagparser/README.md | 24 + .../tagparser/internal/parser/parser.go | 82 + .../vmihailenco/tagparser/internal/safe.go | 11 + .../vmihailenco/tagparser/internal/unsafe.go | 22 + .../vmihailenco/tagparser/tagparser.go | 176 + .../zclconf/go-cty/cty/primitive_type.go | 45 + .../zclconf/go-cty/cty/value_ops.go | 2 +- vendor/golang.org/x/crypto/ssh/certs.go | 2 + vendor/google.golang.org/grpc/CONTRIBUTING.md | 7 +- vendor/google.golang.org/grpc/MAINTAINERS.md | 5 +- vendor/google.golang.org/grpc/Makefile | 2 - vendor/google.golang.org/grpc/NOTICE.txt | 13 + .../grpc/attributes/attributes.go | 80 +- .../grpc/balancer/balancer.go | 100 +- .../grpc/balancer/base/balancer.go | 80 +- .../grpc/balancer/grpclb/state/state.go | 2 +- .../grpc/balancer/roundrobin/roundrobin.go | 4 +- .../grpc/balancer_conn_wrappers.go | 315 +- .../grpc/channelz/channelz.go | 36 + vendor/google.golang.org/grpc/clientconn.go | 878 +- .../grpc/connectivity/connectivity.go | 35 +- .../grpc/credentials/credentials.go | 25 +- .../grpc/credentials/insecure/insecure.go | 98 + .../google.golang.org/grpc/credentials/tls.go | 3 + vendor/google.golang.org/grpc/dialoptions.go | 101 +- .../grpc/encoding/encoding.go | 2 +- .../grpc/grpclog/loggerv2.go | 94 +- .../health/grpc_health_v1/health_grpc.pb.go | 2 +- vendor/google.golang.org/grpc/interceptor.go | 9 +- .../balancer/gracefulswitch/gracefulswitch.go | 382 + .../grpc/internal/binarylog/binarylog.go | 91 +- .../grpc/internal/binarylog/env_config.go | 6 +- .../grpc/internal/binarylog/method_logger.go | 26 +- .../grpc/internal/binarylog/sink.go | 41 +- .../grpc/internal/channelz/funcs.go | 240 +- .../grpc/internal/channelz/id.go | 75 + .../grpc/internal/channelz/logging.go | 91 +- .../grpc/internal/channelz/types.go | 23 +- .../grpc/internal/channelz/types_linux.go | 2 - .../grpc/internal/channelz/types_nonlinux.go | 5 +- .../grpc/internal/channelz/util_linux.go | 2 - .../grpc/internal/channelz/util_nonlinux.go | 3 +- .../grpc/internal/credentials/spiffe.go | 2 - .../grpc/internal/credentials/syscallconn.go | 2 - .../grpc/internal/credentials/util.go | 4 +- .../grpc/internal/envconfig/envconfig.go | 3 - .../grpc/internal/envconfig/xds.go | 101 + .../grpc/internal/grpclog/grpclog.go | 8 +- .../grpc/internal/grpcrand/grpcrand.go | 7 + .../grpc/internal/grpcutil/grpcutil.go | 20 + .../grpc/internal/grpcutil/regex.go | 31 + .../grpc/internal/internal.go | 13 +- .../grpc/internal/metadata/metadata.go | 76 +- .../grpc/internal/pretty/pretty.go | 82 + .../grpc/internal/resolver/config_selector.go | 9 +- .../internal/resolver/dns/dns_resolver.go | 9 +- .../grpc/internal/resolver/unix/unix.go | 12 +- .../internal/serviceconfig/serviceconfig.go | 4 +- .../grpc/internal/status/status.go | 14 +- .../grpc/internal/syscall/syscall_linux.go | 2 - .../grpc/internal/syscall/syscall_nonlinux.go | 21 +- .../grpc/internal/transport/controlbuf.go | 14 +- .../grpc/internal/transport/flowcontrol.go | 4 +- .../grpc/internal/transport/http2_client.go | 235 +- .../grpc/internal/transport/http2_server.go | 216 +- .../grpc/internal/transport/http_util.go | 20 - .../transport/networktype/networktype.go | 2 +- .../grpc/internal/transport/proxy.go | 4 +- .../grpc/internal/transport/transport.go | 15 +- .../grpc/internal/xds_handshake_cluster.go | 2 +- .../grpc/metadata/metadata.go | 15 +- .../google.golang.org/grpc/picker_wrapper.go | 12 +- vendor/google.golang.org/grpc/pickfirst.go | 135 +- .../reflection_grpc.pb.go | 2 +- .../grpc/reflection/serverreflection.go | 416 +- vendor/google.golang.org/grpc/regenerate.sh | 34 +- vendor/google.golang.org/grpc/resolver/map.go | 109 + .../grpc/resolver/resolver.go | 62 +- .../grpc/resolver_conn_wrapper.go | 23 +- vendor/google.golang.org/grpc/rpc_util.go | 40 +- vendor/google.golang.org/grpc/server.go | 205 +- .../google.golang.org/grpc/service_config.go | 5 +- vendor/google.golang.org/grpc/stats/stats.go | 11 +- .../google.golang.org/grpc/status/status.go | 34 +- vendor/google.golang.org/grpc/stream.go | 329 +- vendor/google.golang.org/grpc/version.go | 2 +- vendor/google.golang.org/grpc/vet.sh | 6 +- .../protobuf/encoding/protojson/decode.go | 665 ++ .../protobuf/encoding/protojson/doc.go | 11 + .../protobuf/encoding/protojson/encode.go | 344 + .../encoding/protojson/well_known_types.go | 889 ++ .../protobuf/encoding/protowire/wire.go | 19 +- .../protobuf/internal/encoding/json/decode.go | 340 + .../internal/encoding/json/decode_number.go | 254 + .../internal/encoding/json/decode_string.go | 91 + .../internal/encoding/json/decode_token.go | 192 + .../protobuf/internal/encoding/json/encode.go | 276 + .../protobuf/internal/encoding/text/decode.go | 2 +- .../protobuf/internal/errors/is_go112.go | 1 + .../protobuf/internal/errors/is_go113.go | 1 + .../internal/flags/proto_legacy_disable.go | 1 + .../internal/flags/proto_legacy_enable.go | 1 + .../protobuf/internal/impl/codec_map_go111.go | 1 + .../protobuf/internal/impl/codec_map_go112.go | 1 + .../protobuf/internal/impl/codec_reflect.go | 1 + .../protobuf/internal/impl/codec_unsafe.go | 1 + .../protobuf/internal/impl/decode.go | 8 + .../protobuf/internal/impl/pointer_reflect.go | 1 + .../protobuf/internal/impl/pointer_unsafe.go | 1 + .../protobuf/internal/strs/strings_pure.go | 1 + .../protobuf/internal/strs/strings_unsafe.go | 1 + .../protobuf/internal/version/version.go | 4 +- .../protobuf/proto/decode.go | 17 +- .../protobuf/proto/proto_methods.go | 1 + .../protobuf/proto/proto_reflect.go | 1 + .../protobuf/reflect/protoreflect/methods.go | 1 + .../reflect/protoreflect/value_pure.go | 1 + .../reflect/protoreflect/value_union.go | 25 + .../reflect/protoreflect/value_unsafe.go | 1 + .../protobuf/runtime/protoiface/methods.go | 1 + vendor/gopkg.in/yaml.v3/parserc.go | 11 +- vendor/modules.txt | 153 +- website/allowed-subcategories | 1 + .../eventhub_authorization_rule.html.markdown | 1 - .../docs/d/kubernetes_cluster.html.markdown | 4 + ...kubernetes_cluster_node_pool.html.markdown | 4 + .../d/lb_backend_address_pool.html.markdown | 14 + ...c_maintenance_configurations.html.markdown | 65 + .../d/storage_management_policy.html.markdown | 6 +- ...pp_service_certificate_order.html.markdown | 2 +- .../docs/r/application_gateway.html.markdown | 5 +- ...n_insights_workbook_template.html.markdown | 146 + .../r/cdn_frontdoor_endpoint.html.markdown | 2 + .../r/cdn_frontdoor_rule_set.html.markdown | 4 +- .../docs/r/cognitive_account.html.markdown | 2 +- website/docs/r/container_group.html.markdown | 2 + ...osmosdb_cassandra_datacenter.html.markdown | 14 +- ...ata_factory_trigger_schedule.html.markdown | 2 +- .../docs/r/databox_edge_order.html.markdown | 2 +- ...rkspace_customer_managed_key.html.markdown | 14 +- .../docs/r/fluid_relay_servers.html.markdown | 91 + .../docs/r/gallery_application.html.markdown | 82 + .../gallery_application_version.html.markdown | 152 + .../r/hdinsight_kafka_cluster.html.markdown | 12 + ...eries_insights_access_policy.html.markdown | 2 +- ...nsights_standard_environment.html.markdown | 2 +- .../docs/r/kubernetes_cluster.html.markdown | 4 +- ...kubernetes_cluster_node_pool.html.markdown | 4 +- website/docs/r/kusto_cluster.html.markdown | 2 + ...to_eventgrid_data_connection.html.markdown | 8 +- ...sto_eventhub_data_connection.html.markdown | 3 +- ...kusto_iothub_data_connection.html.markdown | 2 + website/docs/r/kusto_script.html.markdown | 10 +- .../r/lb_backend_address_pool.html.markdown | 2 + ...backend_address_pool_address.html.markdown | 12 + website/docs/r/lb_nat_rule.html.markdown | 25 +- .../r/linux_virtual_machine.html.markdown | 4 + ...ux_virtual_machine_scale_set.html.markdown | 10 +- website/docs/r/linux_web_app.html.markdown | 2 + website/docs/r/logz_sub_account.html.markdown | 104 + website/docs/r/managed_disk.html.markdown | 2 +- ...ement_group_policy_exemption.html.markdown | 86 + ...ent_group_policy_remediation.html.markdown | 80 + .../docs/r/media_live_output.html.markdown | 2 +- website/docs/r/mssql_database.html.markdown | 14 - ...aged_instance_failover_group.html.markdown | 2 - .../r/netapp_snapshot_policy.html.markdown | 2 +- ...ed_virtual_machine_scale_set.html.markdown | 84 +- ...lexible_server_configuration.html.markdown | 34 + ...ource_group_policy_exemption.html.markdown | 87 + ...rce_group_policy_remediation.html.markdown | 107 + .../r/resource_policy_exemption.html.markdown | 94 + .../resource_policy_remediation.html.markdown | 97 + website/docs/r/servicebus_queue.html.markdown | 2 +- website/docs/r/shared_image.html.markdown | 12 + website/docs/r/signalr_service.html.markdown | 14 + ...pring_cloud_build_deployment.html.markdown | 2 + ...g_cloud_container_deployment.html.markdown | 6 +- ...stream_analytics_output_blob.html.markdown | 6 +- ...ubscription_policy_exemption.html.markdown | 84 + ...scription_policy_remediation.html.markdown | 78 + ...se_integration_runtime_azure.html.markdown | 2 +- ...affic_manager_azure_endpoint.html.markdown | 2 +- ...ic_manager_external_endpoint.html.markdown | 3 +- ...ffic_manager_nested_endpoint.html.markdown | 3 +- .../r/windows_virtual_machine.html.markdown | 4 + ...ws_virtual_machine_scale_set.html.markdown | 10 +- website/docs/r/windows_web_app.html.markdown | 2 + 1624 files changed, 119427 insertions(+), 8593 deletions(-) create mode 100644 internal/services/applicationinsights/application_insights_workbook_template_resource.go create mode 100644 internal/services/applicationinsights/application_insights_workbook_template_resource_test.go create mode 100644 internal/services/compute/gallery_application_resource.go create mode 100644 internal/services/compute/gallery_application_resource_test.go create mode 100644 internal/services/compute/gallery_application_version_resource.go create mode 100644 internal/services/compute/gallery_application_version_resource_test.go create mode 100644 internal/services/compute/orchestrated_virtual_machine_scale_set_disk_os_resource_test.go create mode 100644 internal/services/compute/parse/gallery_application.go create mode 100644 internal/services/compute/parse/gallery_application_test.go create mode 100644 internal/services/compute/parse/gallery_application_version.go create mode 100644 internal/services/compute/parse/gallery_application_version_test.go create mode 100644 internal/services/compute/validate/gallery_application_id.go create mode 100644 internal/services/compute/validate/gallery_application_id_test.go create mode 100644 internal/services/compute/validate/gallery_application_version_id.go create mode 100644 internal/services/compute/validate/gallery_application_version_id_test.go create mode 100644 internal/services/databricks/migration/customer_managed_key.go create mode 100644 internal/services/eventhub/migration/eventhub_authorization_rule.go create mode 100644 internal/services/firewall/testdata/openssl.cnf create mode 100644 internal/services/fluidrelay/client/client.go create mode 100644 internal/services/fluidrelay/fluid_relay_servers_resource.go create mode 100644 internal/services/fluidrelay/fluid_relay_servers_resource_test.go create mode 100644 internal/services/fluidrelay/parse/fluid_relay.go create mode 100644 internal/services/fluidrelay/parse/fluid_relay_servers.go create mode 100644 internal/services/fluidrelay/parse/fluid_relay_servers_test.go create mode 100644 internal/services/fluidrelay/parse/fluid_relay_test.go create mode 100644 internal/services/fluidrelay/registration.go create mode 100644 internal/services/fluidrelay/resourceids.go create mode 100644 internal/services/fluidrelay/validate/fluid_relay_servers_id.go create mode 100644 internal/services/fluidrelay/validate/fluid_relay_servers_id_test.go create mode 100644 internal/services/fluidrelay/validate/server_name.go create mode 100644 internal/services/fluidrelay/validate/server_name_test.go create mode 100644 internal/services/logz/logz_common.go create mode 100644 internal/services/logz/logz_sub_account_resource.go create mode 100644 internal/services/logz/logz_sub_account_resource_test.go create mode 100644 internal/services/logz/parse/logz_sub_account.go create mode 100644 internal/services/logz/parse/logz_sub_account_test.go create mode 100644 internal/services/logz/validate/logz_monitor_name.go create mode 100644 internal/services/logz/validate/logz_sub_account_id.go create mode 100644 internal/services/logz/validate/logz_sub_account_id_test.go create mode 100644 internal/services/maintenance/public_maintenance_configurations_data_source.go create mode 100644 internal/services/maintenance/public_maintenance_configurations_data_source_test.go create mode 100644 internal/services/servicebus/transition.go create mode 100644 test/main.tf create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/CHANGELOG.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/_meta.json create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/attacheddatabaseconfigurations.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/clusterprincipalassignments.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/clusters.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/databaseprincipalassignments.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/databases.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/dataconnections.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/enums.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/managedprivateendpoints.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operations.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operationsresults.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operationsresultslocation.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/privateendpointconnections.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/privatelinkresources.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/scripts.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/version.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/CHANGELOG.md create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/_meta.json create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apiportalcustomdomains.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apiportals.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apps.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/bindings.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildpackbinding.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildservice.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildserviceagentpool.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildservicebuilder.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/certificates.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/configservers.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/configurationservices.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/customdomains.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/deployments.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/enums.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gatewaycustomdomains.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gatewayrouteconfigs.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gateways.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/monitoringsettings.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/operations.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/runtimeversions.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/serviceregistries.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/services.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/skus.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/storages.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/version.go create mode 100644 vendor/github.com/golang/protobuf/jsonpb/decode.go create mode 100644 vendor/github.com/golang/protobuf/jsonpb/encode.go create mode 100644 vendor/github.com/golang/protobuf/jsonpb/json.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/id_configurationstore.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_create_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_listbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_listkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_regeneratekey_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_apikey.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstore.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstoreproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstorepropertiesupdateparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstoreupdateparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_encryptionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_keyvaultproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpoint.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpointconnectionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpointconnectionreference.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privatelinkserviceconnectionstate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_regeneratekeyparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_sku.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/id_workbooktemplate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatescreateorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplateslistbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplategallery.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplatelocalizedgallery.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateslistresult.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateupdateparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/id_availabilityset.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_listavailablesizes_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_listbysubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilityset.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilitysetproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilitysetupdate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_instanceviewstatus.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_sku.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_subresource.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_virtualmachinesize.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_virtualmachinesizelistresult.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/id_sshpublickey.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_create_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_generatekeypair_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_listbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_listbysubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeygeneratekeypairresult.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyresource.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyresourceproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyupdateresource.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_container.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_containergroup.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_location.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupscreateorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupslistbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsrestart_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsstart_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsstop_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containersattach_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containersexecutecommand_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containerslistlogs_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistcachedimages_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistcapabilities_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistusage_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_azurefilevolume.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_cachedimages.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_capabilities.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_capabilitiescapabilities.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_container.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerattachresponse.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexec.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecrequest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecrequestterminalsize.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecresponse.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroup.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupdiagnostics.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupnetworkprofile.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergrouppropertiesinstanceview.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerhttpget.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerport.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerprobe.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerpropertiesinstanceview.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerstate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_dnsconfiguration.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_encryptionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_environmentvariable.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_event.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_gitrepovolume.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_gpuresource.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_httpheader.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_imageregistrycredential.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerdefinition.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerpropertiesdefinition.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerpropertiesdefinitioninstanceview.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_ipaddress.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_loganalytics.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_logs.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_port.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resource.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcelimits.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcerequests.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcerequirements.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usage.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usagelistresult.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usagename.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_volume.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_volumemount.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/id_workspace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_listbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_listbysubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_createdby.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryption.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionentitiesdefinition.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionv2.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionv2keyvaultproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_managedidentityconfiguration.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpoint.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpointconnection.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpointconnectionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privatelinkserviceconnectionstate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_sku.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustombooleanparameter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomobjectparameter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomstringparameter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceencryptionparameter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacepropertiesencryption.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceproviderauthorization.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceupdate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/id_eventhub.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/id_eventhubauthorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubscreateorupdateauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubslistauthorizationrules_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubslistkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubsregeneratekeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_accesskeys.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_authorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_authorizationruleproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_regenerateaccesskeyparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/id_authorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacescreateorupdateauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesdeleteauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesgetauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespaceslistauthorizationrules_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespaceslistkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesregeneratekeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_accesskeys.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_authorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_authorizationruleproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_regenerateaccesskeyparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/model_checknameavailabilityparameter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/model_checknameavailabilityresult.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/id_consumergroup.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/id_eventhub.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_listbyeventhub_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/model_consumergroup.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/model_consumergroupproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/id_disasterrecoveryconfig.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_breakpairing_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_failover_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/model_armdisasterrecovery.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/model_armdisasterrecoveryproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_eventhub.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_eventhubauthorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_deleteauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_getauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_listbynamespace_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_authorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_authorizationruleproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_capturedescription.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_destination.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_destinationproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_eventhub.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_eventhubproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/id_cluster.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clusterscreateorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clusterslistbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_cluster.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_clusterproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_clustersku.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/method_namespacescreateorupdatenetworkruleset_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/method_namespacesgetnetworkruleset_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_networkruleset.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_networkrulesetproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_nwrulesetiprules.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_nwrulesetvirtualnetworkrules.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_subnet.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_listbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_connectionstate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_ehnamespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_ehnamespaceproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_encryption.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_keyvaultproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpoint.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpointconnection.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpointconnectionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_sku.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_userassignedidentityproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/id_fluidrelayserver.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_getkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listbysubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_regeneratekey_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_customermanagedkeyencryptionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_customermanagedkeyencryptionpropertieskeyencryptionkeyidentity.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_encryptionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayendpoints.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserver.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverkeys.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverupdate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverupdateproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_regeneratekeyrequest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/id_scopedregistrationassignment.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_authorization.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_plan.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignment.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentpropertiesregistrationdefinition.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/id_scopedregistrationdefinition.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_authorization.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_plan.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_registrationdefinition.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_registrationdefinitionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/id_capacitypool.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/id_netappaccount.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolscreateorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_capacitypool.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_capacitypoolpatch.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_poolpatchproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_poolproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/id_netappaccount.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountscreateorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountslistbysubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_accountencryption.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_accountproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_activedirectory.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_ldapsearchscopeopt.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_netappaccount.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_netappaccountpatch.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/id_netappaccount.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/id_snapshotpolicies.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciescreate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpolicieslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_dailyschedule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_hourlyschedule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_monthlyschedule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicieslist.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicy.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicypatch.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicyproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_weeklyschedule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/id_snapshot.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/id_volume.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_create_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_restorefiles_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshot.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotrestorefiles.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotslist.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/id_capacitypool.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/id_volume.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_exportpolicyrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_mounttargetproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_placementkeyvaluepairs.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_replicationobject.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volume.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumebackupproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatch.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchpropertiesdataprotection.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchpropertiesexportpolicy.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumeproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepropertiesdataprotection.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepropertiesexportpolicy.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumesnapshotproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/id_volume.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesauthorizereplication_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesbreakreplication_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesdeletereplication_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesreinitializereplication_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesreplicationstatus_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesresyncreplication_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_authorizerequest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_breakreplicationrequest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_replicationstatus.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_managementgroup.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_providerremediation.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_providers2remediation.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_remediation.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_scopedremediation.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatmanagementgroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatresource_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatsubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatmanagementgroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatresource_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatsubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatmanagementgroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatresource_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatsubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatmanagementgroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatresource_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatsubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatmanagementgroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatresource_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatsubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistformanagementgroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforresource_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforsubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_errordefinition.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediation.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationdeployment.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationdeploymentsummary.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationfilters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationpropertiesfailurethreshold.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_typederrorinfo.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_authorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_disasterrecoveryconfig.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_breakpairing_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_checknameavailability_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_failover_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_getauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_listauthorizationrules_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_listkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_accesskeys.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_armdisasterrecovery.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_armdisasterrecoveryproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_checknameavailability.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_checknameavailabilityresult.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_failoverproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_failoverpropertiesproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_sbauthorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_sbauthorizationruleproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_checknameavailability_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_createorupdatenetworkruleset_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_getnetworkruleset_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_listbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_listnetworkrulesets_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_checknameavailability.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_checknameavailabilityresult.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_connectionstate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_encryption.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_keyvaultproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_networkruleset.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_networkrulesetproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_nwrulesetiprules.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_nwrulesetvirtualnetworkrules.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpoint.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpointconnection.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpointconnectionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespaceproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespaceupdateparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbsku.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_subnet.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_userassignedidentityproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/id_authorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacescreateorupdateauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesdeleteauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesgetauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespaceslistauthorizationrules_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespaceslistkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesregeneratekeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_accesskeys.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_regenerateaccesskeyparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_sbauthorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_sbauthorizationruleproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/id_queue.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_listbynamespace_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_messagecountdetails.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_sbqueue.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_sbqueueproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/id_queue.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/id_queueauthorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuescreateorupdateauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesdeleteauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesgetauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queueslistauthorizationrules_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queueslistkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesregeneratekeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_accesskeys.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_regenerateaccesskeyparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_sbauthorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_sbauthorizationruleproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/id_rule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/id_subscriptions2.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_listbysubscriptions_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_action.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_correlationfilter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_rule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_ruleproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_sqlfilter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_rule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_subscriptions2.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_topic.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_listbytopic_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_rulesget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_action.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_correlationfilter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_messagecountdetails.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_rule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_ruleproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbclientaffineproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbsubscription.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbsubscriptionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sqlfilter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/id_namespace.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/id_topic.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_listbynamespace_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_messagecountdetails.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_sbtopic.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_sbtopicproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/id_topic.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/id_topicauthorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicscreateorupdateauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsdeleteauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsgetauthorizationrule_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicslistauthorizationrules_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicslistkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsregeneratekeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_accesskeys.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_regenerateaccesskeyparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_sbauthorizationrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_sbauthorizationruleproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/constants.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_customcertificate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_customdomain.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_location.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_privateendpointconnection.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_sharedprivatelinkresource.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_signalr.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_checknameavailability_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatescreateorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatesdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatesget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificateslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainscreateorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainsdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainsget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listbyresourcegroup_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listbysubscription_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listkeys_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listskus_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privatelinkresourceslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_regeneratekey_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_restart_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcescreateorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcesdelete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcesget_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourceslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_update_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_usageslist_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customcertificate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customcertificateproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customdomain.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customdomainproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_livetracecategory.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_livetraceconfiguration.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_managedidentitysettings.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_nameavailability.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_nameavailabilityparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_networkacl.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpoint.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointacl.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointconnection.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointconnectionproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkresource.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkresourceproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkserviceconnectionstate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_regeneratekeyparameters.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcelogcategory.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcelogconfiguration.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcereference.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcesku.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_serverlessupstreamsettings.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_shareableprivatelinkresourceproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_shareableprivatelinkresourcetype.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sharedprivatelinkresource.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sharedprivatelinkresourceproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrcorssettings.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrfeature.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrkeys.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrnetworkacls.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrresource.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrtlssettings.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrusage.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrusagename.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sku.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_skucapacity.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_skulist.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_upstreamauthsettings.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_upstreamtemplate.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/predicates.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/README.md create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/client.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/id_objectreplicationpolicies.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/id_storageaccount.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_createorupdate_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_delete_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_get_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_list_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicies.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicy.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyfilter.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyproperties.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyrule.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/version.go create mode 100644 vendor/github.com/hashicorp/hc-install/fs/version.go create mode 100644 vendor/github.com/hashicorp/hc-install/product/vault.go create mode 100644 vendor/github.com/hashicorp/hcl/v2/diagnostic_typeparams.go create mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/force_unlock.go create mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/graph.go create mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/state_pull.go create mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/state_push.go create mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/taint.go create mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/untaint.go create mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/workspace_delete.go create mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/workspace_show.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/context.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/doc.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/environment_variables.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/keys.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/protocol.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/protocol_data.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/provider.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag/diagnostics.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag/doc.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/context_keys.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/doc.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/downstream_request.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag/diagnostics.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag/doc.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/context_keys.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/doc.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/downstream_request.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-log/internal/hclogutils/args.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-log/internal/hclogutils/logger_options.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/sink.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/environment_variables.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_providers.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_validate.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_providers.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_validate.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/context.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/environment_variables.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/helper_resource.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/helper_schema.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/keys.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/environment_variables.go create mode 100644 vendor/github.com/hashicorp/terraform-registry-address/module.go create mode 100644 vendor/github.com/hashicorp/terraform-registry-address/module_package.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/.golangci.yml create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/.travis.yml create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/CHANGELOG.md create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/LICENSE create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/Makefile create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/README.md create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/appengine.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/codes/codes.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/decode.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/decode_map.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/decode_number.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/decode_query.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/decode_slice.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/decode_string.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/decode_value.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/encode.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/encode_map.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/encode_number.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/encode_slice.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/encode_value.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/ext.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/intern.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/msgpack.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/safe.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/time.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/types.go create mode 100644 vendor/github.com/vmihailenco/msgpack/v4/unsafe.go create mode 100644 vendor/github.com/vmihailenco/tagparser/.travis.yml create mode 100644 vendor/github.com/vmihailenco/tagparser/LICENSE create mode 100644 vendor/github.com/vmihailenco/tagparser/Makefile create mode 100644 vendor/github.com/vmihailenco/tagparser/README.md create mode 100644 vendor/github.com/vmihailenco/tagparser/internal/parser/parser.go create mode 100644 vendor/github.com/vmihailenco/tagparser/internal/safe.go create mode 100644 vendor/github.com/vmihailenco/tagparser/internal/unsafe.go create mode 100644 vendor/github.com/vmihailenco/tagparser/tagparser.go create mode 100644 vendor/google.golang.org/grpc/NOTICE.txt create mode 100644 vendor/google.golang.org/grpc/channelz/channelz.go create mode 100644 vendor/google.golang.org/grpc/credentials/insecure/insecure.go create mode 100644 vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go create mode 100644 vendor/google.golang.org/grpc/internal/channelz/id.go create mode 100644 vendor/google.golang.org/grpc/internal/envconfig/xds.go create mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/grpcutil.go create mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/regex.go create mode 100644 vendor/google.golang.org/grpc/internal/pretty/pretty.go create mode 100644 vendor/google.golang.org/grpc/resolver/map.go create mode 100644 vendor/google.golang.org/protobuf/encoding/protojson/decode.go create mode 100644 vendor/google.golang.org/protobuf/encoding/protojson/doc.go create mode 100644 vendor/google.golang.org/protobuf/encoding/protojson/encode.go create mode 100644 vendor/google.golang.org/protobuf/encoding/protojson/well_known_types.go create mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/decode.go create mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/decode_number.go create mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/decode_string.go create mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/decode_token.go create mode 100644 vendor/google.golang.org/protobuf/internal/encoding/json/encode.go create mode 100644 website/docs/d/public_maintenance_configurations.html.markdown create mode 100644 website/docs/r/application_insights_workbook_template.html.markdown create mode 100644 website/docs/r/fluid_relay_servers.html.markdown create mode 100644 website/docs/r/gallery_application.html.markdown create mode 100644 website/docs/r/gallery_application_version.html.markdown create mode 100644 website/docs/r/logz_sub_account.html.markdown create mode 100644 website/docs/r/management_group_policy_exemption.html.markdown create mode 100644 website/docs/r/management_group_policy_remediation.html.markdown create mode 100644 website/docs/r/resource_group_policy_exemption.html.markdown create mode 100644 website/docs/r/resource_group_policy_remediation.html.markdown create mode 100644 website/docs/r/resource_policy_exemption.html.markdown create mode 100644 website/docs/r/resource_policy_remediation.html.markdown create mode 100644 website/docs/r/subscription_policy_exemption.html.markdown create mode 100644 website/docs/r/subscription_policy_remediation.html.markdown diff --git a/.teamcity/components/generated/services.kt b/.teamcity/components/generated/services.kt index 1cfc96510486..dc82027890cb 100644 --- a/.teamcity/components/generated/services.kt +++ b/.teamcity/components/generated/services.kt @@ -43,6 +43,7 @@ var services = mapOf( "eventgrid" to "EventGrid", "eventhub" to "EventHub", "firewall" to "Firewall", + "fluidrelay" to "Fluid Relay", "frontdoor" to "FrontDoor", "hdinsight" to "HDInsight", "hpccache" to "HPC Cache", diff --git a/CHANGELOG.md b/CHANGELOG.md index 801fa8d9f075..28134090362e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,92 @@ -## 3.13.0 (Unreleased) +## 3.14.0 (Unreleased) ENHANCEMENTS: -* azurestackhci: refactoring to use `hashicorp/go-azure-sdk` [GH-17469] -* hardwaresecuritymodules: refactoring to use `hashicorp/go-azure-sdk` [GH-17470] -* privatedns: refactoring to use `hashicorp/go-azure-sdk` [GH-17436] -* Data Source: `azurerm_container_registry` - add support for the `data_endpoint_enabled` property [GH-17466] +* dependencies: updating to `v0.20220715.1071215` of `github.com/hashicorp/go-azure-sdk` [GH-17645] +* servicebus: refactoring to use `hashicorp/go-azure-sdk` [GH-17628] + +## 3.14.0 (July 14, 2022) + +FEATURES: + +* **New Resource**: `azurerm_application_insights_workbook_template` ([#17433](https://github.com/hashicorp/terraform-provider-azurerm/issues/17433)) +* **New Resource**: `azurerm_gallery_application` ([#17394](https://github.com/hashicorp/terraform-provider-azurerm/issues/17394)) +* **New Resource**: `azurerm_gallery_application_version` ([#17394](https://github.com/hashicorp/terraform-provider-azurerm/issues/17394)) + +ENHANCEMENTS: + +* dependencies: updating to `v0.20220712.1111122` of `github.com/hashicorp/go-azure-sdk` ([#17606](https://github.com/hashicorp/terraform-provider-azurerm/issues/17606)) +* dependencies: updating to `v0.37.0` of `github.com/hashicorp/go-azure-helpers` ([#17588](https://github.com/hashicorp/terraform-provider-azurerm/issues/17588)) +* dependencies: updating to `v2.18.0` of `github.com/hashicorp/terraform-plugin-sdk` ([#17141](https://github.com/hashicorp/terraform-provider-azurerm/issues/17141)) +* appconfiguration: updating to use API Version `2022-05-01` ([#17467](https://github.com/hashicorp/terraform-provider-azurerm/issues/17467)) +* spring: updating to use API Version `2022-05-01-preview` ([#17467](https://github.com/hashicorp/terraform-provider-azurerm/issues/17467)) +* databricks: refactoring to use `hashicorp/go-azure-sdk` ([#17475](https://github.com/hashicorp/terraform-provider-azurerm/issues/17475)) +* lighthouse: refactoring to use `hashicorp/go-azure-sdk` ([#17590](https://github.com/hashicorp/terraform-provider-azurerm/issues/17590)) +* policyremediation: updated to use version `2021-10-01` ([#17298](https://github.com/hashicorp/terraform-provider-azurerm/issues/17298)) +* signalr: refactoring to use `hashicorp/go-azure-sdk` ([#17463](https://github.com/hashicorp/terraform-provider-azurerm/issues/17463)) +* storage: refactoring `objectreplicationpolicy` to use `hashicorp/go-azure-sdk` ([#17471](https://github.com/hashicorp/terraform-provider-azurerm/issues/17471)) +* Data Source: `azurerm_availability_set` - updating to use `hashicorp/go-azure-sdk` ([#17608](https://github.com/hashicorp/terraform-provider-azurerm/issues/17608)) +* Data Source: `azurerm_ssh_public_key` - refactoring to use `hashicorp/go-azure-sdk` ([#17609](https://github.com/hashicorp/terraform-provider-azurerm/issues/17609)) +* `azurerm_availability_set` - updating to use `hashicorp/go-azure-sdk` ([#17608](https://github.com/hashicorp/terraform-provider-azurerm/issues/17608)) +* `azurerm_container_group` - support for the `http_headers` property ([#17519](https://github.com/hashicorp/terraform-provider-azurerm/issues/17519)) +* `azurerm_dashboard` - refactoring to use `hashicorp/go-azure-sdk` ([#17598](https://github.com/hashicorp/terraform-provider-azurerm/issues/17598)) +* `azurerm_kusto_cluster` - support for the `public_ip_address` property ([#17520](https://github.com/hashicorp/terraform-provider-azurerm/issues/17520)) +* `azurerm_kusto_script` - support for the `script_content` property ([#17522](https://github.com/hashicorp/terraform-provider-azurerm/issues/17522)) +* `azurerm_kusto_iothub_data_connection` - support for the `database_routing_type` property ([#17526](https://github.com/hashicorp/terraform-provider-azurerm/issues/17526)) +* `azurerm_kusto_eventhub_data_connection` - support for the `database_routing_type` property ([#17525](https://github.com/hashicorp/terraform-provider-azurerm/issues/17525)) +* `azurerm_kusto_eventgrid_data_connection` - support for the `database_routing_type`, `eventgrid_resource_id`, and `managed_identity_resource_id` properties ([#17524](https://github.com/hashicorp/terraform-provider-azurerm/issues/17524)) +* `azurerm_kubernetes_cluster` - support for the `host_group_id` property ([#17496](https://github.com/hashicorp/terraform-provider-azurerm/issues/17496)) +* `azurerm_kubernetes_cluster_node_pool` - support for the `host_group_id` property ([#17496](https://github.com/hashicorp/terraform-provider-azurerm/issues/17496)) +* `azurerm_linux_virtual_machine_scale_set` - support for `capacity_reservation_group_id` property ([#17530](https://github.com/hashicorp/terraform-provider-azurerm/issues/17530)) +* `azurerm_linux_virtual_machine_scale_set` - support for the `placement` property for os disks ([#17013](https://github.com/hashicorp/terraform-provider-azurerm/issues/17013)) +* `azurerm_orchestrated_virtual_machine_scale_set` - support for the `placement` property for os disks ([#17013](https://github.com/hashicorp/terraform-provider-azurerm/issues/17013)) +* `azurerm_shared_image` - support for the `end_of_life_date` `disk_types_not_allowed`, `max_recommended_vcpu_count`, `max_recommended_vcpu_count`, `max_recommended_memory_in_gb`, `min_recommended_memory_in_gb` ([#17300](https://github.com/hashicorp/terraform-provider-azurerm/issues/17300)) +* `azurerm_signalr_service` - Add support for `live_trace` ([#17629](https://github.com/hashicorp/terraform-provider-azurerm/issues/17629)) +* `azurerm_ssh_public_key` - refactoring to use `hashicorp/go-azure-sdk` ([#17609](https://github.com/hashicorp/terraform-provider-azurerm/issues/17609)) +* `azurerm_stream_analytics_output_blob` - support for the `authentication_mode` property ([#16652](https://github.com/hashicorp/terraform-provider-azurerm/issues/16652)) +* `azurerm_windows_virtual_machine_scale_set` - support for `capacity_reservation_group_id` property ([#17530](https://github.com/hashicorp/terraform-provider-azurerm/issues/17530)) +* `azurerm_windows_virtual_machine_scale_set` - support for the `placement` property for os disks ([#17013](https://github.com/hashicorp/terraform-provider-azurerm/issues/17013)) + +BUG FIXES: + +* `azurerm_api_management` - correct set the API Management Cipher `TLS_RSA_WITH_3DES_EDE_CBC_SHA` ([#17554](https://github.com/hashicorp/terraform-provider-azurerm/issues/17554)) +* `azurerm_dev_test_lab_schedule` - deleting the schedule during deletion ([#17614](https://github.com/hashicorp/terraform-provider-azurerm/issues/17614)) +* `azurerm_linux_function_app` - set the `default_hostname` properly on read ([#17498](https://github.com/hashicorp/terraform-provider-azurerm/issues/17498)) +* `azurerm_linux_function_app_slot` - set the `default_hostname` properly on read ([#17498](https://github.com/hashicorp/terraform-provider-azurerm/issues/17498)) +* `azurerm_windows_function_app` - set the `default_hostname` properly on read ([#17498](https://github.com/hashicorp/terraform-provider-azurerm/issues/17498)) +* `azurerm_windows_function_app` - correctly create function apps when custom handlers are used ([#17498](https://github.com/hashicorp/terraform-provider-azurerm/issues/17498)) +* `azurerm_windows_function_app_slot` - set the `default_hostname` properly on read ([#17498](https://github.com/hashicorp/terraform-provider-azurerm/issues/17498)) +* `azurerm_windows_function_app_slot` - correctly create function apps when custom handlers are used ([#17498](https://github.com/hashicorp/terraform-provider-azurerm/issues/17498)) + +## 3.13.0 (July 08, 2022) + +FEATURES: + +* **New Data Source**: `azurerm_public_maintenance_configurations` ([#16810](https://github.com/hashicorp/terraform-provider-azurerm/issues/16810)) +* **New Resource**: `azurerm_fluid_relay_server` ([#17238](https://github.com/hashicorp/terraform-provider-azurerm/issues/17238)) +* **New Resource**: `azurerm_logz_sub_account` ([#16581](https://github.com/hashicorp/terraform-provider-azurerm/issues/16581)) + +ENHANCEMENTS: + +* azurestackhci: refactoring to use `hashicorp/go-azure-sdk` ([#17469](https://github.com/hashicorp/terraform-provider-azurerm/issues/17469)) +* containerinstance: refactoring to use `hashicorp/go-azure-sdk` ([#17499](https://github.com/hashicorp/terraform-provider-azurerm/issues/17499)) +* eventhub: refactoring to use `hashicorp/go-azure-sdk` ([#17445](https://github.com/hashicorp/terraform-provider-azurerm/issues/17445)) +* hardwaresecuritymodules: refactoring to use `hashicorp/go-azure-sdk` ([#17470](https://github.com/hashicorp/terraform-provider-azurerm/issues/17470)) +* netapp: refactoring to use `hashicorp/go-azure-sdk` ([#17465](https://github.com/hashicorp/terraform-provider-azurerm/issues/17465)) +* privatedns: refactoring to use `hashicorp/go-azure-sdk` ([#17436](https://github.com/hashicorp/terraform-provider-azurerm/issues/17436)) +* Data Source: `azurerm_container_registry` - add support for the `data_endpoint_enabled` property ([#17466](https://github.com/hashicorp/terraform-provider-azurerm/issues/17466)) +* `azurerm_hdinsight_kafka_cluster` -support for the `network` block ([#17259](https://github.com/hashicorp/terraform-provider-azurerm/issues/17259)) +* `azurerm_key_vault_certificate` - will now correctly recover certificates on import ([#17415](https://github.com/hashicorp/terraform-provider-azurerm/issues/17415)) +* `azurerm_kubernetes_clusterl`- support for the `capacity_reservation_group_id` property ([#17395](https://github.com/hashicorp/terraform-provider-azurerm/issues/17395)) +* `azurerm_kubernetes_node_pool`- support for the `capacity_reservation_group_id` property ([#17395](https://github.com/hashicorp/terraform-provider-azurerm/issues/17395)) +* `azurerm_linux_virtual_machine` - support for the `capacity_reservation_group_id` property ([#17236](https://github.com/hashicorp/terraform-provider-azurerm/issues/17236)) +* `azurerm_spring_cloud_deployment` - support for the `addon_json` property ([#16984](https://github.com/hashicorp/terraform-provider-azurerm/issues/16984)) +* `azurerm_synapse_integration_runtime_azure` - the `location` property now supports `Auto Resolve` ([#17111](https://github.com/hashicorp/terraform-provider-azurerm/issues/17111)) +* `azurerm_windows_virtual_machine` - support for the `capacity_reservation_group_id` property ([#17236](https://github.com/hashicorp/terraform-provider-azurerm/issues/17236)) + +BUG FIXES: + +* `azurerm_application_gateway` - the `request_routing_rule.x.priority` property is now optional ([#17380](https://github.com/hashicorp/terraform-provider-azurerm/issues/17380)) ## 3.12.0 (June 30, 2022) diff --git a/DEVELOPER.md b/DEVELOPER.md index 90328c60d93f..2809df0638f8 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -3,6 +3,10 @@ * [Terraform (Core)](https://www.terraform.io/downloads.html) - version 1.x (0.12.x and above are compatible however 1.x is recommended) * [Go](https://golang.org/doc/install) version 1.18.x (to build the provider plugin) +## Contributor Guides + +A Collection of guides geared towards contributors can be found in the [`/contributing`](https://github.com/hashicorp/terraform-provider-azurerm/tree/main/contributing) directory of this repository. + ### On Windows If you're on Windows you'll also need: diff --git a/README.md b/README.md index 564ae78d3e10..764ae6ad4c3e 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,6 @@ resource "azurerm_virtual_network" "example" { * [Learn more about Terraform and the AzureRM Provider on HashiCorp Learn](https://learn.hashicorp.com/collections/terraform/azure-get-started). * [Additional examples can be found in the `./examples` folder within this repository](https://github.com/hashicorp/terraform-provider-azurerm/tree/main/examples). -## Developing the Provider +## Developing & Contributing to the Provider -See [DEVELOPER.md](DEVELOPER.md). +The [DEVELOPER.md](DEVELOPER.md) file is a basic outline on how to build and develop the provider while more detailed guides geared towards contributors can be found in the [`/contributing`] (https://github.com/hashicorp/terraform-provider-azurerm/tree/main/contributing) directory of this repository. diff --git a/contributing/README.md b/contributing/README.md index b7fd697be4ef..719733b9044a 100644 --- a/contributing/README.md +++ b/contributing/README.md @@ -1,4 +1,4 @@ -# AzureRM Provider Contributor Docs +# AzureRM Provider Contributor Guides **First,** thank you for your interest in contributing to the Azure Provider! And if you're unsure or anything, please do reach out for help. You can open a draft pull request (PR) or an issue with what you know or join the [Slack Workspace for Contributors](https://terraform-azure.slack.com) ([Request Invite](https://join.slack.com/t/terraform-azure/shared_invite/enQtNDMzNjQ5NzcxMDc3LWNiY2ZhNThhNDgzNmY0MTM0N2MwZjE4ZGU0MjcxYjUyMzRmN2E5NjZhZmQ0ZTA1OTExMGNjYzA4ZDkwZDYxNDE)) and we'll do our best to guide you in the right direction. diff --git a/contributing/topics/maintainer-changelog.md b/contributing/topics/maintainer-changelog.md index b85ffed97dae..3d201a11d379 100644 --- a/contributing/topics/maintainer-changelog.md +++ b/contributing/topics/maintainer-changelog.md @@ -22,6 +22,8 @@ When adding a changelog entry the following rules should be followed: * each entry should link to the pull request with the placeholder `[GH-{number}]` (e.g. `[GH-1234]`), this will be replaced with a link during the release process. * entries should read as complete sentences such as `support for the property ```new_feature``` ` or `improve validation of the property ```old_feature``` ` not `support ```new_feature``` `. +And finally when making the edit commit, the PR number should be included in the commit message so the edit is linked to the PR, and the entry from the pr. For example `CHANGELOG.md for #1234`. + Here is a list of common changelog entries and how they should be formatted: ```go diff --git a/go.mod b/go.mod index e560ff5aba9b..070258b4990f 100644 --- a/go.mod +++ b/go.mod @@ -1,7 +1,7 @@ module github.com/hashicorp/terraform-provider-azurerm require ( - github.com/Azure/azure-sdk-for-go v64.1.0+incompatible + github.com/Azure/azure-sdk-for-go v65.0.0+incompatible github.com/Azure/go-autorest/autorest v0.11.27 github.com/Azure/go-autorest/autorest/date v0.3.0 github.com/Azure/go-autorest/autorest/to v0.4.0 @@ -12,26 +12,25 @@ require ( github.com/gofrs/uuid v4.0.0+incompatible github.com/google/go-cmp v0.5.8 github.com/google/uuid v1.1.2 - github.com/hashicorp/go-azure-helpers v0.35.0 - github.com/hashicorp/go-azure-sdk v0.20220701.1073833 + github.com/hashicorp/go-azure-helpers v0.37.0 + github.com/hashicorp/go-azure-sdk v0.20220715.1071215 github.com/hashicorp/go-multierror v1.1.1 - github.com/hashicorp/go-uuid v1.0.2 - github.com/hashicorp/go-version v1.4.0 - github.com/hashicorp/terraform-plugin-sdk/v2 v2.10.1 + github.com/hashicorp/go-uuid v1.0.3 + github.com/hashicorp/go-version v1.6.0 + github.com/hashicorp/terraform-plugin-sdk/v2 v2.18.0 github.com/magodo/terraform-provider-azurerm-example-gen v0.0.0-20220407025246-3a3ee0ab24a8 github.com/manicminer/hamilton v0.44.0 - github.com/mitchellh/mapstructure v1.4.1 + github.com/mitchellh/mapstructure v1.5.0 github.com/rickb777/date v1.12.5-0.20200422084442-6300e543c4d9 github.com/sergi/go-diff v1.2.0 github.com/shopspring/decimal v1.2.0 github.com/tombuildsstuff/giovanni v0.20.0 - golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 + golang.org/x/crypto v0.0.0-20220517005047-85d78b3ac167 golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 - gopkg.in/yaml.v3 v3.0.0 + gopkg.in/yaml.v3 v3.0.1 ) require ( - cloud.google.com/go/storage v1.16.0 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest/autorest/adal v0.9.18 // indirect github.com/Azure/go-autorest/autorest/azure/cli v0.4.5 // indirect @@ -40,35 +39,31 @@ require ( github.com/apparentlymart/go-cidr v1.1.0 // indirect github.com/apparentlymart/go-textseg v1.0.0 // indirect github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect - github.com/aws/aws-sdk-go v1.38.69 // indirect github.com/dimchansky/utfbom v1.1.1 // indirect - github.com/fatih/color v1.12.0 // indirect + github.com/fatih/color v1.13.0 // indirect github.com/golang-jwt/jwt/v4 v4.4.1 // indirect - github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-checkpoint v0.5.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect - github.com/hashicorp/go-getter v1.6.1 // indirect - github.com/hashicorp/go-hclog v0.16.1 // indirect - github.com/hashicorp/go-plugin v1.4.2 // indirect + github.com/hashicorp/go-hclog v1.2.1 // indirect + github.com/hashicorp/go-plugin v1.4.4 // indirect github.com/hashicorp/go-retryablehttp v0.7.0 // indirect - github.com/hashicorp/hc-install v0.3.2 // indirect - github.com/hashicorp/hcl/v2 v2.10.0 // indirect + github.com/hashicorp/hc-install v0.4.0 // indirect + github.com/hashicorp/hcl/v2 v2.13.0 // indirect github.com/hashicorp/hcl2 v0.0.0-20191002203319-fb75b3253c80 // indirect github.com/hashicorp/logutils v1.0.0 // indirect - github.com/hashicorp/terraform-exec v0.15.0 // indirect - github.com/hashicorp/terraform-json v0.13.0 // indirect - github.com/hashicorp/terraform-plugin-go v0.5.0 // indirect - github.com/hashicorp/terraform-plugin-log v0.2.0 // indirect - github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896 // indirect + github.com/hashicorp/terraform-exec v0.17.2 // indirect + github.com/hashicorp/terraform-json v0.14.0 // indirect + github.com/hashicorp/terraform-plugin-go v0.10.0 // indirect + github.com/hashicorp/terraform-plugin-log v0.4.1 // indirect + github.com/hashicorp/terraform-registry-address v0.0.0-20220623143253-7d51757b572c // indirect github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 // indirect github.com/hashicorp/yamux v0.0.0-20210316155119-a95892c5f864 // indirect - github.com/klauspost/compress v1.13.1 // indirect github.com/manicminer/hamilton-autorest v0.2.0 // indirect - github.com/mattn/go-colorable v0.1.8 // indirect - github.com/mattn/go-isatty v0.0.13 // indirect + github.com/mattn/go-colorable v0.1.12 // indirect + github.com/mattn/go-isatty v0.0.14 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/go-testing-interface v1.14.1 // indirect @@ -76,20 +71,20 @@ require ( github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/oklog/run v1.1.0 // indirect github.com/rickb777/plural v1.2.0 // indirect - github.com/ulikunitz/xz v0.5.10 // indirect github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect - github.com/zclconf/go-cty v1.9.1 // indirect + github.com/vmihailenco/msgpack/v4 v4.3.12 // indirect + github.com/vmihailenco/tagparser v0.1.1 // indirect + github.com/zclconf/go-cty v1.10.0 // indirect golang.org/x/mod v0.4.2 // indirect golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914 // indirect golang.org/x/sys v0.0.0-20220517195934-5e4e11fc645e // indirect - golang.org/x/text v0.3.6 // indirect + golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.7 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect - google.golang.org/api v0.49.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20210629200056-84d6f6074151 // indirect - google.golang.org/grpc v1.39.0 // indirect - google.golang.org/protobuf v1.27.1 // indirect + google.golang.org/grpc v1.47.0 // indirect + google.golang.org/protobuf v1.28.0 // indirect ) go 1.18 diff --git a/go.sum b/go.sum index 27cdd84c9053..c7d21e59ece3 100644 --- a/go.sum +++ b/go.sum @@ -11,17 +11,8 @@ cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6 cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.61.0/go.mod h1:XukKJg4Y7QsUu0Hxg3qQKUWR4VuWivmyMK2+rUyxAqw= cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= -cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= -cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= -cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= -cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= -cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY= -cloud.google.com/go v0.84.0 h1:hVhK90DwCdOAYGME/FJd9vNIZye9HBR6Yy3fu4js3N8= -cloud.google.com/go v0.84.0/go.mod h1:RazrYuxIK6Kb7YrzzhPoLmCVzl7Sup4NrbKPg8KHSUM= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= @@ -39,13 +30,11 @@ cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0Zeo cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -cloud.google.com/go/storage v1.16.0 h1:1UwAux2OZP4310YXg5ohqBEpV16Y93uZG4+qOX7K2Kg= -cloud.google.com/go/storage v1.16.0/go.mod h1:ieKBmUyzcftN5tbxwnXClMKH00CfcQ+xL6NN0r5QfmE= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/Azure/azure-sdk-for-go v45.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/azure-sdk-for-go v56.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/azure-sdk-for-go v64.1.0+incompatible h1:FpsZmWR9FfEr9hP6K9S7RP0EkSFgGd6P1F2scHtbhnU= -github.com/Azure/azure-sdk-for-go v64.1.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go v65.0.0+incompatible h1:HzKLt3kIwMm4KeJYTdx9EbjRYTySD/t8i1Ee/W5EGXw= +github.com/Azure/azure-sdk-for-go v65.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= github.com/Azure/go-autorest/autorest v0.11.3/go.mod h1:JFgpikqFJ/MleTTxwepExTKnFUKKszPS8UavbQYUMuw= @@ -81,9 +70,6 @@ github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUM github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= -github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= github.com/Microsoft/go-winio v0.4.16 h1:FtSW/jqD+l4ba5iPBj9CODVtgfYAD8w2wS923g/cFDk= github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= @@ -92,45 +78,35 @@ github.com/ProtonMail/go-crypto v0.0.0-20210428141323-04723f9f07d7/go.mod h1:z4/ github.com/acomagu/bufpipe v1.0.3 h1:fxAGrHZTgQ9w5QqVItgzwj235/uYZYgbXitB+dLupOk= github.com/acomagu/bufpipe v1.0.3/go.mod h1:mxdxdup/WdsKVreO5GpW4+M/1CE2sMG4jeGJ2sYmHc4= github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= -github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= -github.com/andybalholm/crlf v0.0.0-20171020200849-670099aa064f/go.mod h1:k8feO4+kXDxro6ErPXBRTJ/ro2mf0SsFG8s7doP9kJE= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/apparentlymart/go-cidr v1.0.1/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= github.com/apparentlymart/go-cidr v1.1.0 h1:2mAhrMoF+nhXqxTzSZMUzDHkLjmIHC+Zzn4tdgBZjnU= github.com/apparentlymart/go-cidr v1.1.0/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0 h1:MzVXffFUye+ZcSR6opIgz9Co7WcDx6ZcY+RjfFHoA0I= -github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= -github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= -github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM= -github.com/aws/aws-sdk-go v1.25.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/aws/aws-sdk-go v1.38.69 h1:V489lmrdkIQSfF6OAGZZ1Cavcm7eczCm2JcGvX+yHRg= -github.com/aws/aws-sdk-go v1.38.69/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= -github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bsm/go-vlq v0.0.0-20150828105119-ec6e8d4f5f4e/go.mod h1:N+BjUcTjSxc2mtRGSCPsat1kze3CUtvJN3/jTXlp29k= github.com/btubbs/datetime v0.1.0 h1:183iHRjmNAokYM5D8V3wbEOOEe/HYEYpm7E2oom3vhM= github.com/btubbs/datetime v0.1.0/go.mod h1:n2BZ/2ltnRzNiz27aE3wUb2onNttQdC+WFxAoks5jJM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -144,14 +120,12 @@ github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3 github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/color v1.12.0 h1:mRhaKNwANqRgUBGKmnI5ZxEk7QXmjQeCcuYFMX2bfcc= -github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= +github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= @@ -181,8 +155,6 @@ github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfU github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= -github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= @@ -190,7 +162,6 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -207,11 +178,8 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA= -github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -221,17 +189,12 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/martian/v3 v3.2.1/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= @@ -239,17 +202,11 @@ github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/errwrap v0.0.0-20180715044906-d6c0cd880357/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -257,10 +214,10 @@ github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brv github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-azure-helpers v0.12.0/go.mod h1:Zc3v4DNeX6PDdy7NljlYpnrdac1++qNW0I4U+ofGwpg= -github.com/hashicorp/go-azure-helpers v0.35.0 h1:/Jpm37dzTmSHobt9SuC8bK6/jSoWw5FdxB9WIqQFXbI= -github.com/hashicorp/go-azure-helpers v0.35.0/go.mod h1:gcutZ/Hf/O7YN9M3UIvyZ9l0Rxv7Yrc9x5sSfM9cuSw= -github.com/hashicorp/go-azure-sdk v0.20220701.1073833 h1:cwutAQhHojIpJR0a7gyf4884A4KX3Un1lj9SUZDRdxE= -github.com/hashicorp/go-azure-sdk v0.20220701.1073833/go.mod h1:yjQPw8DCOtQR8E8+FNaTxF6yz+tyQGkDNiVAGCNoLOo= +github.com/hashicorp/go-azure-helpers v0.37.0 h1:6UOoQ9esE4MJ4wHJr21qU81IJQ9zsXQ9FbANYUbeE4U= +github.com/hashicorp/go-azure-helpers v0.37.0/go.mod h1:gcutZ/Hf/O7YN9M3UIvyZ9l0Rxv7Yrc9x5sSfM9cuSw= +github.com/hashicorp/go-azure-sdk v0.20220715.1071215 h1:PZYeATYa/qh1KM5RxKC8eTSKms5/sqbZohSCcemzrJo= +github.com/hashicorp/go-azure-sdk v0.20220715.1071215/go.mod h1:yjQPw8DCOtQR8E8+FNaTxF6yz+tyQGkDNiVAGCNoLOo= github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU= github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= @@ -269,69 +226,54 @@ github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9n github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 h1:1/D3zfFHttUKaCaGKZ/dR2roBXv0vKbSCnssIldfQdI= github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320/go.mod h1:EiZBMaudVLy8fmjf9Npq1dq9RalhveqZG5w/yz3mHWs= -github.com/hashicorp/go-getter v1.5.3/go.mod h1:BrrV/1clo8cCYu6mxvboYg+KutTiFnXjMEgDD8+i7ZI= -github.com/hashicorp/go-getter v1.6.1 h1:NASsgP4q6tL94WH6nJxKWj8As2H/2kop/bB1d8JMyRY= -github.com/hashicorp/go-getter v1.6.1/go.mod h1:IZCrswsZPeWv9IkVnLElzRU/gz/QPi6pZHn4tv6vbwA= -github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= -github.com/hashicorp/go-hclog v0.14.1/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= -github.com/hashicorp/go-hclog v0.16.1 h1:IVQwpTGNRRIHafnTs2dQLIk4ENtneRIEEJWOVDqz99o= -github.com/hashicorp/go-hclog v0.16.1/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= +github.com/hashicorp/go-hclog v1.2.1 h1:YQsLlGDJgwhXFpucSPyVbCBviQtjlHv3jLTlp8YmtEw= +github.com/hashicorp/go-hclog v1.2.1/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= github.com/hashicorp/go-multierror v0.0.0-20180717150148-3d5d8f294aa0/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-plugin v1.3.0/go.mod h1:F9eH4LrE/ZsRdbwhfjs9k9HoDUwAHnYtXdgmf1AVNs0= -github.com/hashicorp/go-plugin v1.4.1/go.mod h1:5fGEH17QVwTTcR0zV7yhDPLLmFX9YSZ38b18Udy6vYQ= -github.com/hashicorp/go-plugin v1.4.2 h1:yFvG3ufXXpqiMiZx9HLcaK3XbIqQ1WJFR/F1a2CuVw0= -github.com/hashicorp/go-plugin v1.4.2/go.mod h1:5fGEH17QVwTTcR0zV7yhDPLLmFX9YSZ38b18Udy6vYQ= +github.com/hashicorp/go-plugin v1.4.4 h1:NVdrSdFRt3SkZtNckJ6tog7gbpRrcbOjQi/rgF7JYWQ= +github.com/hashicorp/go-plugin v1.4.4/go.mod h1:viDMjcLJuDui6pXb8U4HVfb8AamCWhHGUjr2IrTF67s= github.com/hashicorp/go-retryablehttp v0.7.0 h1:eu1EI/mbirUgP5C8hVsTNaGZreBDlYiwC1FZWkvQPQ4= github.com/hashicorp/go-retryablehttp v0.7.0/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= -github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= -github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.2 h1:cfejS+Tpcp13yd5nYHWDI6qVCny6wyX2Mt5SGur2IGE= github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.4.0 h1:aAQzgqIrRKRa7w75CKpbBxYsmUoPjzVm1W59ca1L0J4= -github.com/hashicorp/go-version v1.4.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.5.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= +github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/hc-install v0.3.1/go.mod h1:3LCdWcCDS1gaHC9mhHCGbkYfoY6vdsKohGjugbZdZak= -github.com/hashicorp/hc-install v0.3.2 h1:oiQdJZvXmkNcRcEOOfM5n+VTsvNjWQeOjfAoO6dKSH8= -github.com/hashicorp/hc-install v0.3.2/go.mod h1:xMG6Tr8Fw1WFjlxH0A9v61cW15pFwgEGqEz0V4jisHs= -github.com/hashicorp/hcl/v2 v2.3.0/go.mod h1:d+FwDBbOLvpAM3Z6J7gPj/VoAGkNe/gm352ZhjJ/Zv8= -github.com/hashicorp/hcl/v2 v2.10.0 h1:1S1UnuhDGlv3gRFV4+0EdwB+znNP5HmcGbIqwnSCByg= -github.com/hashicorp/hcl/v2 v2.10.0/go.mod h1:FwWsfWEjyV/CMj8s/gqAuiviY72rJ1/oayI9WftqcKg= +github.com/hashicorp/hc-install v0.4.0 h1:cZkRFr1WVa0Ty6x5fTvL1TuO1flul231rWkGH92oYYk= +github.com/hashicorp/hc-install v0.4.0/go.mod h1:5d155H8EC5ewegao9A4PUTMNPZaq+TbOzkJJZ4vrXeI= +github.com/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc= +github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0= github.com/hashicorp/hcl2 v0.0.0-20191002203319-fb75b3253c80 h1:PFfGModn55JA0oBsvFghhj0v93me+Ctr3uHC/UmFAls= github.com/hashicorp/hcl2 v0.0.0-20191002203319-fb75b3253c80/go.mod h1:Cxv+IJLuBiEhQ7pBYGEuORa0nr4U994pE8mYLuFd7v0= github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/terraform-exec v0.15.0 h1:cqjh4d8HYNQrDoEmlSGelHmg2DYDh5yayckvJ5bV18E= -github.com/hashicorp/terraform-exec v0.15.0/go.mod h1:H4IG8ZxanU+NW0ZpDRNsvh9f0ul7C0nHP+rUR/CHs7I= -github.com/hashicorp/terraform-json v0.13.0 h1:Li9L+lKD1FO5RVFRM1mMMIBDoUHslOniyEi5CM+FWGY= -github.com/hashicorp/terraform-json v0.13.0/go.mod h1:y5OdLBCT+rxbwnpxZs9kGL7R9ExU76+cpdY8zHwoazk= -github.com/hashicorp/terraform-plugin-go v0.5.0 h1:+gCDdF0hcYCm0YBTxrP4+K1NGIS5ZKZBKDORBewLJmg= -github.com/hashicorp/terraform-plugin-go v0.5.0/go.mod h1:PAVN26PNGpkkmsvva1qfriae5Arky3xl3NfzKa8XFVM= -github.com/hashicorp/terraform-plugin-log v0.2.0 h1:rjflRuBqCnSk3UHOR25MP1G5BDLKktTA6lNjjcAnBfI= -github.com/hashicorp/terraform-plugin-log v0.2.0/go.mod h1:E1kJmapEHzqu1x6M++gjvhzM2yMQNXPVWZRCB8sgYjg= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.10.1 h1:B9AocC+dxrCqcf4vVhztIkSkt3gpRjUkEka8AmZWGlQ= -github.com/hashicorp/terraform-plugin-sdk/v2 v2.10.1/go.mod h1:FjM9DXWfP0w/AeOtJoSKHBZ01LqmaO6uP4bXhv3fekw= -github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896 h1:1FGtlkJw87UsTMg5s8jrekrHmUPUJaMcu6ELiVhQrNw= -github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896/go.mod h1:bzBPnUIkI0RxauU8Dqo+2KrZZ28Cf48s8V6IHt3p4co= +github.com/hashicorp/terraform-exec v0.17.2 h1:EU7i3Fh7vDUI9nNRdMATCEfnm9axzTnad8zszYZ73Go= +github.com/hashicorp/terraform-exec v0.17.2/go.mod h1:tuIbsL2l4MlwwIZx9HPM+LOV9vVyEfBYu2GsO1uH3/8= +github.com/hashicorp/terraform-json v0.14.0 h1:sh9iZ1Y8IFJLx+xQiKHGud6/TSUCM0N8e17dKDpqV7s= +github.com/hashicorp/terraform-json v0.14.0/go.mod h1:5A9HIWPkk4e5aeeXIBbkcOvaZbIYnAIkEyqP2pNSckM= +github.com/hashicorp/terraform-plugin-go v0.10.0 h1:FIQDt/AZDSOXnN+znBnLLZA9aFk4/GwL40rwMLnvuTk= +github.com/hashicorp/terraform-plugin-go v0.10.0/go.mod h1:aphXBG8qtQH0yF1waMRlaw/3G+ZFlR/6Artnvt1QEDE= +github.com/hashicorp/terraform-plugin-log v0.4.1 h1:xpbmVhvuU3mgHzLetOmx9pkOL2rmgpu302XxddON6eo= +github.com/hashicorp/terraform-plugin-log v0.4.1/go.mod h1:p4R1jWBXRTvL4odmEkFfDdhUjHf9zcs/BCoNHAc7IK4= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.18.0 h1:/cdI5di5XA+N80gXzXF4YcHq36DprBskubk6Z8i26ZQ= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.18.0/go.mod h1:L3SHkD/Q8zPVgXviQmpVwy9nKwpXXZscVIpVEnQ/T50= +github.com/hashicorp/terraform-registry-address v0.0.0-20220623143253-7d51757b572c h1:D8aRO6+mTqHfLsK/BC3j5OAoogv1WLRWzY1AaTo3rBg= +github.com/hashicorp/terraform-registry-address v0.0.0-20220623143253-7d51757b572c/go.mod h1:Wn3Na71knbXc1G8Lh+yu/dQWWJeFQEpDeJMtWMtlmNI= github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 h1:HKLsbzeOsfXmKNpr3GiT18XAblV0BjCbzL8KQAMZGa0= github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734/go.mod h1:kNDNcF7sN4DocDLBkQYz73HGKwN1ANB1blq4lIYLYvg= -github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= -github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/hashicorp/yamux v0.0.0-20210316155119-a95892c5f864 h1:Y4V+SFe7d3iH+9pJCoeWIOS5/xBJIFsltS7E+KJSsJY= github.com/hashicorp/yamux v0.0.0-20210316155119-a95892c5f864/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= @@ -339,21 +281,11 @@ github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/jhump/protoreflect v1.6.0 h1:h5jfMVslIg6l29nsMs0D8Wj17RDVdNYti0vDN/PZZoE= -github.com/jhump/protoreflect v1.6.0/go.mod h1:eaTn3RZAmMBcV0fifFvlm6VHNz3wSkYyXYWUh7ymB74= -github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1 h1:6QPYqodiu3GuPL+7mfx+NwDdp2eTkp9IfEUpgAwUN0o= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351 h1:DowS9hvgyYSX4TO5NpyC606/Z4SxnNYbT+WX27or6Ck= github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.11.2/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= -github.com/klauspost/compress v1.13.1 h1:wXr2uRxZTJXHLly6qhJabee5JqIhTRoLBhDOA74hDEQ= -github.com/klauspost/compress v1.13.1/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= @@ -364,7 +296,6 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/magodo/terraform-provider-azurerm-example-gen v0.0.0-20220407025246-3a3ee0ab24a8 h1:HHSqLmPZaa8U66U7N2Gtx3gYptSHrUB/rB5t+6fZTkQ= github.com/magodo/terraform-provider-azurerm-example-gen v0.0.0-20220407025246-3a3ee0ab24a8/go.mod h1:iMzpAzVr2v/NUVie/apAYtZlFZYFndPcp6/E0VLxgAM= github.com/manicminer/hamilton v0.43.0/go.mod h1:lbVyngC+/nCWuDp8UhC6Bw+bh7jcP/E+YwqzHTmzemk= @@ -373,44 +304,28 @@ github.com/manicminer/hamilton v0.44.0/go.mod h1:lbVyngC+/nCWuDp8UhC6Bw+bh7jcP/E github.com/manicminer/hamilton-autorest v0.2.0 h1:dDL+t2DrQza0EfNYINYCvXISeNwVqzgVAQh+CH/19ZU= github.com/manicminer/hamilton-autorest v0.2.0/go.mod h1:NselDpNTImEmOc/fa41kPg6YhDt/6S95ejWbTGZ6tlg= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= -github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8= -github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-isatty v0.0.13 h1:qdl+GuBjcsKKDco5BsxPJlId98mSWNKqYA+Co0SC1yA= -github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= -github.com/mitchellh/cli v1.1.2/go.mod h1:6iaV0fGdElS6dPBx0EApTxHrcWvmJphyh2n8YBLPPZ4= -github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= -github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= -github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nsf/jsondiff v0.0.0-20200515183724-f29ed568f4ce h1:RPclfga2SEJmgMmz2k+Mg7cowZ8yv4Trqw9UsJby758= -github.com/nsf/jsondiff v0.0.0-20200515183724-f29ed568f4ce/go.mod h1:uFMI8w+ref4v2r9jz+c9i1IfIttS/OkmLfrk1jne5hs= -github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA= github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= @@ -420,7 +335,6 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rickb777/date v1.12.5-0.20200422084442-6300e543c4d9 h1:czJCcoUR3FMpHnRQow2E84H/0CPrX1fMAGn9HugzyI4= github.com/rickb777/date v1.12.5-0.20200422084442-6300e543c4d9/go.mod h1:L8WrssTzvgYw34/Ppa0JpJfI7KKXZ2cVGI6Djt0brUU= @@ -443,42 +357,36 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/tombuildsstuff/giovanni v0.20.0 h1:IM/I/iNWMXnPYwcSq8uxV7TKDlv7Nejq0bRK9i6O/C0= github.com/tombuildsstuff/giovanni v0.20.0/go.mod h1:66KVLYma2whJhEdxPSPL3GQHkulhK+C5CluKfHGfPF4= -github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= -github.com/ulikunitz/xz v0.5.10 h1:t92gobL9l3HE202wg3rlk19F6X+JOxl9BBrCCMYEYd8= -github.com/ulikunitz/xz v0.5.10/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI= github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/vmihailenco/msgpack/v4 v4.3.12 h1:07s4sz9IReOgdikxLTKNbBdqDMLsjPKXwvCazn8G65U= github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= +github.com/vmihailenco/tagparser v0.1.1 h1:quXMXlA39OCbd2wAdTsGDlK9RkOk6Wuw+x37wVyIuWY= github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= github.com/xanzy/ssh-agent v0.3.0 h1:wUMzuKtKilRgBAD1sUb8gOwwRr2FGoBVumcjoOACClI= github.com/xanzy/ssh-agent v0.3.0/go.mod h1:3s9xbODqPuuhK9JV1R321M/FlMZSBvE5aY6eAcqrDh0= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/zclconf/go-cty v1.0.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.1.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= -github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= -github.com/zclconf/go-cty v1.9.1 h1:viqrgQwFl5UpSxc046qblj78wZXVDFnSOufaOTER+cc= -github.com/zclconf/go-cty v1.9.1/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= +github.com/zclconf/go-cty v1.10.0 h1:mp9ZXQeIcN8kAwuqorjH+Q+njbJKjLrvB2yIh4q7U+0= +github.com/zclconf/go-cty v1.10.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b/go.mod h1:ZRKQfBXbGkpdV6QMzT3rU1kSTAnfu1dO8dPKjYprgj8= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= -go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= -go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -487,7 +395,6 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= @@ -495,8 +402,8 @@ golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA= -golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220517005047-85d78b3ac167 h1:O8uGbHCqlTp2P6QJSLmCojM4mN6UemYv8K+dCnmHmu0= +golang.org/x/crypto v0.0.0-20220517005047-85d78b3ac167/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -519,8 +426,6 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= @@ -530,11 +435,8 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20180530234432-1e491301e022/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -566,15 +468,10 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210326060303-6b1517762897/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= @@ -583,14 +480,7 @@ golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4Iltr golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210615190721-d04028783cf1/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914 h1:3B43BWw0xEBsLZ/NO1VALz6fppU3481pik+2Ksv45z8= golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -601,14 +491,11 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -619,7 +506,6 @@ golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -636,26 +522,20 @@ golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210502180810-71e4cd670f79/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220517195934-5e4e11fc645e h1:w36l2Uw3dRan1K3TyXriXvY+6T56GNmlKGcqiQUJDfM= golang.org/x/sys v0.0.0-20220517195934-5e4e11fc645e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= @@ -665,10 +545,10 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -709,19 +589,9 @@ golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ= golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= @@ -746,15 +616,6 @@ google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0M google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= -google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= -google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= -google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= -google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= -google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4= -google.golang.org/api v0.49.0 h1:gjIBDxlTG7vnzMmEnYwTnvLTF8Rjzo+ETCgEX1YZ/fY= -google.golang.org/api v0.49.0/go.mod h1:BECiH72wsfwUvOVn3+btPD5WHi0LzavZReBndi42L18= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -763,7 +624,6 @@ google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCID google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto v0.0.0-20170818010345-ee236bd376b0/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -791,29 +651,11 @@ google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfG google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200711021454-869866162049/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= -google.golang.org/genproto v0.0.0-20210604141403-392c879c8b08/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= -google.golang.org/genproto v0.0.0-20210608205507-b6d2f5bf0d7d/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= -google.golang.org/genproto v0.0.0-20210617175327-b9e0b3197ced/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20210624174822-c5cf32407d0a/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= google.golang.org/genproto v0.0.0-20210629200056-84d6f6074151 h1:H/uPzsolsGjhl3CVT6Wb7bK+mf+hmkEvUVu+FBKyNlc= google.golang.org/genproto v0.0.0-20210629200056-84d6f6074151/go.mod h1:yiaVoXHpRzHGyxV3o4DktVWY4mSUErTKaeEOq6C3t3U= -google.golang.org/grpc v1.8.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -826,20 +668,11 @@ google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKa google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= -google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.39.0 h1:Klz8I9kdtkIN6EpHHUOMLCYhTn/2WAe5a0s1hcBkdTI= -google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= -google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= +google.golang.org/grpc v1.47.0 h1:9n77onPX5F3qfFCqjy9dhn8PbNQsIKeVU04J9G7umt8= +google.golang.org/grpc v1.47.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -852,15 +685,15 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/cheggaaa/pb.v1 v1.0.27/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= @@ -870,11 +703,10 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA= -gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/helpers/azure/resource_group.go b/helpers/azure/resource_group.go index 6fa712ecd79b..a9c494287a05 100644 --- a/helpers/azure/resource_group.go +++ b/helpers/azure/resource_group.go @@ -3,7 +3,6 @@ package azure import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourcegroups" - "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" ) diff --git a/internal/clients/client.go b/internal/clients/client.go index f460294421c9..a1db6778fa33 100644 --- a/internal/clients/client.go +++ b/internal/clients/client.go @@ -48,6 +48,7 @@ import ( eventgrid "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventgrid/client" eventhub "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/client" firewall "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall/client" + fluidrelay "github.com/hashicorp/terraform-provider-azurerm/internal/services/fluidrelay/client" frontdoor "github.com/hashicorp/terraform-provider-azurerm/internal/services/frontdoor/client" hdinsight "github.com/hashicorp/terraform-provider-azurerm/internal/services/hdinsight/client" healthcare "github.com/hashicorp/terraform-provider-azurerm/internal/services/healthcare/client" @@ -159,6 +160,7 @@ type Client struct { EventGrid *eventgrid.Client Eventhub *eventhub.Client Firewall *firewall.Client + FluidRelay *fluidrelay.Client Frontdoor *frontdoor.Client HPCCache *hpccache.Client HSM *hsm.Client @@ -272,6 +274,7 @@ func (client *Client) Build(ctx context.Context, o *common.ClientOptions) error client.EventGrid = eventgrid.NewClient(o) client.Eventhub = eventhub.NewClient(o) client.Firewall = firewall.NewClient(o) + client.FluidRelay = fluidrelay.NewClient(o) client.Frontdoor = frontdoor.NewClient(o) client.HPCCache = hpccache.NewClient(o) client.HSM = hsm.NewClient(o) diff --git a/internal/provider/services.go b/internal/provider/services.go index 93092db6aa7e..a0a52d2c40d3 100644 --- a/internal/provider/services.go +++ b/internal/provider/services.go @@ -44,6 +44,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventgrid" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub" "github.com/hashicorp/terraform-provider-azurerm/internal/services/firewall" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/fluidrelay" "github.com/hashicorp/terraform-provider-azurerm/internal/services/frontdoor" "github.com/hashicorp/terraform-provider-azurerm/internal/services/hdinsight" "github.com/hashicorp/terraform-provider-azurerm/internal/services/healthcare" @@ -113,15 +114,18 @@ func SupportedTypedServices() []sdk.TypedServiceRegistration { aadb2c.Registration{}, apimanagement.Registration{}, appconfiguration.Registration{}, + applicationinsights.Registration{}, appservice.Registration{}, batch.Registration{}, bot.Registration{}, + compute.Registration{}, consumption.Registration{}, containers.Registration{}, costmanagement.Registration{}, disks.Registration{}, domainservices.Registration{}, eventhub.Registration{}, + fluidrelay.Registration{}, keyvault.Registration{}, loadbalancer.Registration{}, loadtest.Registration{}, diff --git a/internal/sdk/resource.go b/internal/sdk/resource.go index 301af4b672f2..12fb5662159a 100644 --- a/internal/sdk/resource.go +++ b/internal/sdk/resource.go @@ -11,13 +11,23 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) -type resourceBase interface { +// resourceWithPluginSdkSchema defines the Arguments and Attributes for this resource +// using the types defined in Plugin SDKv2 +type resourceWithPluginSdkSchema interface { // Arguments is a list of user-configurable (that is: Required, Optional, or Optional and Computed) // arguments for this Resource Arguments() map[string]*schema.Schema // Attributes is a list of read-only (e.g. Computed-only) attributes Attributes() map[string]*schema.Schema +} + +type resourceBase interface { + // resourceWithPluginSdkSchema ensure that the Arguments and Attributes are sourced + // from Plugin SDKv2 for now - longer term we'll likely introduce a `Typed Schema` + // which will cross-compile down to both the Plugin SDKv2 and Plugin Framework, but + // that's a story for another day. + resourceWithPluginSdkSchema // ModelObject is an instance of the object the Schema is decoded/encoded into ModelObject() interface{} diff --git a/internal/services/aadb2c/aadb2c_directory_resource.go b/internal/services/aadb2c/aadb2c_directory_resource.go index 0d4f311481e9..fc4c044e737d 100644 --- a/internal/services/aadb2c/aadb2c_directory_resource.go +++ b/internal/services/aadb2c/aadb2c_directory_resource.go @@ -7,7 +7,6 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" - "github.com/hashicorp/go-azure-sdk/resource-manager/aadb2c/2021-04-01-preview/tenants" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" diff --git a/internal/services/apimanagement/api_management_resource.go b/internal/services/apimanagement/api_management_resource.go index 52ed5e5df599..76615c5a0f7a 100644 --- a/internal/services/apimanagement/api_management_resource.go +++ b/internal/services/apimanagement/api_management_resource.go @@ -36,7 +36,7 @@ var ( apimFrontendProtocolSsl3 = "Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Protocols.Ssl30" apimFrontendProtocolTls10 = "Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Protocols.Tls10" apimFrontendProtocolTls11 = "Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Protocols.Tls11" - apimTripleDesCiphers = "Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.TripleDes168" + apimTripleDesCiphers = "Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.TLS_RSA_WITH_3DES_EDE_CBC_SHA" apimHttp2Protocol = "Microsoft.WindowsAzure.ApiManagement.Gateway.Protocols.Server.Http2" apimTlsEcdheEcdsaWithAes256CbcShaCiphers = "Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" apimTlsEcdheEcdsaWithAes128CbcShaCiphers = "Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" diff --git a/internal/services/appconfiguration/app_configuration_data_source.go b/internal/services/appconfiguration/app_configuration_data_source.go index c3943d4b470d..8b4e22355910 100644 --- a/internal/services/appconfiguration/app_configuration_data_source.go +++ b/internal/services/appconfiguration/app_configuration_data_source.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" - "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores" + "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/appconfiguration/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" diff --git a/internal/services/appconfiguration/app_configuration_resource.go b/internal/services/appconfiguration/app_configuration_resource.go index a1c6c23685de..ce4b3054605d 100644 --- a/internal/services/appconfiguration/app_configuration_resource.go +++ b/internal/services/appconfiguration/app_configuration_resource.go @@ -6,13 +6,12 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" - "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" - "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores" + "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/appconfiguration/app_configuration_resource_test.go b/internal/services/appconfiguration/app_configuration_resource_test.go index b96f5862ddc5..053e7f7a8098 100644 --- a/internal/services/appconfiguration/app_configuration_resource_test.go +++ b/internal/services/appconfiguration/app_configuration_resource_test.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores" + "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/appconfiguration/client/client.go b/internal/services/appconfiguration/client/client.go index 77ed7765a8d5..5b12976a67fd 100644 --- a/internal/services/appconfiguration/client/client.go +++ b/internal/services/appconfiguration/client/client.go @@ -6,7 +6,7 @@ import ( "github.com/Azure/go-autorest/autorest" "github.com/hashicorp/go-azure-helpers/lang/response" - "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores" + "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores" "github.com/hashicorp/terraform-provider-azurerm/internal/common" "github.com/hashicorp/terraform-provider-azurerm/internal/services/appconfiguration/sdk/1.0/appconfiguration" ) diff --git a/internal/services/applicationinsights/application_insights_workbook_template_resource.go b/internal/services/applicationinsights/application_insights_workbook_template_resource.go new file mode 100644 index 000000000000..d984bd50a1cc --- /dev/null +++ b/internal/services/applicationinsights/application_insights_workbook_template_resource.go @@ -0,0 +1,433 @@ +package applicationinsights + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights" + "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type ApplicationInsightsWorkbookTemplateModel struct { + Name string `tfschema:"name"` + ResourceGroupName string `tfschema:"resource_group_name"` + Author string `tfschema:"author"` + Galleries []WorkbookTemplateGalleryModel `tfschema:"galleries"` + Localized string `tfschema:"localized"` + Location string `tfschema:"location"` + Priority int64 `tfschema:"priority"` + Tags map[string]string `tfschema:"tags"` + TemplateData string `tfschema:"template_data"` +} + +type WorkbookTemplateGalleryModel struct { + Name string `tfschema:"name"` + Category string `tfschema:"category"` + Order int64 `tfschema:"order"` + ResourceType string `tfschema:"resource_type"` + Type string `tfschema:"type"` +} + +type ApplicationInsightsWorkbookTemplateResource struct{} + +var _ sdk.ResourceWithUpdate = ApplicationInsightsWorkbookTemplateResource{} + +func (r ApplicationInsightsWorkbookTemplateResource) ResourceType() string { + return "azurerm_application_insights_workbook_template" +} + +func (r ApplicationInsightsWorkbookTemplateResource) ModelObject() interface{} { + return &ApplicationInsightsWorkbookTemplateModel{} +} + +func (r ApplicationInsightsWorkbookTemplateResource) IDValidationFunc() pluginsdk.SchemaValidateFunc { + return applicationinsights.ValidateWorkbookTemplateID +} + +func (r ApplicationInsightsWorkbookTemplateResource) Arguments() map[string]*pluginsdk.Schema { + return map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "resource_group_name": commonschema.ResourceGroupName(), + + "location": commonschema.Location(), + + "template_data": { + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validation.StringIsJSON, + DiffSuppressFunc: pluginsdk.SuppressJsonDiff, + }, + + "galleries": { + Type: pluginsdk.TypeList, + Required: true, + MinItems: 1, + Elem: &pluginsdk.Resource{ + Schema: map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "category": { + Type: pluginsdk.TypeString, + Required: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "order": { + Type: pluginsdk.TypeInt, + Optional: true, + Default: 0, + }, + + "resource_type": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + Default: "Azure Monitor", + }, + + "type": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + Default: "workbook", + }, + }, + }, + }, + + "author": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "localized": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "priority": { + Type: pluginsdk.TypeInt, + Optional: true, + Default: 0, + }, + + "tags": commonschema.Tags(), + } +} + +func (r ApplicationInsightsWorkbookTemplateResource) Attributes() map[string]*pluginsdk.Schema { + return map[string]*pluginsdk.Schema{} +} + +func (r ApplicationInsightsWorkbookTemplateResource) Create() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 30 * time.Minute, + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + var model ApplicationInsightsWorkbookTemplateModel + if err := metadata.Decode(&model); err != nil { + return fmt.Errorf("decoding: %+v", err) + } + + client := metadata.Client.AppInsights.WorkbookTemplateClient + subscriptionId := metadata.Client.Account.SubscriptionId + id := applicationinsights.NewWorkbookTemplateID(subscriptionId, model.ResourceGroupName, model.Name) + existing, err := client.WorkbookTemplatesGet(ctx, id) + if err != nil && !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for existing %s: %+v", id, err) + } + + if !response.WasNotFound(existing.HttpResponse) { + return metadata.ResourceRequiresImport(r.ResourceType(), id) + } + + var templateDataValue interface{} + err = json.Unmarshal([]byte(model.TemplateData), &templateDataValue) + if err != nil { + return err + } + + properties := &applicationinsights.WorkbookTemplate{ + Location: location.Normalize(model.Location), + Properties: &applicationinsights.WorkbookTemplateProperties{ + Priority: &model.Priority, + TemplateData: templateDataValue, + }, + + Tags: &model.Tags, + } + + if model.Author != "" { + properties.Properties.Author = &model.Author + } + + if model.Localized != "" { + var localizedValue map[string][]applicationinsights.WorkbookTemplateLocalizedGallery + if err := json.Unmarshal([]byte(model.Localized), &localizedValue); err != nil { + return err + } + + properties.Properties.Localized = &localizedValue + } + + galleriesValue, err := expandWorkbookTemplateGalleryModel(model.Galleries) + if err != nil { + return err + } + + if galleriesValue != nil { + properties.Properties.Galleries = *galleriesValue + } + + if _, err := client.WorkbookTemplatesCreateOrUpdate(ctx, id, *properties); err != nil { + return fmt.Errorf("creating %s: %+v", id, err) + } + + metadata.SetID(id) + return nil + }, + } +} + +func (r ApplicationInsightsWorkbookTemplateResource) Update() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 30 * time.Minute, + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + client := metadata.Client.AppInsights.WorkbookTemplateClient + + id, err := applicationinsights.ParseWorkbookTemplateID(metadata.ResourceData.Id()) + if err != nil { + return err + } + + var model ApplicationInsightsWorkbookTemplateModel + if err := metadata.Decode(&model); err != nil { + return fmt.Errorf("decoding: %+v", err) + } + + resp, err := client.WorkbookTemplatesGet(ctx, *id) + if err != nil { + return fmt.Errorf("retrieving %s: %+v", *id, err) + } + + properties := resp.Model + if properties == nil { + return fmt.Errorf("retrieving %s: properties was nil", id) + } + + if metadata.ResourceData.HasChange("author") { + properties.Properties.Author = &model.Author + } + + if metadata.ResourceData.HasChange("galleries") { + galleriesValue, err := expandWorkbookTemplateGalleryModel(model.Galleries) + if err != nil { + return err + } + + if galleriesValue != nil { + properties.Properties.Galleries = *galleriesValue + } + } + + if metadata.ResourceData.HasChange("priority") { + properties.Properties.Priority = &model.Priority + } + + if metadata.ResourceData.HasChange("template_data") { + var templateDataValue interface{} + err := json.Unmarshal([]byte(model.TemplateData), &templateDataValue) + if err != nil { + return err + } + + properties.Properties.TemplateData = templateDataValue + } + + if metadata.ResourceData.HasChange("localized") { + var localizedValue map[string][]applicationinsights.WorkbookTemplateLocalizedGallery + if err := json.Unmarshal([]byte(model.Localized), &localizedValue); err != nil { + return err + } + + properties.Properties.Localized = &localizedValue + } + + if metadata.ResourceData.HasChange("tags") { + properties.Tags = &model.Tags + } + + if _, err := client.WorkbookTemplatesCreateOrUpdate(ctx, *id, *properties); err != nil { + return fmt.Errorf("updating %s: %+v", *id, err) + } + + return nil + }, + } +} + +func (r ApplicationInsightsWorkbookTemplateResource) Read() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 5 * time.Minute, + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + client := metadata.Client.AppInsights.WorkbookTemplateClient + + id, err := applicationinsights.ParseWorkbookTemplateID(metadata.ResourceData.Id()) + if err != nil { + return err + } + + resp, err := client.WorkbookTemplatesGet(ctx, *id) + if err != nil { + if response.WasNotFound(resp.HttpResponse) { + return metadata.MarkAsGone(id) + } + + return fmt.Errorf("retrieving %s: %+v", *id, err) + } + + model := resp.Model + if model == nil { + return fmt.Errorf("retrieving %s: model was nil", id) + } + + state := ApplicationInsightsWorkbookTemplateModel{ + Name: id.ResourceName, + ResourceGroupName: id.ResourceGroupName, + Location: location.Normalize(model.Location), + } + + if properties := model.Properties; properties != nil { + if properties.Author != nil { + state.Author = *properties.Author + } + + galleriesValue, err := flattenWorkbookTemplateGalleryModel(&properties.Galleries) + if err != nil { + return err + } + + state.Galleries = galleriesValue + + if properties.Priority != nil { + state.Priority = *properties.Priority + } + + if properties.TemplateData != nil { + templateDataValue, err := json.Marshal(properties.TemplateData) + if err != nil { + return err + } + + state.TemplateData = string(templateDataValue) + } + + if properties.Localized != nil { + localizedValue, err := json.Marshal(properties.Localized) + if err != nil { + return err + } + + state.Localized = string(localizedValue) + } + } + + if model.Tags != nil { + state.Tags = *model.Tags + } + + return metadata.Encode(&state) + }, + } +} + +func (r ApplicationInsightsWorkbookTemplateResource) Delete() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 30 * time.Minute, + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + client := metadata.Client.AppInsights.WorkbookTemplateClient + + id, err := applicationinsights.ParseWorkbookTemplateID(metadata.ResourceData.Id()) + if err != nil { + return err + } + + if _, err := client.WorkbookTemplatesDelete(ctx, *id); err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) + } + + return nil + }, + } +} + +func expandWorkbookTemplateGalleryModel(inputList []WorkbookTemplateGalleryModel) (*[]applicationinsights.WorkbookTemplateGallery, error) { + var outputList []applicationinsights.WorkbookTemplateGallery + for _, input := range inputList { + output := applicationinsights.WorkbookTemplateGallery{ + Category: utils.String(input.Category), + Name: utils.String(input.Name), + Order: utils.Int64(input.Order), + ResourceType: utils.String(input.ResourceType), + Type: utils.String(input.Type), + } + + outputList = append(outputList, output) + } + + return &outputList, nil +} + +func flattenWorkbookTemplateGalleryModel(inputList *[]applicationinsights.WorkbookTemplateGallery) ([]WorkbookTemplateGalleryModel, error) { + var outputList []WorkbookTemplateGalleryModel + if inputList == nil { + return outputList, nil + } + + for _, input := range *inputList { + output := WorkbookTemplateGalleryModel{} + + if input.Category != nil { + output.Category = *input.Category + } + + if input.Name != nil { + output.Name = *input.Name + } + + if input.Order != nil { + output.Order = *input.Order + } + + if input.ResourceType != nil { + output.ResourceType = *input.ResourceType + } + + if input.Type != nil { + output.Type = *input.Type + } + + outputList = append(outputList, output) + } + + return outputList, nil +} diff --git a/internal/services/applicationinsights/application_insights_workbook_template_resource_test.go b/internal/services/applicationinsights/application_insights_workbook_template_resource_test.go new file mode 100644 index 000000000000..64fef725c218 --- /dev/null +++ b/internal/services/applicationinsights/application_insights_workbook_template_resource_test.go @@ -0,0 +1,320 @@ +package applicationinsights_test + +import ( + "context" + "fmt" + "testing" + + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type ApplicationInsightsWorkbookTemplateResource struct{} + +func TestAccApplicationInsightsWorkbookTemplate_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_application_insights_workbook_template", "test") + r := ApplicationInsightsWorkbookTemplateResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccApplicationInsightsWorkbookTemplate_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_application_insights_workbook_template", "test") + r := ApplicationInsightsWorkbookTemplateResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.RequiresImportErrorStep(r.requiresImport), + }) +} + +func TestAccApplicationInsightsWorkbookTemplate_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_application_insights_workbook_template", "test") + r := ApplicationInsightsWorkbookTemplateResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.complete(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccApplicationInsightsWorkbookTemplate_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_application_insights_workbook_template", "test") + r := ApplicationInsightsWorkbookTemplateResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.complete(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.update(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func (r ApplicationInsightsWorkbookTemplateResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { + id, err := applicationinsights.ParseWorkbookTemplateID(state.ID) + if err != nil { + return nil, err + } + + client := clients.AppInsights.WorkbookTemplateClient + resp, err := client.WorkbookTemplatesGet(ctx, *id) + if err != nil { + if response.WasNotFound(resp.HttpResponse) { + return utils.Bool(false), nil + } + return nil, fmt.Errorf("retrieving %s: %+v", id, err) + } + return utils.Bool(resp.Model != nil), nil +} + +func (r ApplicationInsightsWorkbookTemplateResource) template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctest-rg-%d" + location = "%s" +} +`, data.RandomInteger, data.Locations.Primary) +} + +func (r ApplicationInsightsWorkbookTemplateResource) basic(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` + %s + +resource "azurerm_application_insights_workbook_template" "test" { + name = "acctest-aiwt-%d" + resource_group_name = azurerm_resource_group.test.name + location = "%s" + + galleries { + category = "workbook" + name = "test" + } + + template_data = jsonencode({ + "version" : "Notebook/1.0", + "items" : [ + { + "type" : 1, + "content" : { + "json" : "## New workbook\n---\n\nWelcome to your new workbook." + }, + "name" : "text - 2" + } + ], + "styleSettings" : {}, + "$schema" : "https://github.com/Microsoft/Application-Insights-Workbooks/blob/master/schema/workbook.json" + }) +} +`, template, data.RandomInteger, data.Locations.Primary) +} + +func (r ApplicationInsightsWorkbookTemplateResource) requiresImport(data acceptance.TestData) string { + config := r.basic(data) + return fmt.Sprintf(` + %s + +resource "azurerm_application_insights_workbook_template" "import" { + name = azurerm_application_insights_workbook_template.test.name + resource_group_name = azurerm_application_insights_workbook_template.test.resource_group_name + location = azurerm_application_insights_workbook_template.test.location + + galleries { + category = "workbook" + name = "test" + } + + template_data = jsonencode({ + "version" : "Notebook/1.0", + "items" : [ + { + "type" : 1, + "content" : { + "json" : "## New workbook\n---\n\nWelcome to your new workbook." + }, + "name" : "text - 2" + } + ], + "styleSettings" : {}, + "$schema" : "https://github.com/Microsoft/Application-Insights-Workbooks/blob/master/schema/workbook.json" + }) +} +`, config) +} + +func (r ApplicationInsightsWorkbookTemplateResource) complete(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` + %s + +resource "azurerm_application_insights_workbook_template" "test" { + name = "acctest-aiwt-%d" + resource_group_name = azurerm_resource_group.test.name + location = "%s" + author = "test author" + priority = 1 + + galleries { + category = "Failures" + name = "test" + order = 100 + resource_type = "microsoft.insights/components" + type = "tsg" + } + + template_data = jsonencode({ + "version" : "Notebook/1.0", + "items" : [ + { + "type" : 1, + "content" : { + "json" : "## New workbook\n---\n\nWelcome to your new workbook." + }, + "name" : "text - 2" + } + ], + "styleSettings" : {}, + "$schema" : "https://github.com/Microsoft/Application-Insights-Workbooks/blob/master/schema/workbook.json" + }) + + localized = jsonencode({ + "ar" : [ + { + "galleries" : [ + { + "name" : "test", + "category" : "Failures", + "type" : "tsg", + "resourceType" : "microsoft.insights/components", + "order" : 100 + } + ], + "templateData" : { + "version" : "Notebook/1.0", + "items" : [ + { + "type" : 1, + "content" : { + "json" : "## New workbook\n---\n\nWelcome to your new workbook." + }, + "name" : "text - 2" + } + ], + "styleSettings" : {}, + "$schema" : "https://github.com/Microsoft/Application-Insights-Workbooks/blob/master/schema/workbook.json" + }, + } + ] + }) + + tags = { + key = "value" + } +} +`, template, data.RandomInteger, data.Locations.Primary) +} + +func (r ApplicationInsightsWorkbookTemplateResource) update(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` + %s + +resource "azurerm_application_insights_workbook_template" "test" { + name = "acctest-aiwt-%d" + resource_group_name = azurerm_resource_group.test.name + location = "%s" + author = "test author 2" + priority = 2 + + galleries { + category = "workbook" + name = "test2" + order = 200 + resource_type = "Azure Monitor" + type = "workbook" + } + + template_data = jsonencode({ + "version" : "Notebook/1.0", + "items" : [ + { + "type" : 2, + "content" : { + "json" : "## New workbook\n---\n\nWelcome to your new workbook." + }, + "name" : "text - 2" + } + ], + "styleSettings" : {}, + "$schema" : "https://github.com/Microsoft/Application-Insights-Workbooks/blob/master/schema/workbook.json" + }) + + localized = jsonencode({ + "en-US" : [ + { + "galleries" : [ + { + "name" : "test2", + "category" : "workbook", + "type" : "workbook", + "resourceType" : "Azure Monitor", + "order" : 200 + } + ], + "templateData" : { + "version" : "Notebook/1.0", + "items" : [ + { + "type" : 2, + "content" : { + "json" : "## New workbook\n---\n\nWelcome to your new workbook." + }, + "name" : "text - 2" + } + ], + "styleSettings" : {}, + "$schema" : "https://github.com/Microsoft/Application-Insights-Workbooks/blob/master/schema/workbook.json" + }, + } + ] + }) + + tags = { + key = "value2" + } +} +`, template, data.RandomInteger, data.Locations.Primary) +} diff --git a/internal/services/applicationinsights/client/client.go b/internal/services/applicationinsights/client/client.go index 4907c213e532..8f69466b6aaa 100644 --- a/internal/services/applicationinsights/client/client.go +++ b/internal/services/applicationinsights/client/client.go @@ -2,6 +2,7 @@ package client import ( "github.com/Azure/azure-sdk-for-go/services/appinsights/mgmt/2020-02-02/insights" + workbookTemplate "github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights" "github.com/hashicorp/terraform-provider-azurerm/internal/common" "github.com/hashicorp/terraform-provider-azurerm/internal/services/applicationinsights/azuresdkhacks" ) @@ -13,6 +14,7 @@ type Client struct { WebTestsClient *azuresdkhacks.WebTestsClient BillingClient *insights.ComponentCurrentBillingFeaturesClient SmartDetectionRuleClient *insights.ProactiveDetectionConfigurationsClient + WorkbookTemplateClient *workbookTemplate.ApplicationInsightsClient } func NewClient(o *common.ClientOptions) *Client { @@ -35,6 +37,9 @@ func NewClient(o *common.ClientOptions) *Client { smartDetectionRuleClient := insights.NewProactiveDetectionConfigurationsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&smartDetectionRuleClient.Client, o.ResourceManagerAuthorizer) + workbookTemplateClient := workbookTemplate.NewApplicationInsightsClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&workbookTemplateClient.Client, o.ResourceManagerAuthorizer) + return &Client{ AnalyticsItemsClient: &analyticsItemsClient, APIKeysClient: &apiKeysClient, @@ -42,5 +47,6 @@ func NewClient(o *common.ClientOptions) *Client { WebTestsClient: &webTestsWorkaroundClient, BillingClient: &billingClient, SmartDetectionRuleClient: &smartDetectionRuleClient, + WorkbookTemplateClient: &workbookTemplateClient, } } diff --git a/internal/services/applicationinsights/registration.go b/internal/services/applicationinsights/registration.go index 061f12d459d0..cc0f01206e8c 100644 --- a/internal/services/applicationinsights/registration.go +++ b/internal/services/applicationinsights/registration.go @@ -7,7 +7,10 @@ import ( type Registration struct{} -var _ sdk.UntypedServiceRegistrationWithAGitHubLabel = Registration{} +var ( + _ sdk.TypedServiceRegistrationWithAGitHubLabel = Registration{} + _ sdk.UntypedServiceRegistrationWithAGitHubLabel = Registration{} +) func (r Registration) AssociatedGitHubLabel() string { return "service/application-insights" @@ -42,3 +45,15 @@ func (r Registration) SupportedResources() map[string]*pluginsdk.Resource { "azurerm_application_insights_web_test": resourceApplicationInsightsWebTests(), } } + +// DataSources returns a list of Data Sources supported by this Service +func (r Registration) DataSources() []sdk.DataSource { + return []sdk.DataSource{} +} + +// Resources returns a list of Resources supported by this Service +func (r Registration) Resources() []sdk.Resource { + return []sdk.Resource{ + ApplicationInsightsWorkbookTemplateResource{}, + } +} diff --git a/internal/services/appservice/helpers/fx_strings.go b/internal/services/appservice/helpers/fx_strings.go index 58e9868d0e96..eae7b2db00e6 100644 --- a/internal/services/appservice/helpers/fx_strings.go +++ b/internal/services/appservice/helpers/fx_strings.go @@ -53,7 +53,7 @@ func decodeApplicationStackLinux(fxString string) ApplicationStackLinux { } func EncodeFunctionAppLinuxFxVersion(input []ApplicationStackLinuxFunctionApp) *string { - if len(input) == 0 { + if len(input) == 0 || input[0].CustomHandler { return utils.String("") } diff --git a/internal/services/appservice/helpers/web_app_schema.go b/internal/services/appservice/helpers/web_app_schema.go index 023cb51f3cbd..e26bf287988e 100644 --- a/internal/services/appservice/helpers/web_app_schema.go +++ b/internal/services/appservice/helpers/web_app_schema.go @@ -2856,7 +2856,7 @@ func httpLogBlobStorageSchemaComputed() *pluginsdk.Schema { } } -func ExpandSiteConfigWindows(siteConfig []SiteConfigWindows, existing *web.SiteConfig, metadata sdk.ResourceMetaData) (*web.SiteConfig, *string, error) { +func ExpandSiteConfigWindows(siteConfig []SiteConfigWindows, existing *web.SiteConfig, metadata sdk.ResourceMetaData, servicePlan web.AppServicePlan) (*web.SiteConfig, *string, error) { if len(siteConfig) == 0 { return nil, nil, nil } @@ -2870,6 +2870,16 @@ func ExpandSiteConfigWindows(siteConfig []SiteConfigWindows, existing *web.SiteC winSiteConfig := siteConfig[0] + if servicePlan.Sku != nil && servicePlan.Sku.Name != nil { + if isFreeOrSharedServicePlan(*servicePlan.Sku.Name) { + if winSiteConfig.AlwaysOn == true { + return nil, nil, fmt.Errorf("always_on cannot be set to true when using Free, F1, D1 Sku") + } + if expanded.AlwaysOn != nil && *expanded.AlwaysOn == true { + return nil, nil, fmt.Errorf("always_on feature has to be turned off before switching to a free/shared Sku") + } + } + } expanded.AlwaysOn = utils.Bool(winSiteConfig.AlwaysOn) if metadata.ResourceData.HasChange("site_config.0.api_management_api_id") { @@ -3012,7 +3022,7 @@ func ExpandSiteConfigWindows(siteConfig []SiteConfigWindows, existing *web.SiteC return expanded, ¤tStack, nil } -func ExpandSiteConfigLinux(siteConfig []SiteConfigLinux, existing *web.SiteConfig, metadata sdk.ResourceMetaData) (*web.SiteConfig, error) { +func ExpandSiteConfigLinux(siteConfig []SiteConfigLinux, existing *web.SiteConfig, metadata sdk.ResourceMetaData, servicePlan web.AppServicePlan) (*web.SiteConfig, error) { if len(siteConfig) == 0 { return nil, nil } @@ -3023,6 +3033,16 @@ func ExpandSiteConfigLinux(siteConfig []SiteConfigLinux, existing *web.SiteConfi linuxSiteConfig := siteConfig[0] + if servicePlan.Sku != nil && servicePlan.Sku.Name != nil { + if isFreeOrSharedServicePlan(*servicePlan.Sku.Name) { + if linuxSiteConfig.AlwaysOn == true { + return nil, fmt.Errorf("always_on cannot be set to true when using Free, F1, D1 Sku") + } + if expanded.AlwaysOn != nil && *expanded.AlwaysOn == true { + return nil, fmt.Errorf("always_on feature has to be turned off before switching to a free/shared Sku") + } + } + } expanded.AlwaysOn = utils.Bool(linuxSiteConfig.AlwaysOn) if metadata.ResourceData.HasChange("site_config.0.api_management_api_id") { @@ -4211,3 +4231,18 @@ func DisabledLogsConfig() *web.SiteLogsConfig { }, } } + +func isFreeOrSharedServicePlan(inputSKU string) bool { + result := false + for _, sku := range freeSkus { + if inputSKU == sku { + result = true + } + } + for _, sku := range sharedSkus { + if inputSKU == sku { + result = true + } + } + return result +} diff --git a/internal/services/appservice/linux_function_app_data_source.go b/internal/services/appservice/linux_function_app_data_source.go index e52185a77955..89bcfbb5b33c 100644 --- a/internal/services/appservice/linux_function_app_data_source.go +++ b/internal/services/appservice/linux_function_app_data_source.go @@ -295,16 +295,18 @@ func (d LinuxFunctionAppDataSource) Read() sdk.ResourceFunc { } state := LinuxFunctionAppDataSourceModel{ - Name: id.SiteName, - ResourceGroup: id.ResourceGroup, - ServicePlanId: utils.NormalizeNilableString(props.ServerFarmID), - Location: location.NormalizeNilable(functionApp.Location), - Enabled: utils.NormaliseNilableBool(functionApp.Enabled), - ClientCertMode: string(functionApp.ClientCertMode), - DailyMemoryTimeQuota: int(utils.NormaliseNilableInt32(props.DailyMemoryTimeQuota)), - StickySettings: helpers.FlattenStickySettings(stickySettings.SlotConfigNames), - Tags: tags.ToTypedObject(functionApp.Tags), - Kind: utils.NormalizeNilableString(functionApp.Kind), + Name: id.SiteName, + ResourceGroup: id.ResourceGroup, + ServicePlanId: utils.NormalizeNilableString(props.ServerFarmID), + Location: location.NormalizeNilable(functionApp.Location), + Enabled: utils.NormaliseNilableBool(functionApp.Enabled), + ClientCertMode: string(functionApp.ClientCertMode), + DailyMemoryTimeQuota: int(utils.NormaliseNilableInt32(props.DailyMemoryTimeQuota)), + StickySettings: helpers.FlattenStickySettings(stickySettings.SlotConfigNames), + Tags: tags.ToTypedObject(functionApp.Tags), + Kind: utils.NormalizeNilableString(functionApp.Kind), + CustomDomainVerificationId: utils.NormalizeNilableString(props.CustomDomainVerificationID), + DefaultHostname: utils.NormalizeNilableString(functionApp.DefaultHostName), } configResp, err := client.GetConfiguration(ctx, id.ResourceGroup, id.SiteName) diff --git a/internal/services/appservice/linux_function_app_data_source_test.go b/internal/services/appservice/linux_function_app_data_source_test.go index 2bbfdbd4ed1d..aa29c992a841 100644 --- a/internal/services/appservice/linux_function_app_data_source_test.go +++ b/internal/services/appservice/linux_function_app_data_source_test.go @@ -19,6 +19,7 @@ func TestAccLinuxFunctionAppDataSource_standardComplete(t *testing.T) { Config: d.standardComplete(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).Key("location").HasValue(data.Locations.Primary), + check.That(data.ResourceName).Key("default_hostname").HasValue(fmt.Sprintf("acctest-lfa-%d.azurewebsites.net", data.RandomInteger)), ), }, }) diff --git a/internal/services/appservice/linux_function_app_resource.go b/internal/services/appservice/linux_function_app_resource.go index e19c384c084a..7296966de840 100644 --- a/internal/services/appservice/linux_function_app_resource.go +++ b/internal/services/appservice/linux_function_app_resource.go @@ -591,6 +591,8 @@ func (r LinuxFunctionAppResource) Read() sdk.ResourceFunc { Tags: tags.ToTypedObject(functionApp.Tags), Kind: utils.NormalizeNilableString(functionApp.Kind), KeyVaultReferenceIdentityID: utils.NormalizeNilableString(props.KeyVaultReferenceIdentity), + CustomDomainVerificationId: utils.NormalizeNilableString(props.CustomDomainVerificationID), + DefaultHostname: utils.NormalizeNilableString(props.DefaultHostName), } configResp, err := client.GetConfiguration(ctx, id.ResourceGroup, id.SiteName) @@ -975,10 +977,11 @@ func (m *LinuxFunctionAppModel) unpackLinuxFunctionAppSettings(input web.StringD } case "WEBSITE_HTTPLOGGING_RETENTION_DAYS": case "FUNCTIONS_WORKER_RUNTIME": - if len(m.SiteConfig) > 0 && len(m.SiteConfig[0].ApplicationStack) > 0 { - m.SiteConfig[0].ApplicationStack[0].CustomHandler = strings.EqualFold(*v, "custom") + if len(m.SiteConfig) > 0 && len(m.SiteConfig[0].ApplicationStack) == 0 { + if *v == "custom" { + m.SiteConfig[0].ApplicationStack = []helpers.ApplicationStackLinuxFunctionApp{{CustomHandler: true}} + } } - if _, ok := metadata.ResourceData.GetOk("app_settings.FUNCTIONS_WORKER_RUNTIME"); ok { appSettings[k] = utils.NormalizeNilableString(v) } diff --git a/internal/services/appservice/linux_function_app_resource_test.go b/internal/services/appservice/linux_function_app_resource_test.go index 5a7338a069a8..c99013c45f94 100644 --- a/internal/services/appservice/linux_function_app_resource_test.go +++ b/internal/services/appservice/linux_function_app_resource_test.go @@ -770,6 +770,22 @@ func TestAccLinuxFunctionApp_appStackDotNet31(t *testing.T) { }) } +func TestAccLinuxFunctionApp_appStackCustom(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_linux_function_app", "test") + r := LinuxFunctionAppResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.appStackCustom(data, SkuBasicPlan), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + check.That(data.ResourceName).Key("kind").HasValue("functionapp,linux"), + ), + }, + data.ImportStep(), + }) +} + func TestAccLinuxFunctionApp_appStackDotNet6(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_linux_function_app", "test") r := LinuxFunctionAppResource{} @@ -1792,6 +1808,32 @@ resource "azurerm_linux_function_app" "test" { `, r.template(data, planSku), data.RandomInteger, version) } +func (r LinuxFunctionAppResource) appStackCustom(data acceptance.TestData, planSku string) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +%s + +resource "azurerm_linux_function_app" "test" { + name = "acctest-LFA-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + service_plan_id = azurerm_service_plan.test.id + + storage_account_name = azurerm_storage_account.test.name + storage_account_access_key = azurerm_storage_account.test.primary_access_key + + site_config { + application_stack { + use_custom_runtime = true + } + } +} +`, r.template(data, planSku), data.RandomInteger) +} + func (r LinuxFunctionAppResource) appStackDotNetIsolated(data acceptance.TestData, planSku string, version string) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/appservice/linux_function_app_slot_resource.go b/internal/services/appservice/linux_function_app_slot_resource.go index 3c60f8b0fa21..6924a4338781 100644 --- a/internal/services/appservice/linux_function_app_slot_resource.go +++ b/internal/services/appservice/linux_function_app_slot_resource.go @@ -567,6 +567,8 @@ func (r LinuxFunctionAppSlotResource) Read() sdk.ResourceFunc { Tags: tags.ToTypedObject(functionApp.Tags), Kind: utils.NormalizeNilableString(functionApp.Kind), KeyVaultReferenceIdentityID: utils.NormalizeNilableString(props.KeyVaultReferenceIdentity), + CustomDomainVerificationId: utils.NormalizeNilableString(props.CustomDomainVerificationID), + DefaultHostname: utils.NormalizeNilableString(props.DefaultHostName), } configResp, err := client.GetConfigurationSlot(ctx, id.ResourceGroup, id.SiteName, id.SlotName) @@ -822,8 +824,10 @@ func (m *LinuxFunctionAppSlotModel) unpackLinuxFunctionAppSettings(input web.Str case "WEBSITE_HTTPLOGGING_RETENTION_DAYS": case "FUNCTIONS_WORKER_RUNTIME": - if m.SiteConfig[0].ApplicationStack != nil && len(m.SiteConfig[0].ApplicationStack) > 0 { - m.SiteConfig[0].ApplicationStack[0].CustomHandler = strings.EqualFold(*v, "custom") + if len(m.SiteConfig) > 0 && len(m.SiteConfig[0].ApplicationStack) == 0 { + if *v == "custom" { + m.SiteConfig[0].ApplicationStack = []helpers.ApplicationStackLinuxFunctionApp{{CustomHandler: true}} + } } if _, ok := metadata.ResourceData.GetOk("app_settings.FUNCTIONS_WORKER_RUNTIME"); ok { appSettings[k] = utils.NormalizeNilableString(v) diff --git a/internal/services/appservice/linux_function_app_slot_resource_test.go b/internal/services/appservice/linux_function_app_slot_resource_test.go index 49e4d2584a6a..3c0d36d44b8f 100644 --- a/internal/services/appservice/linux_function_app_slot_resource_test.go +++ b/internal/services/appservice/linux_function_app_slot_resource_test.go @@ -601,6 +601,22 @@ func TestAccLinuxFunctionAppSlot_appStackDotNet31(t *testing.T) { }) } +func TestAccLinuxFunctionAppSlot_appStackCustom(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_linux_function_app_slot", "test") + r := LinuxFunctionAppSlotResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.appStackCustom(data, SkuStandardPlan), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + check.That(data.ResourceName).Key("kind").HasValue("functionapp,linux"), + ), + }, + data.ImportStep(), + }) +} + func TestAccLinuxFunctionAppSlot_appStackDotNet6(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_linux_function_app_slot", "test") r := LinuxFunctionAppSlotResource{} @@ -1291,6 +1307,29 @@ resource "azurerm_linux_function_app_slot" "test" { `, r.template(data, planSku), data.RandomInteger, version) } +func (r LinuxFunctionAppSlotResource) appStackCustom(data acceptance.TestData, planSku string) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +%s + +resource "azurerm_linux_function_app_slot" "test" { + name = "acctest-LFAS-%d" + function_app_id = azurerm_linux_function_app.test.id + storage_account_name = azurerm_storage_account.test.name + storage_account_access_key = azurerm_storage_account.test.primary_access_key + + site_config { + application_stack { + use_custom_runtime = true + } + } +} +`, r.template(data, planSku), data.RandomInteger) +} + func (r LinuxFunctionAppSlotResource) appStackDotNetIsolated(data acceptance.TestData, planSku string, version string) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/appservice/linux_web_app_resource.go b/internal/services/appservice/linux_web_app_resource.go index ae3641c57936..f6f1917396d8 100644 --- a/internal/services/appservice/linux_web_app_resource.go +++ b/internal/services/appservice/linux_web_app_resource.go @@ -293,7 +293,7 @@ func (r LinuxWebAppResource) Create() sdk.ResourceFunc { return fmt.Errorf("the Site Name %q failed the availability check: %+v", id.SiteName, *checkName.Message) } - siteConfig, err := helpers.ExpandSiteConfigLinux(webApp.SiteConfig, nil, metadata) + siteConfig, err := helpers.ExpandSiteConfigLinux(webApp.SiteConfig, nil, metadata, servicePlan) if err != nil { return err } @@ -586,6 +586,7 @@ func (r LinuxWebAppResource) Update() sdk.ResourceFunc { Timeout: 30 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { client := metadata.Client.AppService.WebAppsClient + servicePlanClient := metadata.Client.AppService.ServicePlanClient id, err := parse.WebAppID(metadata.ResourceData.Id()) if err != nil { @@ -604,9 +605,26 @@ func (r LinuxWebAppResource) Update() sdk.ResourceFunc { return fmt.Errorf("reading Linux %s: %v", id, err) } + var serviceFarmId string + servicePlanChange := false + if existing.SiteProperties.ServerFarmID != nil { + serviceFarmId = *existing.ServerFarmID + } if metadata.ResourceData.HasChange("service_plan_id") { - existing.SiteProperties.ServerFarmID = utils.String(state.ServicePlanId) + serviceFarmId = state.ServicePlanId + existing.SiteProperties.ServerFarmID = utils.String(serviceFarmId) + servicePlanChange = true + } + servicePlanId, err := parse.ServicePlanID(serviceFarmId) + if err != nil { + return err } + + servicePlan, err := servicePlanClient.Get(ctx, servicePlanId.ResourceGroup, servicePlanId.ServerfarmName) + if err != nil { + return fmt.Errorf("reading App %s: %+v", servicePlanId, err) + } + if metadata.ResourceData.HasChange("enabled") { existing.SiteProperties.Enabled = utils.Bool(state.Enabled) } @@ -639,8 +657,8 @@ func (r LinuxWebAppResource) Update() sdk.ResourceFunc { existing.Tags = tags.FromTypedObject(state.Tags) } - if metadata.ResourceData.HasChange("site_config") { - siteConfig, err := helpers.ExpandSiteConfigLinux(state.SiteConfig, existing.SiteConfig, metadata) + if metadata.ResourceData.HasChange("site_config") || servicePlanChange { + siteConfig, err := helpers.ExpandSiteConfigLinux(state.SiteConfig, existing.SiteConfig, metadata, servicePlan) if err != nil { return fmt.Errorf("expanding Site Config for Linux %s: %+v", id, err) } diff --git a/internal/services/appservice/linux_web_app_resource_test.go b/internal/services/appservice/linux_web_app_resource_test.go index d4a71668bcf3..a276dfd801a2 100644 --- a/internal/services/appservice/linux_web_app_resource_test.go +++ b/internal/services/appservice/linux_web_app_resource_test.go @@ -3,6 +3,7 @@ package appservice_test import ( "context" "fmt" + "regexp" "testing" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" @@ -31,6 +32,18 @@ func TestAccLinuxWebApp_basic(t *testing.T) { }) } +func TestAccLinuxWebApp_freeSkuAlwaysOnShouldFail(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_linux_web_app", "test") + r := LinuxWebAppResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.linuxFreeSku(data), + ExpectError: regexp.MustCompile("always_on cannot be set to true when using Free, F1, D1 Sku"), + }, + }) +} + func TestAccLinuxWebApp_complete(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_linux_web_app", "test") r := LinuxWebAppResource{} @@ -1189,6 +1202,25 @@ resource "azurerm_linux_web_app" "test" { `, r.baseTemplate(data), data.RandomInteger) } +func (r LinuxWebAppResource) linuxFreeSku(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +%s + +resource "azurerm_linux_web_app" "test" { + name = "acctestWA-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + service_plan_id = azurerm_service_plan.test.id + + site_config {} +} +`, r.linuxFreeSkuTemplate(data), data.RandomInteger) +} + func (r LinuxWebAppResource) basicWithStorage(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { @@ -2744,6 +2776,24 @@ resource "azurerm_service_plan" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } +func (LinuxWebAppResource) linuxFreeSkuTemplate(data acceptance.TestData) string { + return fmt.Sprintf(` + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_plan" "test" { + name = "acctestASP-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + os_type = "Linux" + sku_name = "F1" +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} + func (LinuxWebAppResource) standardPlanTemplate(data acceptance.TestData) string { return fmt.Sprintf(` diff --git a/internal/services/appservice/linux_web_app_slot_resource.go b/internal/services/appservice/linux_web_app_slot_resource.go index 1893b22b2ac9..ef686bce20a2 100644 --- a/internal/services/appservice/linux_web_app_slot_resource.go +++ b/internal/services/appservice/linux_web_app_slot_resource.go @@ -7,11 +7,9 @@ import ( "strings" "time" + "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - - "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/appservice/helpers" "github.com/hashicorp/terraform-provider-azurerm/internal/services/appservice/parse" diff --git a/internal/services/appservice/windows_function_app_data_source.go b/internal/services/appservice/windows_function_app_data_source.go index b7d2a30cbbc5..b82be7e16eef 100644 --- a/internal/services/appservice/windows_function_app_data_source.go +++ b/internal/services/appservice/windows_function_app_data_source.go @@ -256,6 +256,7 @@ func (d WindowsFunctionAppDataSource) Read() sdk.ResourceFunc { functionApp.Tags = tags.ToTypedObject(existing.Tags) functionApp.Kind = utils.NormalizeNilableString(existing.Kind) functionApp.CustomDomainVerificationId = utils.NormalizeNilableString(props.CustomDomainVerificationID) + functionApp.DefaultHostname = utils.NormalizeNilableString(props.DefaultHostName) appSettingsResp, err := client.ListApplicationSettings(ctx, id.ResourceGroup, id.SiteName) if err != nil { diff --git a/internal/services/appservice/windows_function_app_data_source_test.go b/internal/services/appservice/windows_function_app_data_source_test.go index ea762ce65d59..b8ab54af0115 100644 --- a/internal/services/appservice/windows_function_app_data_source_test.go +++ b/internal/services/appservice/windows_function_app_data_source_test.go @@ -19,6 +19,7 @@ func TestAccWindowsFunctionAppDataSource_complete(t *testing.T) { Config: d.complete(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).Key("location").HasValue(data.Locations.Primary), + check.That(data.ResourceName).Key("default_hostname").HasValue(fmt.Sprintf("acctest-wfa-%d.azurewebsites.net", data.RandomInteger)), ), }, }) diff --git a/internal/services/appservice/windows_function_app_resource.go b/internal/services/appservice/windows_function_app_resource.go index 39e0f8f831ba..cfd3422eca33 100644 --- a/internal/services/appservice/windows_function_app_resource.go +++ b/internal/services/appservice/windows_function_app_resource.go @@ -7,10 +7,9 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" - "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" "github.com/google/uuid" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" @@ -591,6 +590,7 @@ func (r WindowsFunctionAppResource) Read() sdk.ResourceFunc { Kind: utils.NormalizeNilableString(functionApp.Kind), KeyVaultReferenceIdentityID: utils.NormalizeNilableString(props.KeyVaultReferenceIdentity), CustomDomainVerificationId: utils.NormalizeNilableString(props.CustomDomainVerificationID), + DefaultHostname: utils.NormalizeNilableString(props.DefaultHostName), } configResp, err := client.GetConfiguration(ctx, id.ResourceGroup, id.SiteName) diff --git a/internal/services/appservice/windows_function_app_slot_resource.go b/internal/services/appservice/windows_function_app_slot_resource.go index a6d324b7c6a3..675eb013e537 100644 --- a/internal/services/appservice/windows_function_app_slot_resource.go +++ b/internal/services/appservice/windows_function_app_slot_resource.go @@ -7,10 +7,9 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" - "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" "github.com/google/uuid" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/appservice/helpers" @@ -575,6 +574,7 @@ func (r WindowsFunctionAppSlotResource) Read() sdk.ResourceFunc { Kind: utils.NormalizeNilableString(functionAppSlot.Kind), KeyVaultReferenceIdentityID: utils.NormalizeNilableString(props.KeyVaultReferenceIdentity), CustomDomainVerificationId: utils.NormalizeNilableString(props.CustomDomainVerificationID), + DefaultHostname: utils.NormalizeNilableString(props.DefaultHostName), } configResp, err := client.GetConfigurationSlot(ctx, id.ResourceGroup, id.SiteName, id.SlotName) diff --git a/internal/services/appservice/windows_web_app_resource.go b/internal/services/appservice/windows_web_app_resource.go index 29dc7b3c1751..a730feb630a9 100644 --- a/internal/services/appservice/windows_web_app_resource.go +++ b/internal/services/appservice/windows_web_app_resource.go @@ -282,7 +282,7 @@ func (r WindowsWebAppResource) Create() sdk.ResourceFunc { return fmt.Errorf("the Site Name %q failed the availability check: %+v", id.SiteName, *checkName.Message) } - siteConfig, currentStack, err := helpers.ExpandSiteConfigWindows(webApp.SiteConfig, nil, metadata) + siteConfig, currentStack, err := helpers.ExpandSiteConfigWindows(webApp.SiteConfig, nil, metadata, servicePlan) if err != nil { return err } @@ -584,6 +584,7 @@ func (r WindowsWebAppResource) Update() sdk.ResourceFunc { Timeout: 30 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { client := metadata.Client.AppService.WebAppsClient + servicePlanClient := metadata.Client.AppService.ServicePlanClient id, err := parse.WebAppID(metadata.ResourceData.Id()) if err != nil { @@ -602,9 +603,26 @@ func (r WindowsWebAppResource) Update() sdk.ResourceFunc { return fmt.Errorf("reading Windows %s: %v", id, err) } + var serviceFarmId string + servicePlanChange := false + if existing.SiteProperties.ServerFarmID != nil { + serviceFarmId = *existing.ServerFarmID + } if metadata.ResourceData.HasChange("service_plan_id") { - existing.SiteProperties.ServerFarmID = utils.String(state.ServicePlanId) + serviceFarmId = state.ServicePlanId + existing.SiteProperties.ServerFarmID = utils.String(serviceFarmId) + servicePlanChange = true } + servicePlanId, err := parse.ServicePlanID(serviceFarmId) + if err != nil { + return err + } + + servicePlan, err := servicePlanClient.Get(ctx, servicePlanId.ResourceGroup, servicePlanId.ServerfarmName) + if err != nil { + return fmt.Errorf("reading App %s: %+v", servicePlanId, err) + } + if metadata.ResourceData.HasChange("enabled") { existing.SiteProperties.Enabled = utils.Bool(state.Enabled) } @@ -638,8 +656,13 @@ func (r WindowsWebAppResource) Update() sdk.ResourceFunc { } currentStack := "" - if metadata.ResourceData.HasChange("site_config") { - siteConfig, stack, err := helpers.ExpandSiteConfigWindows(state.SiteConfig, existing.SiteConfig, metadata) + stateConfig := state.SiteConfig[0] + if len(stateConfig.ApplicationStack) == 1 { + currentStack = stateConfig.ApplicationStack[0].CurrentStack + } + + if metadata.ResourceData.HasChange("site_config") || servicePlanChange { + siteConfig, stack, err := helpers.ExpandSiteConfigWindows(state.SiteConfig, existing.SiteConfig, metadata, servicePlan) if err != nil { return fmt.Errorf("expanding Site Config for Windows %s: %+v", id, err) } diff --git a/internal/services/appservice/windows_web_app_resource_test.go b/internal/services/appservice/windows_web_app_resource_test.go index a1c4025b3437..4b0f031cc828 100644 --- a/internal/services/appservice/windows_web_app_resource_test.go +++ b/internal/services/appservice/windows_web_app_resource_test.go @@ -3,6 +3,7 @@ package appservice_test import ( "context" "fmt" + "regexp" "testing" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" @@ -32,6 +33,18 @@ func TestAccWindowsWebApp_basic(t *testing.T) { }) } +func TestAccWindowsWebApp_freeSkuAlwaysOnShouldFail(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_windows_web_app", "test") + r := WindowsWebAppResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.windowsFreeSku(data), + ExpectError: regexp.MustCompile("always_on cannot be set to true when using Free, F1, D1 Sku"), + }, + }) +} + func TestAccWindowsWebApp_complete(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_windows_web_app", "test") r := WindowsWebAppResource{} @@ -1080,6 +1093,25 @@ resource "azurerm_windows_web_app" "test" { `, r.baseTemplate(data), data.RandomInteger) } +func (r WindowsWebAppResource) windowsFreeSku(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +%s + +resource "azurerm_windows_web_app" "test" { + name = "acctestWA-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + service_plan_id = azurerm_service_plan.test.id + + site_config {} +} +`, r.windowsFreeSkuTemplate(data), data.RandomInteger) +} + func (r WindowsWebAppResource) withBackup(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { @@ -2693,6 +2725,25 @@ resource "azurerm_service_plan" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } +func (WindowsWebAppResource) windowsFreeSkuTemplate(data acceptance.TestData) string { + return fmt.Sprintf(` + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_plan" "test" { + name = "acctestASP-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + os_type = "Windows" + sku_name = "F1" + +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} + func (WindowsWebAppResource) premiumV3PlanContainerTemplate(data acceptance.TestData) string { return fmt.Sprintf(` diff --git a/internal/services/appservice/windows_web_app_slot_resource.go b/internal/services/appservice/windows_web_app_slot_resource.go index 5c34bd5bd126..011c4e5a851c 100644 --- a/internal/services/appservice/windows_web_app_slot_resource.go +++ b/internal/services/appservice/windows_web_app_slot_resource.go @@ -6,9 +6,8 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" - "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/appservice/helpers" @@ -572,6 +571,11 @@ func (r WindowsWebAppSlotResource) Update() sdk.ResourceFunc { } currentStack := "" + stateConfig := state.SiteConfig[0] + if len(stateConfig.ApplicationStack) == 1 { + currentStack = stateConfig.ApplicationStack[0].CurrentStack + } + if metadata.ResourceData.HasChange("site_config") { siteConfig, stack, err := helpers.ExpandSiteConfigWindowsWebAppSlot(state.SiteConfig, existing.SiteConfig, metadata) if err != nil { diff --git a/internal/services/attestation/attestation_provider_resource.go b/internal/services/attestation/attestation_provider_resource.go index 944810132dc9..9e30cc505ccc 100644 --- a/internal/services/attestation/attestation_provider_resource.go +++ b/internal/services/attestation/attestation_provider_resource.go @@ -7,8 +7,6 @@ import ( "log" "time" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/attestation/validate" - "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" @@ -16,6 +14,7 @@ import ( "github.com/hashicorp/go-azure-sdk/resource-manager/attestation/2020-10-01/attestationproviders" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/attestation/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" ) diff --git a/internal/services/cdn/cdn_frontdoor_endpoint_data_source.go b/internal/services/cdn/cdn_frontdoor_endpoint_data_source.go index bedaf8e6c11d..5ec6bebae230 100644 --- a/internal/services/cdn/cdn_frontdoor_endpoint_data_source.go +++ b/internal/services/cdn/cdn_frontdoor_endpoint_data_source.go @@ -5,7 +5,6 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/cdn/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/cdn/validate" diff --git a/internal/services/cdn/cdn_frontdoor_endpoint_resource.go b/internal/services/cdn/cdn_frontdoor_endpoint_resource.go index 5787357a21ad..f05993cd1114 100644 --- a/internal/services/cdn/cdn_frontdoor_endpoint_resource.go +++ b/internal/services/cdn/cdn_frontdoor_endpoint_resource.go @@ -4,9 +4,8 @@ import ( "fmt" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - "github.com/Azure/azure-sdk-for-go/services/cdn/mgmt/2021-06-01/cdn" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/compute/availability_set_data_source.go b/internal/services/compute/availability_set_data_source.go index 7836f9e6c75b..4b396fb1a7ad 100644 --- a/internal/services/compute/availability_set_data_source.go +++ b/internal/services/compute/availability_set_data_source.go @@ -2,19 +2,18 @@ package compute import ( "fmt" - "strconv" "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceAvailabilitySet() *pluginsdk.Resource { @@ -26,26 +25,23 @@ func dataSourceAvailabilitySet() *pluginsdk.Resource { }, Schema: map[string]*pluginsdk.Schema{ - "resource_group_name": commonschema.ResourceGroupNameForDataSource(), - "name": { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringIsNotEmpty, }, - "location": { - Type: pluginsdk.TypeString, - Computed: true, - }, + "resource_group_name": commonschema.ResourceGroupNameForDataSource(), + + "location": commonschema.LocationComputed(), "platform_update_domain_count": { - Type: pluginsdk.TypeString, + Type: pluginsdk.TypeInt, Computed: true, }, "platform_fault_domain_count": { - Type: pluginsdk.TypeString, + Type: pluginsdk.TypeInt, Computed: true, }, @@ -54,7 +50,7 @@ func dataSourceAvailabilitySet() *pluginsdk.Resource { Computed: true, }, - "tags": tags.SchemaDataSource(), + "tags": commonschema.TagsDataSource(), }, } } @@ -65,31 +61,35 @@ func dataSourceAvailabilitySetRead(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewAvailabilitySetID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + id := availabilitysets.NewAvailabilitySetID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + resp, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } - return fmt.Errorf("making Read request on %s: %+v", id, err) + return fmt.Errorf("retrieving %s: %+v", id, err) } d.SetId(id.ID()) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - if resp.Sku != nil && resp.Sku.Name != nil { - d.Set("managed", strings.EqualFold(*resp.Sku.Name, "Aligned")) - } - if props := resp.AvailabilitySetProperties; props != nil { - if v := props.PlatformUpdateDomainCount; v != nil { - d.Set("platform_update_domain_count", strconv.Itoa(int(*v))) + + if model := resp.Model; model != nil { + d.Set("location", location.Normalize(model.Location)) + managed := false + if model.Sku != nil && model.Sku.Name != nil { + managed = strings.EqualFold(*model.Sku.Name, "Aligned") } - if v := props.PlatformFaultDomainCount; v != nil { - d.Set("platform_fault_domain_count", strconv.Itoa(int(*v))) + d.Set("managed", managed) + + if props := model.Properties; props != nil { + d.Set("platform_fault_domain_count", props.PlatformFaultDomainCount) + d.Set("platform_update_domain_count", props.PlatformUpdateDomainCount) + } + + if err := tags.FlattenAndSet(d, model.Tags); err != nil { + return err } } - return tags.FlattenAndSet(d, resp.Tags) + + return nil } diff --git a/internal/services/compute/availability_set_resource.go b/internal/services/compute/availability_set_resource.go index ec3a64de4628..10ca440f4185 100644 --- a/internal/services/compute/availability_set_resource.go +++ b/internal/services/compute/availability_set_resource.go @@ -7,12 +7,13 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" - "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" @@ -27,7 +28,7 @@ func resourceAvailabilitySet() *pluginsdk.Resource { Update: resourceAvailabilitySetCreateUpdate, Delete: resourceAvailabilitySetDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.AvailabilitySetID(id) + _, err := availabilitysets.ParseAvailabilitySetID(id) return err }), @@ -49,9 +50,9 @@ func resourceAvailabilitySet() *pluginsdk.Resource { ), }, - "resource_group_name": azure.SchemaResourceGroupName(), + "resource_group_name": commonschema.ResourceGroupName(), - "location": azure.SchemaLocation(), + "location": commonschema.Location(), "platform_update_domain_count": { Type: pluginsdk.TypeInt, @@ -88,7 +89,7 @@ func resourceAvailabilitySet() *pluginsdk.Resource { DiffSuppressFunc: suppress.CaseDifference, }, - "tags": tags.Schema(), + "tags": commonschema.Tags(), }, } } @@ -99,58 +100,53 @@ func resourceAvailabilitySetCreateUpdate(d *pluginsdk.ResourceData, meta interfa ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - log.Printf("[INFO] preparing arguments for AzureRM Availability Set creation.") - id := parse.NewAvailabilitySetID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - + id := availabilitysets.NewAvailabilitySetID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, id.ResourceGroup, id.Name) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %s", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_availability_set", id.ID()) } } - location := azure.NormalizeLocation(d.Get("location").(string)) updateDomainCount := d.Get("platform_update_domain_count").(int) faultDomainCount := d.Get("platform_fault_domain_count").(int) managed := d.Get("managed").(bool) t := d.Get("tags").(map[string]interface{}) - availSet := compute.AvailabilitySet{ - Name: &id.Name, - Location: &location, - AvailabilitySetProperties: &compute.AvailabilitySetProperties{ - PlatformFaultDomainCount: utils.Int32(int32(faultDomainCount)), - PlatformUpdateDomainCount: utils.Int32(int32(updateDomainCount)), + payload := availabilitysets.AvailabilitySet{ + Location: location.Normalize(d.Get("location").(string)), + Properties: &availabilitysets.AvailabilitySetProperties{ + PlatformFaultDomainCount: utils.Int64(int64(faultDomainCount)), + PlatformUpdateDomainCount: utils.Int64(int64(updateDomainCount)), }, Tags: tags.Expand(t), } if v, ok := d.GetOk("proximity_placement_group_id"); ok { - availSet.AvailabilitySetProperties.ProximityPlacementGroup = &compute.SubResource{ - ID: utils.String(v.(string)), + payload.Properties.ProximityPlacementGroup = &availabilitysets.SubResource{ + Id: utils.String(v.(string)), } } if managed { n := "Aligned" - availSet.Sku = &compute.Sku{ + payload.Sku = &availabilitysets.Sku{ Name: &n, } } - _, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.Name, availSet) + _, err := client.CreateOrUpdate(ctx, id, payload) if err != nil { - return err + return fmt.Errorf("creating/updating %s: %+v", id, err) } d.SetId(id.ID()) - return resourceAvailabilitySetRead(d, meta) } @@ -159,39 +155,47 @@ func resourceAvailabilitySetRead(d *pluginsdk.ResourceData, meta interface{}) er ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AvailabilitySetID(d.Id()) + id, err := availabilitysets.ParseAvailabilitySetID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { + log.Printf("[DEBUG] %s was not found - removing from state!", *id) d.SetId("") return nil } - return fmt.Errorf("making Read request on Azure Availability Set %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %+v", id, err) } - d.Set("name", resp.Name) - d.Set("resource_group_name", id.ResourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - if resp.Sku != nil && resp.Sku.Name != nil { - d.Set("managed", strings.EqualFold(*resp.Sku.Name, "Aligned")) - } + d.Set("name", id.AvailabilitySetName) + d.Set("resource_group_name", id.ResourceGroupName) + + if model := resp.Model; model != nil { + d.Set("location", location.Normalize(model.Location)) + managed := false + if model.Sku != nil && model.Sku.Name != nil { + managed = strings.EqualFold(*model.Sku.Name, "Aligned") + } + d.Set("managed", managed) - if props := resp.AvailabilitySetProperties; props != nil { - d.Set("platform_update_domain_count", props.PlatformUpdateDomainCount) - d.Set("platform_fault_domain_count", props.PlatformFaultDomainCount) + if props := model.Properties; props != nil { + d.Set("platform_update_domain_count", props.PlatformUpdateDomainCount) + d.Set("platform_fault_domain_count", props.PlatformFaultDomainCount) - if proximityPlacementGroup := props.ProximityPlacementGroup; proximityPlacementGroup != nil { - d.Set("proximity_placement_group_id", proximityPlacementGroup.ID) + if proximityPlacementGroup := props.ProximityPlacementGroup; proximityPlacementGroup != nil { + d.Set("proximity_placement_group_id", proximityPlacementGroup.Id) + } + } + + if err := tags.FlattenAndSet(d, model.Tags); err != nil { + return err } } - return tags.FlattenAndSet(d, resp.Tags) + return nil } func resourceAvailabilitySetDelete(d *pluginsdk.ResourceData, meta interface{}) error { @@ -199,11 +203,14 @@ func resourceAvailabilitySetDelete(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AvailabilitySetID(d.Id()) + id, err := availabilitysets.ParseAvailabilitySetID(d.Id()) if err != nil { return err } - _, err = client.Delete(ctx, id.ResourceGroup, id.Name) - return err + if _, err = client.Delete(ctx, *id); err != nil { + return fmt.Errorf("deleting %s: %+v", *id, err) + } + + return nil } diff --git a/internal/services/compute/availability_set_resource_test.go b/internal/services/compute/availability_set_resource_test.go index 6f7f0ed130dd..097ccbf59910 100644 --- a/internal/services/compute/availability_set_resource_test.go +++ b/internal/services/compute/availability_set_resource_test.go @@ -6,10 +6,10 @@ import ( "testing" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -141,29 +141,29 @@ func TestAccAvailabilitySet_unmanaged(t *testing.T) { } func (AvailabilitySetResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.AvailabilitySetID(state.ID) + id, err := availabilitysets.ParseAvailabilitySetID(state.ID) if err != nil { return nil, err } - resp, err := clients.Compute.AvailabilitySetsClient.Get(ctx, id.ResourceGroup, id.Name) + resp, err := clients.Compute.AvailabilitySetsClient.Get(ctx, *id) if err != nil { - return nil, fmt.Errorf("retrieving Compute Availability Set %q", id.String()) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (AvailabilitySetResource) Destroy(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.AvailabilitySetID(state.ID) + id, err := availabilitysets.ParseAvailabilitySetID(state.ID) if err != nil { return nil, err } - resp, err := client.Compute.AvailabilitySetsClient.Delete(ctx, id.ResourceGroup, id.Name) + resp, err := client.Compute.AvailabilitySetsClient.Delete(ctx, *id) if err != nil { - if !response.WasNotFound(resp.Response) { - return nil, fmt.Errorf("deleting on availSetClient: %+v", err) + if !response.WasNotFound(resp.HttpResponse) { + return nil, fmt.Errorf("deleting %s: %+v", *id, err) } } diff --git a/internal/services/compute/client/client.go b/internal/services/compute/client/client.go index d7deed8d6dfc..ce3fe7323043 100644 --- a/internal/services/compute/client/client.go +++ b/internal/services/compute/client/client.go @@ -3,39 +3,43 @@ package client import ( "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" "github.com/Azure/azure-sdk-for-go/services/marketplaceordering/mgmt/2015-06-01/marketplaceordering" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys" "github.com/hashicorp/terraform-provider-azurerm/internal/common" ) type Client struct { - AvailabilitySetsClient *compute.AvailabilitySetsClient - CapacityReservationsClient *compute.CapacityReservationsClient - CapacityReservationGroupsClient *compute.CapacityReservationGroupsClient - DedicatedHostsClient *compute.DedicatedHostsClient - DedicatedHostGroupsClient *compute.DedicatedHostGroupsClient - DisksClient *compute.DisksClient - DiskAccessClient *compute.DiskAccessesClient - DiskEncryptionSetsClient *compute.DiskEncryptionSetsClient - GalleriesClient *compute.GalleriesClient - GalleryImagesClient *compute.GalleryImagesClient - GalleryImageVersionsClient *compute.GalleryImageVersionsClient - ProximityPlacementGroupsClient *compute.ProximityPlacementGroupsClient - MarketplaceAgreementsClient *marketplaceordering.MarketplaceAgreementsClient - ImagesClient *compute.ImagesClient - SnapshotsClient *compute.SnapshotsClient - UsageClient *compute.UsageClient - VMExtensionImageClient *compute.VirtualMachineExtensionImagesClient - VMExtensionClient *compute.VirtualMachineExtensionsClient - VMScaleSetClient *compute.VirtualMachineScaleSetsClient - VMScaleSetExtensionsClient *compute.VirtualMachineScaleSetExtensionsClient - VMScaleSetRollingUpgradesClient *compute.VirtualMachineScaleSetRollingUpgradesClient - VMScaleSetVMsClient *compute.VirtualMachineScaleSetVMsClient - VMClient *compute.VirtualMachinesClient - VMImageClient *compute.VirtualMachineImagesClient - SSHPublicKeysClient *compute.SSHPublicKeysClient + AvailabilitySetsClient *availabilitysets.AvailabilitySetsClient + CapacityReservationsClient *compute.CapacityReservationsClient + CapacityReservationGroupsClient *compute.CapacityReservationGroupsClient + DedicatedHostsClient *compute.DedicatedHostsClient + DedicatedHostGroupsClient *compute.DedicatedHostGroupsClient + DisksClient *compute.DisksClient + DiskAccessClient *compute.DiskAccessesClient + DiskEncryptionSetsClient *compute.DiskEncryptionSetsClient + GalleriesClient *compute.GalleriesClient + GalleryApplicationsClient *compute.GalleryApplicationsClient + GalleryApplicationVersionsClient *compute.GalleryApplicationVersionsClient + GalleryImagesClient *compute.GalleryImagesClient + GalleryImageVersionsClient *compute.GalleryImageVersionsClient + ImagesClient *compute.ImagesClient + MarketplaceAgreementsClient *marketplaceordering.MarketplaceAgreementsClient + ProximityPlacementGroupsClient *compute.ProximityPlacementGroupsClient + SSHPublicKeysClient *sshpublickeys.SshPublicKeysClient + SnapshotsClient *compute.SnapshotsClient + UsageClient *compute.UsageClient + VMExtensionImageClient *compute.VirtualMachineExtensionImagesClient + VMExtensionClient *compute.VirtualMachineExtensionsClient + VMScaleSetClient *compute.VirtualMachineScaleSetsClient + VMScaleSetExtensionsClient *compute.VirtualMachineScaleSetExtensionsClient + VMScaleSetRollingUpgradesClient *compute.VirtualMachineScaleSetRollingUpgradesClient + VMScaleSetVMsClient *compute.VirtualMachineScaleSetVMsClient + VMClient *compute.VirtualMachinesClient + VMImageClient *compute.VirtualMachineImagesClient } func NewClient(o *common.ClientOptions) *Client { - availabilitySetsClient := compute.NewAvailabilitySetsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + availabilitySetsClient := availabilitysets.NewAvailabilitySetsClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&availabilitySetsClient.Client, o.ResourceManagerAuthorizer) capacityReservationsClient := compute.NewCapacityReservationsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) @@ -62,6 +66,12 @@ func NewClient(o *common.ClientOptions) *Client { galleriesClient := compute.NewGalleriesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&galleriesClient.Client, o.ResourceManagerAuthorizer) + galleryApplicationsClient := compute.NewGalleryApplicationsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&galleryApplicationsClient.Client, o.ResourceManagerAuthorizer) + + galleryApplicationVersionsClient := compute.NewGalleryApplicationVersionsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&galleryApplicationVersionsClient.Client, o.ResourceManagerAuthorizer) + galleryImagesClient := compute.NewGalleryImagesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&galleryImagesClient.Client, o.ResourceManagerAuthorizer) @@ -80,6 +90,9 @@ func NewClient(o *common.ClientOptions) *Client { snapshotsClient := compute.NewSnapshotsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&snapshotsClient.Client, o.ResourceManagerAuthorizer) + sshPublicKeysClient := sshpublickeys.NewSshPublicKeysClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&sshPublicKeysClient.Client, o.ResourceManagerAuthorizer) + usageClient := compute.NewUsageClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&usageClient.Client, o.ResourceManagerAuthorizer) @@ -107,34 +120,33 @@ func NewClient(o *common.ClientOptions) *Client { vmClient := compute.NewVirtualMachinesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&vmClient.Client, o.ResourceManagerAuthorizer) - sshPublicKeysClient := compute.NewSSHPublicKeysClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) - o.ConfigureClient(&sshPublicKeysClient.Client, o.ResourceManagerAuthorizer) - return &Client{ - AvailabilitySetsClient: &availabilitySetsClient, - CapacityReservationsClient: &capacityReservationsClient, - CapacityReservationGroupsClient: &capacityReservationGroupsClient, - DedicatedHostsClient: &dedicatedHostsClient, - DedicatedHostGroupsClient: &dedicatedHostGroupsClient, - DisksClient: &disksClient, - DiskAccessClient: &diskAccessClient, - DiskEncryptionSetsClient: &diskEncryptionSetsClient, - GalleriesClient: &galleriesClient, - GalleryImagesClient: &galleryImagesClient, - GalleryImageVersionsClient: &galleryImageVersionsClient, - ImagesClient: &imagesClient, - MarketplaceAgreementsClient: &marketplaceAgreementsClient, - ProximityPlacementGroupsClient: &proximityPlacementGroupsClient, - SnapshotsClient: &snapshotsClient, - UsageClient: &usageClient, - VMExtensionImageClient: &vmExtensionImageClient, - VMExtensionClient: &vmExtensionClient, - VMScaleSetClient: &vmScaleSetClient, - VMScaleSetExtensionsClient: &vmScaleSetExtensionsClient, - VMScaleSetRollingUpgradesClient: &vmScaleSetRollingUpgradesClient, - VMScaleSetVMsClient: &vmScaleSetVMsClient, - VMClient: &vmClient, - VMImageClient: &vmImageClient, - SSHPublicKeysClient: &sshPublicKeysClient, + AvailabilitySetsClient: &availabilitySetsClient, + CapacityReservationsClient: &capacityReservationsClient, + CapacityReservationGroupsClient: &capacityReservationGroupsClient, + DedicatedHostsClient: &dedicatedHostsClient, + DedicatedHostGroupsClient: &dedicatedHostGroupsClient, + DisksClient: &disksClient, + DiskAccessClient: &diskAccessClient, + DiskEncryptionSetsClient: &diskEncryptionSetsClient, + GalleriesClient: &galleriesClient, + GalleryApplicationsClient: &galleryApplicationsClient, + GalleryApplicationVersionsClient: &galleryApplicationVersionsClient, + GalleryImagesClient: &galleryImagesClient, + GalleryImageVersionsClient: &galleryImageVersionsClient, + ImagesClient: &imagesClient, + MarketplaceAgreementsClient: &marketplaceAgreementsClient, + ProximityPlacementGroupsClient: &proximityPlacementGroupsClient, + SSHPublicKeysClient: &sshPublicKeysClient, + SnapshotsClient: &snapshotsClient, + UsageClient: &usageClient, + VMExtensionImageClient: &vmExtensionImageClient, + VMExtensionClient: &vmExtensionClient, + VMScaleSetClient: &vmScaleSetClient, + VMScaleSetExtensionsClient: &vmScaleSetExtensionsClient, + VMScaleSetRollingUpgradesClient: &vmScaleSetRollingUpgradesClient, + VMScaleSetVMsClient: &vmScaleSetVMsClient, + VMClient: &vmClient, + VMImageClient: &vmImageClient, } } diff --git a/internal/services/compute/gallery_application_resource.go b/internal/services/compute/gallery_application_resource.go new file mode 100644 index 000000000000..57b336896d8f --- /dev/null +++ b/internal/services/compute/gallery_application_resource.go @@ -0,0 +1,362 @@ +package compute + +import ( + "context" + "fmt" + "time" + + "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" + "github.com/Azure/go-autorest/autorest/date" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/validate" + "github.com/hashicorp/terraform-provider-azurerm/internal/tags" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type GalleryApplicationResource struct{} + +var ( + _ sdk.ResourceWithUpdate = GalleryApplicationResource{} + _ sdk.ResourceWithCustomizeDiff = GalleryApplicationResource{} +) + +type GalleryApplicationModel struct { + Name string `tfschema:"name"` + GalleryId string `tfschema:"gallery_id"` + Location string `tfschema:"location"` + SupportedOSType string `tfschema:"supported_os_type"` + Description string `tfschema:"description"` + EndOfLifeDate string `tfschema:"end_of_life_date"` + Eula string `tfschema:"eula"` + PrivacyStatementURI string `tfschema:"privacy_statement_uri"` + ReleaseNoteURI string `tfschema:"release_note_uri"` + Tags map[string]string `tfschema:"tags"` +} + +func (r GalleryApplicationResource) Arguments() map[string]*pluginsdk.Schema { + return map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.GalleryApplicationName, + }, + + "gallery_id": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.SharedImageGalleryID, + }, + + "location": commonschema.Location(), + + "supported_os_type": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + string(compute.OperatingSystemTypesWindows), + string(compute.OperatingSystemTypesLinux), + }, false), + }, + + "description": { + Type: pluginsdk.TypeString, + Optional: true, + }, + + "end_of_life_date": { + Type: pluginsdk.TypeString, + Optional: true, + DiffSuppressFunc: suppress.RFC3339Time, + ValidateFunc: validation.IsRFC3339Time, + }, + + "eula": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "privacy_statement_uri": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "release_note_uri": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "tags": tags.Schema(), + } +} + +func (r GalleryApplicationResource) Attributes() map[string]*pluginsdk.Schema { + return map[string]*pluginsdk.Schema{} +} + +func (r GalleryApplicationResource) ResourceType() string { + return "azurerm_gallery_application" +} + +func (r GalleryApplicationResource) ModelObject() interface{} { + return &GalleryApplicationModel{} +} + +func (r GalleryApplicationResource) IDValidationFunc() pluginsdk.SchemaValidateFunc { + return validate.GalleryApplicationID +} + +func (r GalleryApplicationResource) Create() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + var state GalleryApplicationModel + if err := metadata.Decode(&state); err != nil { + return err + } + + client := metadata.Client.Compute.GalleryApplicationsClient + subscriptionId := metadata.Client.Account.SubscriptionId + + galleryId, err := parse.SharedImageGalleryID(state.GalleryId) + if err != nil { + return err + } + + id := parse.NewGalleryApplicationID(subscriptionId, galleryId.ResourceGroup, galleryId.GalleryName, state.Name) + + existing, err := client.Get(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName) + if err != nil && !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("checking for the presence of existing %q: %+v", id, err) + } + if !utils.ResponseWasNotFound(existing.Response) { + return metadata.ResourceRequiresImport(r.ResourceType(), id) + } + + input := compute.GalleryApplication{ + Location: utils.String(location.Normalize(state.Location)), + GalleryApplicationProperties: &compute.GalleryApplicationProperties{ + SupportedOSType: compute.OperatingSystemTypes(state.SupportedOSType), + }, + Tags: tags.FromTypedObject(state.Tags), + } + + if state.Description != "" { + input.GalleryApplicationProperties.Description = utils.String(state.Description) + } + + if state.EndOfLifeDate != "" { + endOfLifeDate, _ := time.Parse(time.RFC3339, state.EndOfLifeDate) + input.GalleryApplicationProperties.EndOfLifeDate = &date.Time{ + Time: endOfLifeDate, + } + } + + if state.Eula != "" { + input.GalleryApplicationProperties.Eula = utils.String(state.Eula) + } + + if state.PrivacyStatementURI != "" { + input.GalleryApplicationProperties.PrivacyStatementURI = utils.String(state.PrivacyStatementURI) + } + + if state.ReleaseNoteURI != "" { + input.GalleryApplicationProperties.ReleaseNoteURI = utils.String(state.ReleaseNoteURI) + } + + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, input) + if err != nil { + return fmt.Errorf("creating %s: %+v", id, err) + } + + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for creation of %s: %+v", id, err) + } + + metadata.SetID(id) + return nil + }, + Timeout: 30 * time.Minute, + } +} + +func (r GalleryApplicationResource) Read() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + client := metadata.Client.Compute.GalleryApplicationsClient + id, err := parse.GalleryApplicationID(metadata.ResourceData.Id()) + if err != nil { + return err + } + + resp, err := client.Get(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + metadata.Logger.Infof("%q was not found - removing from state!", *id) + return metadata.MarkAsGone(id) + } + + return fmt.Errorf("retrieving %s: %+v", *id, err) + } + + galleryId := parse.NewSharedImageGalleryID(id.SubscriptionId, id.ResourceGroup, id.GalleryName) + + state := &GalleryApplicationModel{ + Name: id.ApplicationName, + GalleryId: galleryId.ID(), + Location: location.NormalizeNilable(resp.Location), + Tags: tags.ToTypedObject(resp.Tags), + } + + if props := resp.GalleryApplicationProperties; props != nil { + if v := props.Description; v != nil { + state.Description = *props.Description + } + + if v := props.EndOfLifeDate; v != nil { + state.EndOfLifeDate = props.EndOfLifeDate.Format(time.RFC3339) + } + + if v := props.Eula; v != nil { + state.Eula = *props.Eula + } + + if v := props.PrivacyStatementURI; v != nil { + state.PrivacyStatementURI = *props.PrivacyStatementURI + } + + if v := props.ReleaseNoteURI; v != nil { + state.ReleaseNoteURI = *props.ReleaseNoteURI + } + + state.SupportedOSType = string(props.SupportedOSType) + } + + return metadata.Encode(state) + }, + Timeout: 5 * time.Minute, + } +} + +func (r GalleryApplicationResource) Update() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + id, err := parse.GalleryApplicationID(metadata.ResourceData.Id()) + if err != nil { + return err + } + + var state GalleryApplicationModel + if err := metadata.Decode(&state); err != nil { + return err + } + + client := metadata.Client.Compute.GalleryApplicationsClient + existing, err := client.Get(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName) + if err != nil { + return fmt.Errorf("retrieving %s: %+v", *id, err) + } + + if metadata.ResourceData.HasChange("description") { + existing.GalleryApplicationProperties.Description = utils.String(state.Description) + } + + if metadata.ResourceData.HasChange("end_of_life_date") { + endOfLifeDate, _ := time.Parse(time.RFC3339, state.EndOfLifeDate) + existing.GalleryApplicationProperties.EndOfLifeDate = &date.Time{ + Time: endOfLifeDate, + } + } + + if metadata.ResourceData.HasChange("eula") { + existing.GalleryApplicationProperties.Eula = utils.String(state.Eula) + } + + if metadata.ResourceData.HasChange("privacy_statement_uri") { + existing.GalleryApplicationProperties.PrivacyStatementURI = utils.String(state.PrivacyStatementURI) + } + + if metadata.ResourceData.HasChange("release_note_uri") { + existing.GalleryApplicationProperties.ReleaseNoteURI = utils.String(state.ReleaseNoteURI) + } + + if metadata.ResourceData.HasChange("tags") { + existing.Tags = tags.FromTypedObject(state.Tags) + } + + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, existing) + if err != nil { + return fmt.Errorf("updating %s: %+v", id, err) + } + + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for update of %s: %+v", id, err) + } + + return nil + }, + Timeout: 30 * time.Minute, + } +} + +func (r GalleryApplicationResource) Delete() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + client := metadata.Client.Compute.GalleryApplicationsClient + id, err := parse.GalleryApplicationID(metadata.ResourceData.Id()) + if err != nil { + return err + } + + future, err := client.Delete(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName) + if err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) + } + + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for deletion of %s: %+v", id, err) + } + return nil + }, + Timeout: 30 * time.Minute, + } +} + +func (r GalleryApplicationResource) CustomizeDiff() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 5 * time.Minute, + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + rd := metadata.ResourceDiff + + if oldVal, newVal := rd.GetChange("end_of_life_date"); oldVal.(string) != "" && newVal.(string) == "" { + if err := rd.ForceNew("end_of_life_date"); err != nil { + return err + } + } + + if oldVal, newVal := rd.GetChange("privacy_statement_uri"); oldVal.(string) != "" && newVal.(string) == "" { + if err := rd.ForceNew("privacy_statement_uri"); err != nil { + return err + } + } + + if oldVal, newVal := rd.GetChange("release_note_uri"); oldVal.(string) != "" && newVal.(string) == "" { + if err := rd.ForceNew("release_note_uri"); err != nil { + return err + } + } + + return nil + }, + } +} diff --git a/internal/services/compute/gallery_application_resource_test.go b/internal/services/compute/gallery_application_resource_test.go new file mode 100644 index 000000000000..9e5e2abed532 --- /dev/null +++ b/internal/services/compute/gallery_application_resource_test.go @@ -0,0 +1,519 @@ +package compute_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type GalleryApplicationResource struct{} + +func TestAccGalleryApplication_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplication_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.RequiresImportErrorStep(r.requiresImport), + }) +} + +func TestAccGalleryApplication_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.complete(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplication_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.complete(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplication_description(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.description(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.descriptionUpdated(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.description(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplication_endOfLifeDate(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + + endOfLifeDate := time.Now().Add(time.Hour * 10).Format(time.RFC3339) + endOfLifeDateUpdated := time.Now().Add(time.Hour * 20).Format(time.RFC3339) + + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.endOfLifeDate(data, endOfLifeDate), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.endOfLifeDate(data, endOfLifeDateUpdated), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplication_eula(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.eula(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.eulaUpdated(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.eula(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplication_privacyStatementURI(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.privacyStatementURI(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.privacyStatementURIUpdated(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplication_releaseNoteURI(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.releaseNoteURI(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.releaseNoteURIUpdated(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplication_tags(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application", "test") + r := GalleryApplicationResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.tags(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.tagsUpdated(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.tags(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func (r GalleryApplicationResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { + id, err := parse.GalleryApplicationID(state.ID) + if err != nil { + return nil, err + } + resp, err := client.Compute.GalleryApplicationsClient.Get(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return utils.Bool(false), nil + } + return nil, fmt.Errorf("retrieving %s: %+v", id, err) + } + return utils.Bool(resp.ID != nil), nil +} + +func (r GalleryApplicationResource) template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctest-compute-%[2]d" + location = "%[1]s" +} + +resource "azurerm_shared_image_gallery" "test" { + name = "acctestsig%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} +`, data.Locations.Primary, data.RandomInteger) +} + +func (r GalleryApplicationResource) basic(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) requiresImport(data acceptance.TestData) string { + config := r.basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "import" { + name = azurerm_gallery_application.test.name + gallery_id = azurerm_gallery_application.test.gallery_id + location = azurerm_gallery_application.test.location + supported_os_type = azurerm_gallery_application.test.supported_os_type +} +`, config) +} + +func (r GalleryApplicationResource) complete(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + description = "This is the gallery application description." + end_of_life_date = "%s" + eula = "https://eula.net" + privacy_statement_uri = "https://privacy.statement.net" + release_note_uri = "https://release.note.net" + + tags = { + ENV = "Test" + } +} +`, template, data.RandomInteger, time.Now().Add(time.Hour*10).Format(time.RFC3339)) +} + +func (r GalleryApplicationResource) description(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + description = "This is the gallery application description." +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) descriptionUpdated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + description = "This is the gallery application description updated." +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) endOfLifeDate(data acceptance.TestData, endOfLifeDate string) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + end_of_life_date = "%s" +} +`, template, data.RandomInteger, endOfLifeDate) +} + +func (r GalleryApplicationResource) eula(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + eula = "https://eula.net" +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) eulaUpdated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + eula = "https://eula2.net" +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) privacyStatementURI(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + privacy_statement_uri = "https://privacy.statement.net" +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) privacyStatementURIUpdated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + privacy_statement_uri = "https://privacy.statement2.net" +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) releaseNoteURI(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + release_note_uri = "https://release.note2.net" +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) releaseNoteURIUpdated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + release_note_uri = "https://release.note.net" +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) tags(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + tags = { + ENV = "Test" + } +} +`, template, data.RandomInteger) +} + +func (r GalleryApplicationResource) tagsUpdated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" + + tags = { + ENV = "Test2" + } +} +`, template, data.RandomInteger) +} diff --git a/internal/services/compute/gallery_application_version_resource.go b/internal/services/compute/gallery_application_version_resource.go new file mode 100644 index 000000000000..da570e50b71d --- /dev/null +++ b/internal/services/compute/gallery_application_version_resource.go @@ -0,0 +1,568 @@ +package compute + +import ( + "context" + "fmt" + "time" + + "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" + "github.com/Azure/go-autorest/autorest/date" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/validate" + "github.com/hashicorp/terraform-provider-azurerm/internal/tags" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type GalleryApplicationVersionResource struct{} + +var ( + _ sdk.ResourceWithUpdate = GalleryApplicationVersionResource{} + _ sdk.ResourceWithCustomizeDiff = GalleryApplicationVersionResource{} +) + +type GalleryApplicationVersionModel struct { + Name string `tfschema:"name"` + GalleryApplicationId string `tfschema:"gallery_application_id"` + Location string `tfschema:"location"` + EnableHealthCheck bool `tfschema:"enable_health_check"` + EndOfLifeDate string `tfschema:"end_of_life_date"` + ExcludeFromLatest bool `tfschema:"exclude_from_latest"` + ManageAction []ManageAction `tfschema:"manage_action"` + Source []Source `tfschema:"source"` + TargetRegion []TargetRegion `tfschema:"target_region"` + Tags map[string]string `tfschema:"tags"` +} + +type Source struct { + MediaLink string `tfschema:"media_link"` + DefaultConfigurationLink string `tfschema:"default_configuration_link"` +} + +type ManageAction struct { + Install string `tfschema:"install"` + Remove string `tfschema:"remove"` + Update string `tfschema:"update"` +} + +type TargetRegion struct { + Name string `tfschema:"name"` + RegionalReplicaCount int `tfschema:"regional_replica_count"` + StorageAccountType string `tfschema:"storage_account_type"` +} + +func (r GalleryApplicationVersionResource) Arguments() map[string]*pluginsdk.Schema { + return map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.GalleryApplicationVersionName, + }, + + "gallery_application_id": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.GalleryApplicationID, + }, + + "location": commonschema.Location(), + + "enable_health_check": { + Type: pluginsdk.TypeBool, + Optional: true, + Default: false, + }, + + "end_of_life_date": { + Type: pluginsdk.TypeString, + Optional: true, + DiffSuppressFunc: suppress.RFC3339Time, + ValidateFunc: validation.IsRFC3339Time, + }, + + "exclude_from_latest": { + Type: pluginsdk.TypeBool, + Optional: true, + Default: false, + }, + + "manage_action": { + Type: pluginsdk.TypeList, + Required: true, + MaxItems: 1, + Elem: &pluginsdk.Resource{ + Schema: map[string]*pluginsdk.Schema{ + "install": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 4096), + }, + + "remove": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 4096), + }, + + "update": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 4096), + }, + }, + }, + }, + + "source": { + Type: pluginsdk.TypeList, + Required: true, + MaxItems: 1, + Elem: &pluginsdk.Resource{ + Schema: map[string]*pluginsdk.Schema{ + "media_link": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.IsURLWithScheme([]string{"http", "https"}), + }, + + "default_configuration_link": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.IsURLWithScheme([]string{"http", "https"}), + }, + }, + }, + }, + + "target_region": { + // This needs to be a `TypeList` due to the `StateFunc` on the nested property `name` + // See: https://github.com/hashicorp/terraform-plugin-sdk/issues/160 + Type: pluginsdk.TypeList, + Required: true, + Elem: &pluginsdk.Resource{ + Schema: map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + StateFunc: location.StateFunc, + DiffSuppressFunc: location.DiffSuppressFunc, + }, + + "regional_replica_count": { + Type: pluginsdk.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 10), + }, + + "storage_account_type": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(compute.StorageAccountTypePremiumLRS), + string(compute.StorageAccountTypeStandardLRS), + string(compute.StorageAccountTypeStandardZRS), + }, false), + Default: string(compute.StorageAccountTypeStandardLRS), + }, + }, + }, + }, + + "tags": tags.Schema(), + } +} + +func (r GalleryApplicationVersionResource) Attributes() map[string]*pluginsdk.Schema { + return map[string]*pluginsdk.Schema{} +} + +func (r GalleryApplicationVersionResource) ResourceType() string { + return "azurerm_gallery_application_version" +} + +func (r GalleryApplicationVersionResource) ModelObject() interface{} { + return &GalleryApplicationVersionModel{} +} + +func (r GalleryApplicationVersionResource) IDValidationFunc() pluginsdk.SchemaValidateFunc { + return validate.GalleryApplicationVersionID +} + +func (r GalleryApplicationVersionResource) Create() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + var state GalleryApplicationVersionModel + if err := metadata.Decode(&state); err != nil { + return err + } + + client := metadata.Client.Compute.GalleryApplicationVersionsClient + subscriptionId := metadata.Client.Account.SubscriptionId + + galleryApplicationId, err := parse.GalleryApplicationID(state.GalleryApplicationId) + if err != nil { + return err + } + + id := parse.NewGalleryApplicationVersionID(subscriptionId, galleryApplicationId.ResourceGroup, galleryApplicationId.GalleryName, galleryApplicationId.ApplicationName, state.Name) + existing, err := client.Get(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, id.VersionName, "") + if err != nil && !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("checking for the presence of existing %q: %+v", id, err) + } + if !utils.ResponseWasNotFound(existing.Response) { + return metadata.ResourceRequiresImport(r.ResourceType(), id) + } + + input := compute.GalleryApplicationVersion{ + Location: utils.String(location.Normalize(state.Location)), + GalleryApplicationVersionProperties: &compute.GalleryApplicationVersionProperties{ + PublishingProfile: &compute.GalleryApplicationVersionPublishingProfile{ + EnableHealthCheck: utils.Bool(state.EnableHealthCheck), + ExcludeFromLatest: utils.Bool(state.ExcludeFromLatest), + ManageActions: expandGalleryApplicationVersionManageAction(state.ManageAction), + Source: expandGalleryApplicationVersionSource(state.Source), + TargetRegions: expandGalleryApplicationVersionTargetRegion(state.TargetRegion), + }, + }, + Tags: tags.FromTypedObject(state.Tags), + } + + if state.EndOfLifeDate != "" { + endOfLifeDate, _ := time.Parse(time.RFC3339, state.EndOfLifeDate) + input.GalleryApplicationVersionProperties.PublishingProfile.EndOfLifeDate = &date.Time{ + Time: endOfLifeDate, + } + } + + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, id.VersionName, input) + if err != nil { + return fmt.Errorf("creating %s: %+v", id, err) + } + + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for creation of %s: %+v", id, err) + } + + metadata.SetID(id) + return nil + }, + Timeout: 30 * time.Minute, + } +} + +func (r GalleryApplicationVersionResource) Read() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + client := metadata.Client.Compute.GalleryApplicationVersionsClient + id, err := parse.GalleryApplicationVersionID(metadata.ResourceData.Id()) + if err != nil { + return err + } + + resp, err := client.Get(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, id.VersionName, "") + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + metadata.Logger.Infof("%q was not found - removing from state!", *id) + return metadata.MarkAsGone(id) + } + + return fmt.Errorf("retrieving %s: %+v", *id, err) + } + + galleryApplicationId := parse.NewGalleryApplicationID(id.SubscriptionId, id.ResourceGroup, id.GalleryName, id.ApplicationName) + + state := &GalleryApplicationVersionModel{ + Name: id.VersionName, + GalleryApplicationId: galleryApplicationId.ID(), + Location: location.NormalizeNilable(resp.Location), + Tags: tags.ToTypedObject(resp.Tags), + } + + if props := resp.GalleryApplicationVersionProperties; props != nil { + if publishingProfile := props.PublishingProfile; publishingProfile != nil { + if publishingProfile.EnableHealthCheck != nil { + state.EnableHealthCheck = *publishingProfile.EnableHealthCheck + } + + if publishingProfile.EndOfLifeDate != nil { + state.EndOfLifeDate = publishingProfile.EndOfLifeDate.Format(time.RFC3339) + } + + if publishingProfile.ExcludeFromLatest != nil { + state.ExcludeFromLatest = *publishingProfile.ExcludeFromLatest + } + + if publishingProfile.ManageActions != nil { + state.ManageAction = flattenGalleryApplicationVersionManageAction(publishingProfile.ManageActions) + } + + if publishingProfile.Source != nil { + state.Source = flattenGalleryApplicationVersionSource(publishingProfile.Source) + } + + if publishingProfile.TargetRegions != nil { + state.TargetRegion = flattenGalleryApplicationVersionTargetRegion(publishingProfile.TargetRegions) + } + } + } + + return metadata.Encode(state) + }, + Timeout: 5 * time.Minute, + } +} + +func (r GalleryApplicationVersionResource) Update() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + id, err := parse.GalleryApplicationVersionID(metadata.ResourceData.Id()) + if err != nil { + return err + } + + var state GalleryApplicationVersionModel + if err := metadata.Decode(&state); err != nil { + return err + } + + client := metadata.Client.Compute.GalleryApplicationVersionsClient + existing, err := client.Get(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, id.VersionName, "") + if err != nil { + return fmt.Errorf("retrieving %s: %+v", *id, err) + } + + if existing.PublishingProfile == nil { + existing.PublishingProfile = &compute.GalleryApplicationVersionPublishingProfile{} + } + + if metadata.ResourceData.HasChange("enable_health_check") { + existing.PublishingProfile.EnableHealthCheck = utils.Bool(state.EnableHealthCheck) + } + + if metadata.ResourceData.HasChange("end_of_life_date") { + endOfLifeDate, _ := time.Parse(time.RFC3339, state.EndOfLifeDate) + existing.GalleryApplicationVersionProperties.PublishingProfile.EndOfLifeDate = &date.Time{ + Time: endOfLifeDate, + } + } + + if metadata.ResourceData.HasChange("exclude_from_latest") { + existing.PublishingProfile.ExcludeFromLatest = utils.Bool(state.ExcludeFromLatest) + } + + if metadata.ResourceData.HasChange("manage_actions") { + existing.GalleryApplicationVersionProperties.PublishingProfile.ManageActions = expandGalleryApplicationVersionManageAction(state.ManageAction) + } + if metadata.ResourceData.HasChange("source") { + existing.GalleryApplicationVersionProperties.PublishingProfile.Source = expandGalleryApplicationVersionSource(state.Source) + } + + if metadata.ResourceData.HasChange("target_region") { + existing.GalleryApplicationVersionProperties.PublishingProfile.TargetRegions = expandGalleryApplicationVersionTargetRegion(state.TargetRegion) + } + + if metadata.ResourceData.HasChange("tags") { + existing.Tags = tags.FromTypedObject(state.Tags) + } + + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, id.VersionName, existing) + if err != nil { + return fmt.Errorf("updating %s: %+v", id, err) + } + + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for update of %s: %+v", id, err) + } + + return nil + }, + Timeout: 30 * time.Minute, + } +} + +func (r GalleryApplicationVersionResource) Delete() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + client := metadata.Client.Compute.GalleryApplicationVersionsClient + id, err := parse.GalleryApplicationVersionID(metadata.ResourceData.Id()) + if err != nil { + return err + } + + future, err := client.Delete(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, id.VersionName) + if err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) + } + + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for deletion of %s: %+v", id, err) + } + + metadata.Logger.Infof("Waiting for %s to be eventually deleted", *id) + timeout, _ := ctx.Deadline() + stateConf := &pluginsdk.StateChangeConf{ + Pending: []string{"Exists"}, + Target: []string{"NotFound"}, + Refresh: galleryApplicationVersionDeleteStateRefreshFunc(ctx, client, *id), + MinTimeout: 10 * time.Second, + ContinuousTargetOccurence: 10, + Timeout: time.Until(timeout), + } + + if _, err := stateConf.WaitForStateContext(ctx); err != nil { + return fmt.Errorf("waiting for %s to be deleted: %+v", *id, err) + } + + return nil + }, + Timeout: 30 * time.Minute, + } +} + +func (r GalleryApplicationVersionResource) CustomizeDiff() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 5 * time.Minute, + Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { + rd := metadata.ResourceDiff + + if oldVal, newVal := rd.GetChange("end_of_life_date"); oldVal.(string) != "" && newVal.(string) == "" { + if err := rd.ForceNew("end_of_life_date"); err != nil { + return err + } + } + + return nil + }, + } +} + +func expandGalleryApplicationVersionManageAction(input []ManageAction) *compute.UserArtifactManage { + if len(input) == 0 { + return &compute.UserArtifactManage{} + } + v := input[0] + return &compute.UserArtifactManage{ + Install: utils.String(v.Install), + Remove: utils.String(v.Remove), + Update: utils.String(v.Update), + } +} + +func flattenGalleryApplicationVersionManageAction(input *compute.UserArtifactManage) []ManageAction { + if input == nil { + return nil + } + + obj := ManageAction{} + + if input.Install != nil { + obj.Install = *input.Install + } + + if input.Remove != nil { + obj.Remove = *input.Remove + } + + if input.Update != nil { + obj.Update = *input.Update + } + + return []ManageAction{obj} +} + +func expandGalleryApplicationVersionSource(input []Source) *compute.UserArtifactSource { + if len(input) == 0 { + return &compute.UserArtifactSource{} + } + v := input[0] + return &compute.UserArtifactSource{ + MediaLink: utils.String(v.MediaLink), + DefaultConfigurationLink: utils.String(v.DefaultConfigurationLink), + } +} + +func flattenGalleryApplicationVersionSource(input *compute.UserArtifactSource) []Source { + if input == nil { + return nil + } + + obj := Source{} + + if input.MediaLink != nil { + obj.MediaLink = *input.MediaLink + } + + if input.DefaultConfigurationLink != nil { + obj.DefaultConfigurationLink = *input.DefaultConfigurationLink + } + + return []Source{obj} +} + +func expandGalleryApplicationVersionTargetRegion(input []TargetRegion) *[]compute.TargetRegion { + results := make([]compute.TargetRegion, 0) + for _, item := range input { + results = append(results, compute.TargetRegion{ + Name: utils.String(location.Normalize(item.Name)), + RegionalReplicaCount: utils.Int32(int32(item.RegionalReplicaCount)), + StorageAccountType: compute.StorageAccountType(item.StorageAccountType), + }) + } + return &results +} + +func flattenGalleryApplicationVersionTargetRegion(input *[]compute.TargetRegion) []TargetRegion { + if input == nil { + return nil + } + + results := make([]TargetRegion, 0) + + for _, item := range *input { + obj := TargetRegion{} + + if item.Name != nil { + obj.Name = location.Normalize(*item.Name) + } + + if item.RegionalReplicaCount != nil { + obj.RegionalReplicaCount = int(*item.RegionalReplicaCount) + } + + if item.StorageAccountType != "" { + obj.StorageAccountType = string(item.StorageAccountType) + } + results = append(results, obj) + } + return results +} + +func galleryApplicationVersionDeleteStateRefreshFunc(ctx context.Context, client *compute.GalleryApplicationVersionsClient, id parse.GalleryApplicationVersionId) pluginsdk.StateRefreshFunc { + // Whilst the Gallery Application Version is deleted quickly, it appears it's not actually finished replicating at this time + // so the deletion of the parent Gallery Application fails with "can not delete until nested resources are deleted" + // ergo we need to poll on this for a bit, see https://github.com/Azure/azure-rest-api-specs/issues/19686 + return func() (interface{}, string, error) { + res, err := client.Get(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, id.VersionName, "") + if err != nil { + if utils.ResponseWasNotFound(res.Response) { + return "NotFound", "NotFound", nil + } + + return nil, "", fmt.Errorf("failed to poll to check if the Gallery Application Version has been deleted: %+v", err) + } + + return res, "Exists", nil + } +} diff --git a/internal/services/compute/gallery_application_version_resource_test.go b/internal/services/compute/gallery_application_version_resource_test.go new file mode 100644 index 000000000000..9179a87a027b --- /dev/null +++ b/internal/services/compute/gallery_application_version_resource_test.go @@ -0,0 +1,678 @@ +package compute_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type GalleryApplicationVersionResource struct{} + +func TestAccGalleryApplicationVersion_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application_version", "test") + r := GalleryApplicationVersionResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + check.That(data.ResourceName).Key("enable_health_check").HasValue("false"), + check.That(data.ResourceName).Key("exclude_from_latest").HasValue("false"), + check.That(data.ResourceName).Key("target_region.0.storage_account_type").HasValue("Standard_LRS"), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplicationVersion_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application_version", "test") + r := GalleryApplicationVersionResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.RequiresImportErrorStep(r.requiresImport), + }) +} + +func TestAccGalleryApplicationVersion_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application_version", "test") + r := GalleryApplicationVersionResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.complete(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplicationVersion_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application_version", "test") + r := GalleryApplicationVersionResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.complete(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplicationVersion_enableHealthCheck(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application_version", "test") + r := GalleryApplicationVersionResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.enableHealthCheck(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.enableHealthCheckUpdated(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.enableHealthCheck(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplicationVersion_endOfLifeDate(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application_version", "test") + r := GalleryApplicationVersionResource{} + + endOfLifeDate := time.Now().Add(time.Hour * 10).Format(time.RFC3339) + endOfLifeDateUpdated := time.Now().Add(time.Hour * 20).Format(time.RFC3339) + + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.endOfLifeDate(data, endOfLifeDate), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.endOfLifeDate(data, endOfLifeDateUpdated), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplicationVersion_excludeFromLatest(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application_version", "test") + r := GalleryApplicationVersionResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.excludeFromLatest(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.excludeFromLatestUpdated(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.excludeFromLatest(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplicationVersion_targetRegion(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application_version", "test") + r := GalleryApplicationVersionResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.targetRegion(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.targetRegionUpdated(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.targetRegion(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccGalleryApplicationVersion_tags(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_gallery_application_version", "test") + r := GalleryApplicationVersionResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.tags(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.tagsUpdated(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.tags(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func (r GalleryApplicationVersionResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { + id, err := parse.GalleryApplicationVersionID(state.ID) + if err != nil { + return nil, err + } + resp, err := client.Compute.GalleryApplicationVersionsClient.Get(ctx, id.ResourceGroup, id.GalleryName, id.ApplicationName, id.VersionName, "") + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return utils.Bool(false), nil + } + return nil, fmt.Errorf("retrieving %s: %+v", id, err) + } + return utils.Bool(resp.ID != nil), nil +} + +func (r GalleryApplicationVersionResource) template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctest-compute-%[2]d" + location = "%[1]s" +} + +resource "azurerm_shared_image_gallery" "test" { + name = "acctestsig%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_gallery_application" "test" { + name = "acctest-app-%[2]d" + gallery_id = azurerm_shared_image_gallery.test.id + location = azurerm_resource_group.test.location + supported_os_type = "Linux" +} + +resource "azurerm_storage_account" "test" { + name = "acctestacc%[3]s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_storage_container" "test" { + name = "acctestsc%[3]s" + storage_account_name = azurerm_storage_account.test.name + container_access_type = "blob" +} + +resource "azurerm_storage_blob" "test" { + name = "scripts" + storage_account_name = azurerm_storage_account.test.name + storage_container_name = azurerm_storage_container.test.name + type = "Block" + source_content = "[scripts file content]" +} + +`, data.Locations.Primary, data.RandomInteger, data.RandomString) +} + +func (r GalleryApplicationVersionResource) basic(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } +} +`, template) +} + +func (r GalleryApplicationVersionResource) requiresImport(data acceptance.TestData) string { + config := r.basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "import" { + name = azurerm_gallery_application_version.test.name + gallery_application_id = azurerm_gallery_application_version.test.gallery_application_id + location = azurerm_gallery_application_version.test.location + + manage_action { + install = azurerm_gallery_application_version.test.manage_action.0.install + remove = azurerm_gallery_application_version.test.manage_action.0.remove + } + + source { + media_link = azurerm_gallery_application_version.test.source.0.media_link + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } +} +`, config) +} + +func (r GalleryApplicationVersionResource) complete(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + enable_health_check = true + end_of_life_date = "%s" + exclude_from_latest = true + + manage_action { + install = "[install command]" + remove = "[remove command]" + update = "[update command]" + } + + source { + media_link = azurerm_storage_blob.test.id + default_configuration_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + storage_account_type = "Premium_LRS" + } + + tags = { + ENV = "Test" + } +} +`, template, time.Now().Add(time.Hour*10).Format(time.RFC3339)) +} + +func (r GalleryApplicationVersionResource) enableHealthCheck(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + enable_health_check = true + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } +} +`, template) +} + +func (r GalleryApplicationVersionResource) enableHealthCheckUpdated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + enable_health_check = false + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } +} +`, template) +} + +func (r GalleryApplicationVersionResource) endOfLifeDate(data acceptance.TestData, endOfLifeDate string) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + end_of_life_date = "%s" + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } +} +`, template, endOfLifeDate) +} + +func (r GalleryApplicationVersionResource) excludeFromLatest(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + exclude_from_latest = true + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } +} +`, template) +} + +func (r GalleryApplicationVersionResource) excludeFromLatestUpdated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + exclude_from_latest = false + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } +} +`, template) +} + +func (r GalleryApplicationVersionResource) targetRegion(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } + + target_region { + name = "%s" + regional_replica_count = 2 + storage_account_type = "Premium_LRS" + } +} +`, template, data.Locations.Secondary) +} + +func (r GalleryApplicationVersionResource) targetRegionUpdated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } + + target_region { + name = "%s" + regional_replica_count = 3 + storage_account_type = "Premium_LRS" + } +} +`, template, data.Locations.Secondary) +} + +func (r GalleryApplicationVersionResource) tags(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } + + tags = { + ENV = "Test" + } +} +`, template) +} + +func (r GalleryApplicationVersionResource) tagsUpdated(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_gallery_application_version" "test" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.test.id + location = azurerm_gallery_application.test.location + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.test.id + } + + target_region { + name = azurerm_gallery_application.test.location + regional_replica_count = 1 + } + + tags = { + ENV = "Test2" + } +} +`, template) +} diff --git a/internal/services/compute/linux_virtual_machine_resource.go b/internal/services/compute/linux_virtual_machine_resource.go index 745f801ddbd7..6a48829f4380 100644 --- a/internal/services/compute/linux_virtual_machine_resource.go +++ b/internal/services/compute/linux_virtual_machine_resource.go @@ -7,11 +7,11 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" azValidate "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" @@ -108,11 +108,12 @@ func resourceLinuxVirtualMachine() *pluginsdk.Resource { Type: pluginsdk.TypeString, Optional: true, ForceNew: true, - ValidateFunc: computeValidate.AvailabilitySetID, + ValidateFunc: availabilitysets.ValidateAvailabilitySetID, // the Compute/VM API is broken and returns the Availability Set name in UPPERCASE :shrug: // tracked by https://github.com/Azure/azure-rest-api-specs/issues/19424 DiffSuppressFunc: suppress.CaseDifference, ConflictsWith: []string{ + "capacity_reservation_group_id", "virtual_machine_scale_set_id", "zone", }, @@ -120,6 +121,19 @@ func resourceLinuxVirtualMachine() *pluginsdk.Resource { "boot_diagnostics": bootDiagnosticsSchema(), + "capacity_reservation_group_id": { + Type: pluginsdk.TypeString, + Optional: true, + // the Compute/VM API is broken and returns the Resource Group name in UPPERCASE + // tracked by https://github.com/Azure/azure-rest-api-specs/issues/19424 + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: computeValidate.CapacityReservationGroupID, + ConflictsWith: []string{ + "availability_set_id", + "proximity_placement_group_id", + }, + }, + "computer_name": { Type: pluginsdk.TypeString, Optional: true, @@ -244,6 +258,9 @@ func resourceLinuxVirtualMachine() *pluginsdk.Resource { // the Compute/VM API is broken and returns the Resource Group name in UPPERCASE :shrug: // tracked by https://github.com/Azure/azure-rest-api-specs/issues/19424 DiffSuppressFunc: suppress.CaseDifference, + ConflictsWith: []string{ + "capacity_reservation_group_id", + }, }, "secret": linuxSecretSchema(), @@ -541,6 +558,14 @@ func resourceLinuxVirtualMachineCreate(d *pluginsdk.ResourceData, meta interface } } + if v, ok := d.GetOk("capacity_reservation_group_id"); ok { + params.CapacityReservation = &compute.CapacityReservationProfile{ + CapacityReservationGroup: &compute.SubResource{ + ID: utils.String(v.(string)), + }, + } + } + if v, ok := d.GetOk("custom_data"); ok { params.OsProfile.CustomData = utils.String(v.(string)) } @@ -685,6 +710,12 @@ func resourceLinuxVirtualMachineRead(d *pluginsdk.ResourceData, meta interface{} } d.Set("availability_set_id", availabilitySetId) + capacityReservationGroupId := "" + if props.CapacityReservation != nil && props.CapacityReservation.CapacityReservationGroup != nil && props.CapacityReservation.CapacityReservationGroup.ID != nil { + capacityReservationGroupId = *props.CapacityReservation.CapacityReservationGroup.ID + } + d.Set("capacity_reservation_group_id", capacityReservationGroupId) + licenseType := "" if props.LicenseType != nil { licenseType = *props.LicenseType @@ -942,6 +973,23 @@ func resourceLinuxVirtualMachineUpdate(d *pluginsdk.ResourceData, meta interface } } + if d.HasChange("capacity_reservation_group_id") { + shouldUpdate = true + shouldDeallocate = true + + if v, ok := d.GetOk("capacity_reservation_group_id"); ok { + update.CapacityReservation = &compute.CapacityReservationProfile{ + CapacityReservationGroup: &compute.SubResource{ + ID: utils.String(v.(string)), + }, + } + } else { + update.CapacityReservation = &compute.CapacityReservationProfile{ + CapacityReservationGroup: &compute.SubResource{}, + } + } + } + if d.HasChange("dedicated_host_id") { shouldUpdate = true diff --git a/internal/services/compute/linux_virtual_machine_resource_scaling_test.go b/internal/services/compute/linux_virtual_machine_resource_scaling_test.go index fb82ba15e7dc..10f538a46ecc 100644 --- a/internal/services/compute/linux_virtual_machine_resource_scaling_test.go +++ b/internal/services/compute/linux_virtual_machine_resource_scaling_test.go @@ -39,6 +39,57 @@ func TestAccLinuxVirtualMachine_scalingAvailabilitySet(t *testing.T) { }) } +func TestAccLinuxVirtualMachine_scalingCapacityReservationGroup(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_linux_virtual_machine", "test") + r := LinuxVirtualMachineResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.scalingCapacityReservationGroup(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccLinuxVirtualMachine_scalingCapacityReservationGroupUpdate(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_linux_virtual_machine", "test") + r := LinuxVirtualMachineResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.scalingCapacityReservationGroupInitial(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.scalingCapacityReservationGroup(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.scalingCapacityReservationGroupUpdate(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.scalingCapacityReservationGroupRemoved(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccLinuxVirtualMachine_scalingDedicatedHost(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_linux_virtual_machine", "test") r := LinuxVirtualMachineResource{} @@ -325,6 +376,232 @@ resource "azurerm_linux_virtual_machine" "test" { `, r.template(data), data.RandomInteger, data.RandomInteger) } +func (r LinuxVirtualMachineResource) scalingCapacityReservationGroupInitial(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_linux_virtual_machine" "test" { + name = "acctestVM-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + size = "Standard_F2" + admin_username = "adminuser" + network_interface_ids = [ + azurerm_network_interface.test.id, + ] + + admin_ssh_key { + username = "adminuser" + public_key = local.first_public_key + } + + os_disk { + caching = "ReadWrite" + storage_account_type = "Standard_LRS" + } + + source_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } +} +`, r.template(data), data.RandomInteger) +} + +func (r LinuxVirtualMachineResource) scalingCapacityReservationGroup(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_linux_virtual_machine" "test" { + name = "acctestVM-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + size = "Standard_F2" + admin_username = "adminuser" + + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + + network_interface_ids = [ + azurerm_network_interface.test.id, + ] + + admin_ssh_key { + username = "adminuser" + public_key = local.first_public_key + } + + os_disk { + caching = "ReadWrite" + storage_account_type = "Standard_LRS" + } + + source_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } + + depends_on = [ + azurerm_capacity_reservation.test, + ] +} +`, r.template(data), data.RandomInteger) +} + +func (r LinuxVirtualMachineResource) scalingCapacityReservationGroupUpdate(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_capacity_reservation_group" "test2" { + name = "acctest-ccrg2-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test2" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test2.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_linux_virtual_machine" "test" { + name = "acctestVM-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + size = "Standard_F2" + admin_username = "adminuser" + + capacity_reservation_group_id = azurerm_capacity_reservation_group.test2.id + + network_interface_ids = [ + azurerm_network_interface.test.id, + ] + + admin_ssh_key { + username = "adminuser" + public_key = local.first_public_key + } + + os_disk { + caching = "ReadWrite" + storage_account_type = "Standard_LRS" + } + + source_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } + + depends_on = [ + azurerm_capacity_reservation.test2, + ] +} +`, r.template(data), data.RandomInteger) +} + +func (r LinuxVirtualMachineResource) scalingCapacityReservationGroupRemoved(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test2" { + name = "acctest-ccrg2-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test2" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test2.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_linux_virtual_machine" "test" { + name = "acctestVM-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + size = "Standard_F2" + admin_username = "adminuser" + + network_interface_ids = [ + azurerm_network_interface.test.id, + ] + + admin_ssh_key { + username = "adminuser" + public_key = local.first_public_key + } + + os_disk { + caching = "ReadWrite" + storage_account_type = "Standard_LRS" + } + + source_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } +} +`, r.template(data), data.RandomInteger) +} + func (r LinuxVirtualMachineResource) scalingDedicatedHostInitial(data acceptance.TestData) string { return fmt.Sprintf(` %s diff --git a/internal/services/compute/linux_virtual_machine_scale_set_disk_os_resource_test.go b/internal/services/compute/linux_virtual_machine_scale_set_disk_os_resource_test.go index c4463237a46b..05271b697625 100644 --- a/internal/services/compute/linux_virtual_machine_scale_set_disk_os_resource_test.go +++ b/internal/services/compute/linux_virtual_machine_scale_set_disk_os_resource_test.go @@ -98,6 +98,21 @@ func TestAccLinuxVirtualMachineScaleSet_disksOSDiskEphemeral(t *testing.T) { }) } +func TestAccLinuxVirtualMachineScaleSet_disksOSDiskEphemeralResourceDisk(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_linux_virtual_machine", "test") + r := LinuxVirtualMachineResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.diskOSEphemeralResourceDisk(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("admin_password"), + }) +} + func TestAccLinuxVirtualMachineScaleSet_disksOSDiskStorageAccountTypeStandardLRS(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_linux_virtual_machine_scale_set", "test") r := LinuxVirtualMachineScaleSetResource{} @@ -482,6 +497,52 @@ resource "azurerm_linux_virtual_machine_scale_set" "test" { `, r.template(data), data.RandomInteger) } +func (r LinuxVirtualMachineScaleSetResource) disksOSDiskEphemeralResourceDisk(data acceptance.TestData) string { + return fmt.Sprintf(` +%s + +resource "azurerm_linux_virtual_machine_scale_set" "test" { + name = "acctestvmss-%d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + sku = "Standard_F2s_v2" + instances = 1 + admin_username = "adminuser" + admin_password = "P@ssword1234!" + + disable_password_authentication = false + + source_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } + + os_disk { + storage_account_type = "Standard_LRS" + caching = "ReadOnly" + + diff_disk_settings { + option = "Local" + placement = "ResourceDisk" + } + } + + network_interface { + name = "example" + primary = true + + ip_configuration { + name = "internal" + primary = true + subnet_id = azurerm_subnet.test.id + } + } +} +`, r.template(data), data.RandomInteger) +} + func (r LinuxVirtualMachineScaleSetResource) disksOSDiskStorageAccountType(data acceptance.TestData, storageAccountType string) string { return fmt.Sprintf(` %s diff --git a/internal/services/compute/linux_virtual_machine_scale_set_resource.go b/internal/services/compute/linux_virtual_machine_scale_set_resource.go index 5dc54a098225..a276c8473178 100644 --- a/internal/services/compute/linux_virtual_machine_scale_set_resource.go +++ b/internal/services/compute/linux_virtual_machine_scale_set_resource.go @@ -193,6 +193,17 @@ func resourceLinuxVirtualMachineScaleSetCreate(d *pluginsdk.ResourceData, meta i }, } + if v, ok := d.GetOk("capacity_reservation_group_id"); ok { + if d.Get("single_placement_group").(bool) { + return fmt.Errorf("`single_placement_group` must be set to `false` when `capacity_reservation_group_id` is specified") + } + virtualMachineProfile.CapacityReservation = &compute.CapacityReservationProfile{ + CapacityReservationGroup: &compute.SubResource{ + ID: utils.String(v.(string)), + }, + } + } + hasHealthExtension := false if vmExtensionsRaw, ok := d.GetOk("extension"); ok { virtualMachineProfile.ExtensionProfile, hasHealthExtension, err = expandVirtualMachineScaleSetExtensions(vmExtensionsRaw.(*pluginsdk.Set).List()) @@ -806,6 +817,12 @@ func resourceLinuxVirtualMachineScaleSetRead(d *pluginsdk.ResourceData, meta int return fmt.Errorf("setting `boot_diagnostics`: %+v", err) } + capacityReservationGroupId := "" + if profile.CapacityReservation != nil && profile.CapacityReservation.CapacityReservationGroup != nil && profile.CapacityReservation.CapacityReservationGroup.ID != nil { + capacityReservationGroupId = *profile.CapacityReservation.CapacityReservationGroup.ID + } + d.Set("capacity_reservation_group_id", capacityReservationGroupId) + // defaulted since BillingProfile isn't returned if it's unset maxBidPrice := float64(-1.0) if profile.BillingProfile != nil && profile.BillingProfile.MaxPrice != nil { @@ -1070,6 +1087,16 @@ func resourceLinuxVirtualMachineScaleSetSchema() map[string]*pluginsdk.Schema { "boot_diagnostics": bootDiagnosticsSchema(), + "capacity_reservation_group_id": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validate.CapacityReservationGroupID, + ConflictsWith: []string{ + "proximity_placement_group_id", + }, + }, + "computer_name_prefix": { Type: pluginsdk.TypeString, Optional: true, @@ -1179,6 +1206,9 @@ func resourceLinuxVirtualMachineScaleSetSchema() map[string]*pluginsdk.Schema { ValidateFunc: validate.ProximityPlacementGroupID, // the Compute API is broken and returns the Resource Group name in UPPERCASE :shrug:, github issue: https://github.com/Azure/azure-rest-api-specs/issues/10016 DiffSuppressFunc: suppress.CaseDifference, + ConflictsWith: []string{ + "capacity_reservation_group_id", + }, }, "rolling_upgrade_policy": VirtualMachineScaleSetRollingUpgradePolicySchema(), diff --git a/internal/services/compute/linux_virtual_machine_scale_set_scaling_resource_test.go b/internal/services/compute/linux_virtual_machine_scale_set_scaling_resource_test.go index 6c5fb71d0dea..b39157675633 100644 --- a/internal/services/compute/linux_virtual_machine_scale_set_scaling_resource_test.go +++ b/internal/services/compute/linux_virtual_machine_scale_set_scaling_resource_test.go @@ -23,6 +23,21 @@ func TestAccLinuxVirtualMachineScaleSet_scalingAutoScale(t *testing.T) { }) } +func TestAccLinuxVirtualMachineScaleSet_scalingCapacityReservationGroupId(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_linux_virtual_machine_scale_set", "test") + r := LinuxVirtualMachineScaleSetResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.scalingCapacityReservationGroupId(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("admin_password"), + }) +} + func TestAccLinuxVirtualMachineScaleSet_scalingInstanceCount(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_linux_virtual_machine_scale_set", "test") r := LinuxVirtualMachineScaleSetResource{} @@ -316,6 +331,70 @@ resource "azurerm_monitor_autoscale_setting" "test" { `, r.template(data), data.RandomInteger) } +func (r LinuxVirtualMachineScaleSetResource) scalingCapacityReservationGroupId(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_linux_virtual_machine_scale_set" "test" { + name = "acctestvmss-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + sku = "Standard_F2" + instances = 1 + admin_username = "adminuser" + admin_password = "P@ssword1234!" + + disable_password_authentication = false + + single_placement_group = false + platform_fault_domain_count = 3 + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + + source_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04-LTS" + version = "latest" + } + + os_disk { + storage_account_type = "Standard_LRS" + caching = "ReadWrite" + } + + network_interface { + name = "example" + primary = true + + ip_configuration { + name = "internal" + primary = true + subnet_id = azurerm_subnet.test.id + } + } + + depends_on = [ + azurerm_capacity_reservation.test, + ] +} +`, r.template(data), data.RandomInteger) +} + func (r LinuxVirtualMachineScaleSetResource) scalingInstanceCount(data acceptance.TestData, instanceCount int) string { return fmt.Sprintf(` %s diff --git a/internal/services/compute/managed_disk_resource.go b/internal/services/compute/managed_disk_resource.go index 8d9bc832f9af..82037cf3d45e 100644 --- a/internal/services/compute/managed_disk_resource.go +++ b/internal/services/compute/managed_disk_resource.go @@ -6,10 +6,9 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" diff --git a/internal/services/compute/orchestrated_virtual_machine_scale_set.go b/internal/services/compute/orchestrated_virtual_machine_scale_set.go index 7dc2482a549e..3ea461927e59 100644 --- a/internal/services/compute/orchestrated_virtual_machine_scale_set.go +++ b/internal/services/compute/orchestrated_virtual_machine_scale_set.go @@ -559,7 +559,16 @@ func OrchestratedVirtualMachineScaleSetOSDiskSchema() *pluginsdk.Schema { string(compute.DiffDiskOptionsLocal), }, false), }, - }, + "placement": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + Default: string(compute.DiffDiskPlacementCacheDisk), + ValidateFunc: validation.StringInSlice([]string{ + string(compute.DiffDiskPlacementCacheDisk), + string(compute.DiffDiskPlacementResourceDisk), + }, false), + }}, }, }, @@ -1211,7 +1220,8 @@ func ExpandOrchestratedVirtualMachineScaleSetOSDisk(input []interface{}, osType if diffDiskSettingsRaw := raw["diff_disk_settings"].([]interface{}); len(diffDiskSettingsRaw) > 0 { diffDiskRaw := diffDiskSettingsRaw[0].(map[string]interface{}) disk.DiffDiskSettings = &compute.DiffDiskSettings{ - Option: compute.DiffDiskOptions(diffDiskRaw["option"].(string)), + Option: compute.DiffDiskOptions(diffDiskRaw["option"].(string)), + Placement: compute.DiffDiskPlacement(diffDiskRaw["placement"].(string)), } } @@ -1781,7 +1791,8 @@ func FlattenOrchestratedVirtualMachineScaleSetOSDisk(input *compute.VirtualMachi diffDiskSettings := make([]interface{}, 0) if input.DiffDiskSettings != nil { diffDiskSettings = append(diffDiskSettings, map[string]interface{}{ - "option": string(input.DiffDiskSettings.Option), + "option": string(input.DiffDiskSettings.Option), + "placement": string(input.DiffDiskSettings.Placement), }) } diff --git a/internal/services/compute/orchestrated_virtual_machine_scale_set_disk_os_resource_test.go b/internal/services/compute/orchestrated_virtual_machine_scale_set_disk_os_resource_test.go new file mode 100644 index 000000000000..3230eb22db41 --- /dev/null +++ b/internal/services/compute/orchestrated_virtual_machine_scale_set_disk_os_resource_test.go @@ -0,0 +1,107 @@ +package compute_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" +) + +func TestAccOrchestratedVirtualMachineScaleSet_disksOSDiskCaching(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_orchestrated_virtual_machine_scale_set", "test") + r := OrchestratedVirtualMachineScaleSetResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.disksOSDiskEphemeral(data, "CacheDisk"), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("os_profile.0.linux_configuration.0.admin_password"), + { + Config: r.disksOSDiskEphemeral(data, "ResourceDisk"), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("os_profile.0.linux_configuration.0.admin_password"), + }) +} + +func (r OrchestratedVirtualMachineScaleSetResource) disksOSDiskEphemeral(data acceptance.TestData, placement string) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-OVMSS-%[1]d" + location = "%[2]s" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%[1]d" + address_space = ["10.0.0.0/16"] + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%[1]d" + resource_group_name = azurerm_resource_group.test.name + virtual_network_name = azurerm_virtual_network.test.name + address_prefixes = ["10.0.2.0/24"] +} + +resource "azurerm_orchestrated_virtual_machine_scale_set" "test" { + name = "acctestOVMSS-%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + + sku_name = "Standard_F2s_v2" + instances = 1 + + platform_fault_domain_count = 2 + + os_profile { + linux_configuration { + computer_name_prefix = "testvm-%[1]d" + admin_username = "myadmin" + admin_password = "Passwword1234" + + disable_password_authentication = false + } + } + + network_interface { + name = "TestNetworkProfile" + primary = true + + ip_configuration { + name = "TestIPConfiguration" + primary = true + subnet_id = azurerm_subnet.test.id + } + } + + os_disk { + storage_account_type = "Standard_LRS" + caching = "ReadOnly" + + diff_disk_settings { + option = "Local" + placement = "%s" + } + } + + source_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "16.04.0-LTS" + version = "latest" + } +} +`, data.RandomInteger, data.Locations.Primary) +} diff --git a/internal/services/compute/orchestrated_virtual_machine_scale_set_resource.go b/internal/services/compute/orchestrated_virtual_machine_scale_set_resource.go index 0a67b3bfc9f8..8032d50aef37 100644 --- a/internal/services/compute/orchestrated_virtual_machine_scale_set_resource.go +++ b/internal/services/compute/orchestrated_virtual_machine_scale_set_resource.go @@ -7,13 +7,11 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/zones" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/zones" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" diff --git a/internal/services/compute/parse/gallery_application.go b/internal/services/compute/parse/gallery_application.go new file mode 100644 index 000000000000..f3fdc29f5e8b --- /dev/null +++ b/internal/services/compute/parse/gallery_application.go @@ -0,0 +1,75 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +type GalleryApplicationId struct { + SubscriptionId string + ResourceGroup string + GalleryName string + ApplicationName string +} + +func NewGalleryApplicationID(subscriptionId, resourceGroup, galleryName, applicationName string) GalleryApplicationId { + return GalleryApplicationId{ + SubscriptionId: subscriptionId, + ResourceGroup: resourceGroup, + GalleryName: galleryName, + ApplicationName: applicationName, + } +} + +func (id GalleryApplicationId) String() string { + segments := []string{ + fmt.Sprintf("Application Name %q", id.ApplicationName), + fmt.Sprintf("Gallery Name %q", id.GalleryName), + fmt.Sprintf("Resource Group %q", id.ResourceGroup), + } + segmentsStr := strings.Join(segments, " / ") + return fmt.Sprintf("%s: (%s)", "Gallery Application", segmentsStr) +} + +func (id GalleryApplicationId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/galleries/%s/applications/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.GalleryName, id.ApplicationName) +} + +// GalleryApplicationID parses a GalleryApplication ID into an GalleryApplicationId struct +func GalleryApplicationID(input string) (*GalleryApplicationId, error) { + id, err := resourceids.ParseAzureResourceID(input) + if err != nil { + return nil, err + } + + resourceId := GalleryApplicationId{ + SubscriptionId: id.SubscriptionID, + ResourceGroup: id.ResourceGroup, + } + + if resourceId.SubscriptionId == "" { + return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + } + + if resourceId.ResourceGroup == "" { + return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") + } + + if resourceId.GalleryName, err = id.PopSegment("galleries"); err != nil { + return nil, err + } + if resourceId.ApplicationName, err = id.PopSegment("applications"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &resourceId, nil +} diff --git a/internal/services/compute/parse/gallery_application_test.go b/internal/services/compute/parse/gallery_application_test.go new file mode 100644 index 000000000000..07413f91c804 --- /dev/null +++ b/internal/services/compute/parse/gallery_application_test.go @@ -0,0 +1,128 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "testing" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.Id = GalleryApplicationId{} + +func TestGalleryApplicationIDFormatter(t *testing.T) { + actual := NewGalleryApplicationID("12345678-1234-9876-4563-123456789012", "resGroup1", "gallery1", "galleryApplication1").ID() + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1" + if actual != expected { + t.Fatalf("Expected %q but got %q", expected, actual) + } +} + +func TestGalleryApplicationID(t *testing.T) { + testData := []struct { + Input string + Error bool + Expected *GalleryApplicationId + }{ + + { + // empty + Input: "", + Error: true, + }, + + { + // missing SubscriptionId + Input: "/", + Error: true, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Error: true, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Error: true, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", + Error: true, + }, + + { + // missing GalleryName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/", + Error: true, + }, + + { + // missing value for GalleryName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/", + Error: true, + }, + + { + // missing ApplicationName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/", + Error: true, + }, + + { + // missing value for ApplicationName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/", + Error: true, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1", + Expected: &GalleryApplicationId{ + SubscriptionId: "12345678-1234-9876-4563-123456789012", + ResourceGroup: "resGroup1", + GalleryName: "gallery1", + ApplicationName: "galleryApplication1", + }, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.COMPUTE/GALLERIES/GALLERY1/APPLICATIONS/GALLERYAPPLICATION1", + Error: true, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Input) + + actual, err := GalleryApplicationID(v.Input) + if err != nil { + if v.Error { + continue + } + + t.Fatalf("Expect a value but got an error: %s", err) + } + if v.Error { + t.Fatal("Expect an error but didn't get one") + } + + if actual.SubscriptionId != v.Expected.SubscriptionId { + t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) + } + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) + } + if actual.GalleryName != v.Expected.GalleryName { + t.Fatalf("Expected %q but got %q for GalleryName", v.Expected.GalleryName, actual.GalleryName) + } + if actual.ApplicationName != v.Expected.ApplicationName { + t.Fatalf("Expected %q but got %q for ApplicationName", v.Expected.ApplicationName, actual.ApplicationName) + } + } +} diff --git a/internal/services/compute/parse/gallery_application_version.go b/internal/services/compute/parse/gallery_application_version.go new file mode 100644 index 000000000000..5e5e6d2f085d --- /dev/null +++ b/internal/services/compute/parse/gallery_application_version.go @@ -0,0 +1,81 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +type GalleryApplicationVersionId struct { + SubscriptionId string + ResourceGroup string + GalleryName string + ApplicationName string + VersionName string +} + +func NewGalleryApplicationVersionID(subscriptionId, resourceGroup, galleryName, applicationName, versionName string) GalleryApplicationVersionId { + return GalleryApplicationVersionId{ + SubscriptionId: subscriptionId, + ResourceGroup: resourceGroup, + GalleryName: galleryName, + ApplicationName: applicationName, + VersionName: versionName, + } +} + +func (id GalleryApplicationVersionId) String() string { + segments := []string{ + fmt.Sprintf("Version Name %q", id.VersionName), + fmt.Sprintf("Application Name %q", id.ApplicationName), + fmt.Sprintf("Gallery Name %q", id.GalleryName), + fmt.Sprintf("Resource Group %q", id.ResourceGroup), + } + segmentsStr := strings.Join(segments, " / ") + return fmt.Sprintf("%s: (%s)", "Gallery Application Version", segmentsStr) +} + +func (id GalleryApplicationVersionId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/galleries/%s/applications/%s/versions/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.GalleryName, id.ApplicationName, id.VersionName) +} + +// GalleryApplicationVersionID parses a GalleryApplicationVersion ID into an GalleryApplicationVersionId struct +func GalleryApplicationVersionID(input string) (*GalleryApplicationVersionId, error) { + id, err := resourceids.ParseAzureResourceID(input) + if err != nil { + return nil, err + } + + resourceId := GalleryApplicationVersionId{ + SubscriptionId: id.SubscriptionID, + ResourceGroup: id.ResourceGroup, + } + + if resourceId.SubscriptionId == "" { + return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + } + + if resourceId.ResourceGroup == "" { + return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") + } + + if resourceId.GalleryName, err = id.PopSegment("galleries"); err != nil { + return nil, err + } + if resourceId.ApplicationName, err = id.PopSegment("applications"); err != nil { + return nil, err + } + if resourceId.VersionName, err = id.PopSegment("versions"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &resourceId, nil +} diff --git a/internal/services/compute/parse/gallery_application_version_test.go b/internal/services/compute/parse/gallery_application_version_test.go new file mode 100644 index 000000000000..eabb8d975e37 --- /dev/null +++ b/internal/services/compute/parse/gallery_application_version_test.go @@ -0,0 +1,144 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "testing" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.Id = GalleryApplicationVersionId{} + +func TestGalleryApplicationVersionIDFormatter(t *testing.T) { + actual := NewGalleryApplicationVersionID("12345678-1234-9876-4563-123456789012", "resGroup1", "gallery1", "galleryApplication1", "galleryApplicationVersion1").ID() + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1/versions/galleryApplicationVersion1" + if actual != expected { + t.Fatalf("Expected %q but got %q", expected, actual) + } +} + +func TestGalleryApplicationVersionID(t *testing.T) { + testData := []struct { + Input string + Error bool + Expected *GalleryApplicationVersionId + }{ + + { + // empty + Input: "", + Error: true, + }, + + { + // missing SubscriptionId + Input: "/", + Error: true, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Error: true, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Error: true, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", + Error: true, + }, + + { + // missing GalleryName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/", + Error: true, + }, + + { + // missing value for GalleryName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/", + Error: true, + }, + + { + // missing ApplicationName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/", + Error: true, + }, + + { + // missing value for ApplicationName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/", + Error: true, + }, + + { + // missing VersionName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1/", + Error: true, + }, + + { + // missing value for VersionName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1/versions/", + Error: true, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1/versions/galleryApplicationVersion1", + Expected: &GalleryApplicationVersionId{ + SubscriptionId: "12345678-1234-9876-4563-123456789012", + ResourceGroup: "resGroup1", + GalleryName: "gallery1", + ApplicationName: "galleryApplication1", + VersionName: "galleryApplicationVersion1", + }, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.COMPUTE/GALLERIES/GALLERY1/APPLICATIONS/GALLERYAPPLICATION1/VERSIONS/GALLERYAPPLICATIONVERSION1", + Error: true, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Input) + + actual, err := GalleryApplicationVersionID(v.Input) + if err != nil { + if v.Error { + continue + } + + t.Fatalf("Expect a value but got an error: %s", err) + } + if v.Error { + t.Fatal("Expect an error but didn't get one") + } + + if actual.SubscriptionId != v.Expected.SubscriptionId { + t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) + } + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) + } + if actual.GalleryName != v.Expected.GalleryName { + t.Fatalf("Expected %q but got %q for GalleryName", v.Expected.GalleryName, actual.GalleryName) + } + if actual.ApplicationName != v.Expected.ApplicationName { + t.Fatalf("Expected %q but got %q for ApplicationName", v.Expected.ApplicationName, actual.ApplicationName) + } + if actual.VersionName != v.Expected.VersionName { + t.Fatalf("Expected %q but got %q for VersionName", v.Expected.VersionName, actual.VersionName) + } + } +} diff --git a/internal/services/compute/registration.go b/internal/services/compute/registration.go index e9e6caa24eb5..77a248942932 100644 --- a/internal/services/compute/registration.go +++ b/internal/services/compute/registration.go @@ -1,6 +1,7 @@ package compute import ( + "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) @@ -74,3 +75,14 @@ func (r Registration) SupportedResources() map[string]*pluginsdk.Resource { return resources } + +func (r Registration) DataSources() []sdk.DataSource { + return []sdk.DataSource{} +} + +func (r Registration) Resources() []sdk.Resource { + return []sdk.Resource{ + GalleryApplicationResource{}, + GalleryApplicationVersionResource{}, + } +} diff --git a/internal/services/compute/resourceids.go b/internal/services/compute/resourceids.go index 75cc0253c84e..46e1aa7c721f 100644 --- a/internal/services/compute/resourceids.go +++ b/internal/services/compute/resourceids.go @@ -1,11 +1,12 @@ package compute -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=AvailabilitySet -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/availabilitySets/set1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=CapacityReservationGroup -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/capacityReservationGroups/capacityReservationGroup1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=CapacityReservation -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/capacityReservationGroups/capacityReservationGroup1/capacityReservations/capacityReservation1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=DedicatedHostGroup -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/hostGroups/hostGroup1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=DedicatedHost -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/hostGroups/hostGroup1/hosts/host1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=DiskEncryptionSet -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/diskEncryptionSets/set1 +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=GalleryApplication -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1 +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=GalleryApplicationVersion -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1/versions/galleryApplicationVersion1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=Image -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/images/image1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=ManagedDisk -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/disks/disk1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=ProximityPlacementGroup -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/proximityPlacementGroups/group1 diff --git a/internal/services/compute/shared_image_data_source_test.go b/internal/services/compute/shared_image_data_source_test.go index 22c40d86f130..f02ba76e8460 100644 --- a/internal/services/compute/shared_image_data_source_test.go +++ b/internal/services/compute/shared_image_data_source_test.go @@ -60,7 +60,7 @@ data "azurerm_shared_image" "test" { gallery_name = azurerm_shared_image.test.gallery_name resource_group_name = azurerm_shared_image.test.resource_group_name } -`, SharedImageResource{}.basic(data, hyperVGen)) +`, SharedImageResource{}.basicWithHyperVGen(data, hyperVGen)) } func (SharedImageDataSource) complete(data acceptance.TestData, hyperVGen string) string { @@ -72,5 +72,5 @@ data "azurerm_shared_image" "test" { gallery_name = azurerm_shared_image.test.gallery_name resource_group_name = azurerm_shared_image.test.resource_group_name } -`, SharedImageResource{}.complete(data, hyperVGen)) +`, SharedImageResource{}.completeWithHyperVGen(data, hyperVGen)) } diff --git a/internal/services/compute/shared_image_resource.go b/internal/services/compute/shared_image_resource.go index 208012aa8519..8f2372db0361 100644 --- a/internal/services/compute/shared_image_resource.go +++ b/internal/services/compute/shared_image_resource.go @@ -8,6 +8,7 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" + "github.com/Azure/go-autorest/autorest/date" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -15,6 +16,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" @@ -68,6 +70,25 @@ func resourceSharedImage() *pluginsdk.Resource { }, false), }, + "disk_types_not_allowed": { + Type: pluginsdk.TypeSet, + Optional: true, + Elem: &pluginsdk.Schema{ + Type: pluginsdk.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(compute.DiskStorageAccountTypesStandardLRS), + string(compute.DiskStorageAccountTypesPremiumLRS), + }, false), + }, + }, + + "end_of_life_date": { + Type: pluginsdk.TypeString, + Optional: true, + DiffSuppressFunc: suppress.RFC3339Time, + ValidateFunc: validation.IsRFC3339Time, + }, + "hyper_v_generation": { Type: pluginsdk.TypeString, Optional: true, @@ -149,6 +170,30 @@ func resourceSharedImage() *pluginsdk.Resource { Optional: true, }, + "max_recommended_vcpu_count": { + Type: pluginsdk.TypeInt, + Optional: true, + ValidateFunc: validation.IntBetween(1, 80), + }, + + "min_recommended_vcpu_count": { + Type: pluginsdk.TypeInt, + Optional: true, + ValidateFunc: validation.IntBetween(1, 80), + }, + + "max_recommended_memory_in_gb": { + Type: pluginsdk.TypeInt, + Optional: true, + ValidateFunc: validation.IntBetween(1, 640), + }, + + "min_recommended_memory_in_gb": { + Type: pluginsdk.TypeInt, + Optional: true, + ValidateFunc: validation.IntBetween(1, 640), + }, + "release_note_uri": { Type: pluginsdk.TypeString, Optional: true, @@ -174,6 +219,12 @@ func resourceSharedImage() *pluginsdk.Resource { "tags": tags.Schema(), }, + + CustomizeDiff: pluginsdk.CustomDiffWithAll( + pluginsdk.ForceNewIfChange("end_of_life_date", func(ctx context.Context, old, new, meta interface{}) bool { + return old.(string) != "" && new.(string) == "" + }), + ), } } @@ -213,10 +264,16 @@ func resourceSharedImageCreateUpdate(d *pluginsdk.ResourceData, meta interface{} }) } + recommended, err := expandGalleryImageRecommended(d) + if err != nil { + return err + } + image := compute.GalleryImage{ Location: utils.String(azure.NormalizeLocation(d.Get("location").(string))), GalleryImageProperties: &compute.GalleryImageProperties{ Description: utils.String(d.Get("description").(string)), + Disallowed: expandGalleryImageDisallowed(d), Identifier: expandGalleryImageIdentifier(d), PrivacyStatementURI: utils.String(d.Get("privacy_statement_uri").(string)), ReleaseNoteURI: utils.String(d.Get("release_note_uri").(string)), @@ -224,10 +281,18 @@ func resourceSharedImageCreateUpdate(d *pluginsdk.ResourceData, meta interface{} HyperVGeneration: compute.HyperVGeneration(d.Get("hyper_v_generation").(string)), PurchasePlan: expandGalleryImagePurchasePlan(d.Get("purchase_plan").([]interface{})), Features: &features, + Recommended: recommended, }, Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } + if v, ok := d.GetOk("end_of_life_date"); ok { + endOfLifeDate, _ := time.Parse(time.RFC3339, v.(string)) + image.GalleryImageProperties.EndOfLifeDate = &date.Time{ + Time: endOfLifeDate, + } + } + if v, ok := d.GetOk("eula"); ok { image.GalleryImageProperties.Eula = utils.String(v.(string)) } @@ -282,7 +347,50 @@ func resourceSharedImageRead(d *pluginsdk.ResourceData, meta interface{}) error if props := resp.GalleryImageProperties; props != nil { d.Set("description", props.Description) + + diskTypesNotAllowed := make([]string, 0) + if disallowed := props.Disallowed; disallowed != nil { + if disallowed.DiskTypes != nil { + for _, v := range *disallowed.DiskTypes { + diskTypesNotAllowed = append(diskTypesNotAllowed, v) + } + } + } + d.Set("disk_types_not_allowed", diskTypesNotAllowed) + + if v := props.EndOfLifeDate; v != nil { + d.Set("end_of_life_date", props.EndOfLifeDate.Format(time.RFC3339)) + } + d.Set("eula", props.Eula) + + maxRecommendedVcpuCount := 0 + minRecommendedVcpuCount := 0 + maxRecommendedMemoryInGB := 0 + minRecommendedMemoryInGB := 0 + if recommended := props.Recommended; recommended != nil { + if vcpus := recommended.VCPUs; vcpus != nil { + if vcpus.Max != nil { + maxRecommendedVcpuCount = int(*vcpus.Max) + } + if vcpus.Min != nil { + minRecommendedVcpuCount = int(*vcpus.Min) + } + } + if memory := recommended.Memory; memory != nil { + if memory.Max != nil { + maxRecommendedMemoryInGB = int(*memory.Max) + } + if memory.Min != nil { + minRecommendedMemoryInGB = int(*memory.Min) + } + } + } + d.Set("max_recommended_vcpu_count", maxRecommendedVcpuCount) + d.Set("min_recommended_vcpu_count", minRecommendedVcpuCount) + d.Set("max_recommended_memory_in_gb", maxRecommendedMemoryInGB) + d.Set("min_recommended_memory_in_gb", minRecommendedMemoryInGB) + d.Set("os_type", string(props.OsType)) d.Set("specialized", props.OsState == compute.OperatingSystemStateTypesSpecialized) d.Set("hyper_v_generation", string(props.HyperVGeneration)) @@ -469,3 +577,49 @@ func flattenGalleryImagePurchasePlan(input *compute.ImagePurchasePlan) []interfa }, } } + +func expandGalleryImageDisallowed(d *pluginsdk.ResourceData) *compute.Disallowed { + diskTypesNotAllowedRaw := d.Get("disk_types_not_allowed").(*pluginsdk.Set).List() + + diskTypesNotAllowed := make([]string, 0) + for _, v := range diskTypesNotAllowedRaw { + diskTypesNotAllowed = append(diskTypesNotAllowed, v.(string)) + } + + return &compute.Disallowed{ + DiskTypes: &diskTypesNotAllowed, + } +} + +func expandGalleryImageRecommended(d *pluginsdk.ResourceData) (*compute.RecommendedMachineConfiguration, error) { + result := &compute.RecommendedMachineConfiguration{ + VCPUs: &compute.ResourceRange{}, + Memory: &compute.ResourceRange{}, + } + + maxVcpuCount := d.Get("max_recommended_vcpu_count").(int) + minVcpuCount := d.Get("min_recommended_vcpu_count").(int) + if maxVcpuCount != 0 && minVcpuCount != 0 && maxVcpuCount < minVcpuCount { + return nil, fmt.Errorf("`max_recommended_vcpu_count` must be greater than or equal to `min_recommended_vcpu_count`") + } + if maxVcpuCount != 0 { + result.VCPUs.Max = utils.Int32(int32(maxVcpuCount)) + } + if minVcpuCount != 0 { + result.VCPUs.Min = utils.Int32(int32(minVcpuCount)) + } + + maxMemory := d.Get("max_recommended_memory_in_gb").(int) + minMemory := d.Get("min_recommended_memory_in_gb").(int) + if maxMemory != 0 && minMemory != 0 && maxMemory < minMemory { + return nil, fmt.Errorf("`max_recommended_memory_in_gb` must be greater than or equal to `min_recommended_memory_in_gb`") + } + if maxMemory != 0 { + result.Memory.Max = utils.Int32(int32(maxMemory)) + } + if minMemory != 0 { + result.Memory.Min = utils.Int32(int32(minMemory)) + } + + return result, nil +} diff --git a/internal/services/compute/shared_image_resource_test.go b/internal/services/compute/shared_image_resource_test.go index 472d67828dce..02baa96a135f 100644 --- a/internal/services/compute/shared_image_resource_test.go +++ b/internal/services/compute/shared_image_resource_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "testing" + "time" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" @@ -20,7 +21,7 @@ func TestAccSharedImage_basic(t *testing.T) { r := SharedImageResource{} data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, ""), + Config: r.basicWithHyperVGen(data, ""), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("description").HasValue(""), @@ -35,7 +36,7 @@ func TestAccSharedImage_basic_hyperVGeneration_V2(t *testing.T) { r := SharedImageResource{} data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, "V2"), + Config: r.basicWithHyperVGen(data, "V2"), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("description").HasValue(""), @@ -52,7 +53,7 @@ func TestAccSharedImage_requiresImport(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, ""), + Config: r.basicWithHyperVGen(data, ""), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("description").HasValue(""), @@ -67,7 +68,7 @@ func TestAccSharedImage_complete(t *testing.T) { r := SharedImageResource{} data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.complete(data, "V1"), + Config: r.completeWithHyperVGen(data, "V1"), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("os_type").HasValue("Linux"), @@ -166,6 +167,101 @@ func TestAccSharedImage_releaseNoteURI(t *testing.T) { }) } +func TestAccSharedImage_disallowedDiskTypes(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_shared_image", "test") + r := SharedImageResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basicWithDiskTypesNotAllowed(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basicWithDiskTypesNotAllowedUpdated(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basicWithDiskTypesNotAllowed(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccSharedImage_endOfLifeDate(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_shared_image", "test") + r := SharedImageResource{} + + endOfLifeDate := time.Now().Add(time.Hour * 10).Format(time.RFC3339) + endOfLifeDateUpdated := time.Now().Add(time.Hour * 20).Format(time.RFC3339) + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.endOfLifeDate(data, endOfLifeDate), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.endOfLifeDate(data, endOfLifeDateUpdated), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccSharedImage_recommended(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_shared_image", "test") + r := SharedImageResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basicWithRecommended(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basicWithRecommendedUpdated(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basicWithRecommended(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func (t SharedImageResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { id, err := parse.SharedImageID(state.ID) if err != nil { @@ -180,7 +276,36 @@ func (t SharedImageResource) Exists(ctx context.Context, clients *clients.Client return utils.Bool(resp.ID != nil), nil } -func (SharedImageResource) basic(data acceptance.TestData, hyperVGen string) string { +func (SharedImageResource) basic(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[2]d" + location = "%[1]s" +} +resource "azurerm_shared_image_gallery" "test" { + name = "acctestsig%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} +resource "azurerm_shared_image" "test" { + name = "acctestimg%[2]d" + gallery_name = azurerm_shared_image_gallery.test.name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + os_type = "Linux" + identifier { + publisher = "AccTesPublisher%[2]d" + offer = "AccTesOffer%[2]d" + sku = "AccTesSku%[2]d" + } +} +`, data.Locations.Primary, data.RandomInteger) +} + +func (SharedImageResource) basicWithHyperVGen(data acceptance.TestData, hyperVGen string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -274,10 +399,10 @@ resource "azurerm_shared_image" "import" { sku = "AccTesSku%d" } } -`, r.basic(data, ""), data.RandomInteger, data.RandomInteger, data.RandomInteger) +`, r.basicWithHyperVGen(data, ""), data.RandomInteger, data.RandomInteger, data.RandomInteger) } -func (SharedImageResource) complete(data acceptance.TestData, hyperVGen string) string { +func (SharedImageResource) completeWithHyperVGen(data acceptance.TestData, hyperVGen string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -526,3 +651,189 @@ resource "azurerm_shared_image" "test" { } `, data.Locations.Primary, data.RandomInteger) } + +func (SharedImageResource) basicWithDiskTypesNotAllowed(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[2]d" + location = "%[1]s" +} + +resource "azurerm_shared_image_gallery" "test" { + name = "acctestsig%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_shared_image" "test" { + name = "acctestimg%[2]d" + gallery_name = azurerm_shared_image_gallery.test.name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + os_type = "Linux" + + disk_types_not_allowed = [ + "Standard_LRS", + ] + + identifier { + publisher = "AccTesPublisher%[2]d" + offer = "AccTesOffer%[2]d" + sku = "AccTesSku%[2]d" + } +} +`, data.Locations.Primary, data.RandomInteger) +} + +func (SharedImageResource) basicWithDiskTypesNotAllowedUpdated(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[2]d" + location = "%[1]s" +} + +resource "azurerm_shared_image_gallery" "test" { + name = "acctestsig%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_shared_image" "test" { + name = "acctestimg%[2]d" + gallery_name = azurerm_shared_image_gallery.test.name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + os_type = "Linux" + + disk_types_not_allowed = [ + "Standard_LRS", + "Premium_LRS", + ] + + identifier { + publisher = "AccTesPublisher%[2]d" + offer = "AccTesOffer%[2]d" + sku = "AccTesSku%[2]d" + } +} +`, data.Locations.Primary, data.RandomInteger) +} + +func (SharedImageResource) endOfLifeDate(data acceptance.TestData, endOfLifeDate string) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[2]d" + location = "%[1]s" +} + +resource "azurerm_shared_image_gallery" "test" { + name = "acctestsig%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_shared_image" "test" { + name = "acctestimg%[2]d" + gallery_name = azurerm_shared_image_gallery.test.name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + os_type = "Linux" + + end_of_life_date = "%[3]s" + + identifier { + publisher = "AccTesPublisher%[2]d" + offer = "AccTesOffer%[2]d" + sku = "AccTesSku%[2]d" + } +} +`, data.Locations.Primary, data.RandomInteger, endOfLifeDate) +} + +func (SharedImageResource) basicWithRecommended(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[2]d" + location = "%[1]s" +} + +resource "azurerm_shared_image_gallery" "test" { + name = "acctestsig%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_shared_image" "test" { + name = "acctestimg%[2]d" + gallery_name = azurerm_shared_image_gallery.test.name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + os_type = "Linux" + + max_recommended_vcpu_count = 8 + min_recommended_vcpu_count = 7 + max_recommended_memory_in_gb = 6 + min_recommended_memory_in_gb = 5 + + identifier { + publisher = "AccTesPublisher%[2]d" + offer = "AccTesOffer%[2]d" + sku = "AccTesSku%[2]d" + } +} +`, data.Locations.Primary, data.RandomInteger) +} + +func (SharedImageResource) basicWithRecommendedUpdated(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[2]d" + location = "%[1]s" +} + +resource "azurerm_shared_image_gallery" "test" { + name = "acctestsig%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_shared_image" "test" { + name = "acctestimg%[2]d" + gallery_name = azurerm_shared_image_gallery.test.name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + os_type = "Linux" + + max_recommended_vcpu_count = 4 + min_recommended_vcpu_count = 3 + max_recommended_memory_in_gb = 2 + min_recommended_memory_in_gb = 1 + + identifier { + publisher = "AccTesPublisher%[2]d" + offer = "AccTesOffer%[2]d" + sku = "AccTesSku%[2]d" + } +} +`, data.Locations.Primary, data.RandomInteger) +} diff --git a/internal/services/compute/shared_image_version_data_source.go b/internal/services/compute/shared_image_version_data_source.go index 3a4c415d7213..38bde5406b64 100644 --- a/internal/services/compute/shared_image_version_data_source.go +++ b/internal/services/compute/shared_image_version_data_source.go @@ -5,10 +5,9 @@ import ( "fmt" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" @@ -118,8 +117,14 @@ func dataSourceSharedImageVersionRead(d *pluginsdk.ResourceData, meta interface{ return err } - d.SetId(id.ID()) - d.Set("name", image.Name) + name := "" + if image.Name != nil { + name = *image.Name + } + + exactId := parse.NewSharedImageVersionID(subscriptionId, id.ResourceGroup, id.GalleryName, id.ImageName, name) + d.SetId(exactId.ID()) + d.Set("name", name) d.Set("image_name", id.ImageName) d.Set("gallery_name", id.GalleryName) d.Set("resource_group_name", id.ResourceGroup) diff --git a/internal/services/compute/ssh_public_key_data_source.go b/internal/services/compute/ssh_public_key_data_source.go index 84e13f26e5d8..372f0982db12 100644 --- a/internal/services/compute/ssh_public_key_data_source.go +++ b/internal/services/compute/ssh_public_key_data_source.go @@ -5,14 +5,14 @@ import ( "regexp" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceSshPublicKey() *pluginsdk.Resource { @@ -40,7 +40,7 @@ func dataSourceSshPublicKey() *pluginsdk.Resource { Computed: true, }, - "tags": tags.Schema(), + "tags": commonschema.Tags(), }, } } @@ -51,11 +51,10 @@ func dataSourceSshPublicKeyRead(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewSSHPublicKeyID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + id := sshpublickeys.NewSshPublicKeyID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + resp, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } return fmt.Errorf("making Read request on %s: %s", id, err) @@ -63,17 +62,23 @@ func dataSourceSshPublicKeyRead(d *pluginsdk.ResourceData, meta interface{}) err d.SetId(id.ID()) - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) + d.Set("name", id.SshPublicKeyName) + d.Set("resource_group_name", id.ResourceGroupName) + + if model := resp.Model; model != nil { + var publicKey *string + if props := model.Properties; props.PublicKey != nil { + publicKey, err = NormalizeSSHKey(*props.PublicKey) + if err != nil { + return fmt.Errorf("normalising public key: %+v", err) + } + } + d.Set("public_key", publicKey) - var publicKey *string - if props := resp.SSHPublicKeyResourceProperties; props.PublicKey != nil { - publicKey, err = NormalizeSSHKey(*props.PublicKey) - if err != nil { - return fmt.Errorf("normalising public key: %+v", err) + if err := tags.FlattenAndSet(d, model.Tags); err != nil { + return err } } - d.Set("public_key", publicKey) - return tags.FlattenAndSet(d, resp.Tags) + return nil } diff --git a/internal/services/compute/ssh_public_key_resource.go b/internal/services/compute/ssh_public_key_resource.go index 3704b57c1ada..b1cfae138130 100644 --- a/internal/services/compute/ssh_public_key_resource.go +++ b/internal/services/compute/ssh_public_key_resource.go @@ -6,14 +6,14 @@ import ( "regexp" "time" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" "github.com/hashicorp/go-azure-helpers/lang/response" - "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -28,7 +28,7 @@ func resourceSshPublicKey() *pluginsdk.Resource { Delete: resourceSshPublicKeyDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.SSHPublicKeyID(id) + _, err := sshpublickeys.ParseSshPublicKeyID(id) return err }), @@ -49,12 +49,10 @@ func resourceSshPublicKey() *pluginsdk.Resource { "Public SSH Key name must be 1 - 128 characters long, can contain letters, numbers, underscores, and hyphens (but the first and last character must be a letter or number).", ), }, - // We have to ignore case due to incorrect capitalisation of resource group name in - // ID in the response we get from the API request. - // Related issue: https://github.com/Azure/azure-rest-api-specs/issues/13491 - "resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(), - "location": azure.SchemaLocation(), + "resource_group_name": commonschema.ResourceGroupName(), + + "location": commonschema.Location(), "public_key": { Type: pluginsdk.TypeString, @@ -63,7 +61,7 @@ func resourceSshPublicKey() *pluginsdk.Resource { ValidateFunc: validate.SSHKey, }, - "tags": tags.Schema(), + "tags": commonschema.Tags(), }, } } @@ -74,35 +72,28 @@ func resourceSshPublicKeyCreate(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewSSHPublicKeyID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - public_key := d.Get("public_key").(string) - - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + id := sshpublickeys.NewSshPublicKeyID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + resp, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("checking for existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(resp.Response) { - return tf.ImportAsExistsError("azurerm_ssh_public_key", *resp.ID) + if !response.WasNotFound(resp.HttpResponse) { + return tf.ImportAsExistsError("azurerm_ssh_public_key", id.ID()) } - location := azure.NormalizeLocation(d.Get("location").(string)) - - t := d.Get("tags").(map[string]interface{}) - - params := compute.SSHPublicKeyResource{ - Name: utils.String(id.Name), - Location: utils.String(location), - Tags: tags.Expand(t), - SSHPublicKeyResourceProperties: &compute.SSHPublicKeyResourceProperties{ - PublicKey: utils.String(public_key), + payload := sshpublickeys.SshPublicKeyResource{ + Location: location.Normalize(d.Get("location").(string)), + Properties: &sshpublickeys.SshPublicKeyResourceProperties{ + PublicKey: utils.String(d.Get("public_key").(string)), }, + Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } - if _, err := client.Create(ctx, id.ResourceGroup, id.Name, params); err != nil { - return fmt.Errorf("creating SSH Public Key %s: %+v", id, err) + if _, err := client.Create(ctx, id, payload); err != nil { + return fmt.Errorf("creating/updating %s: %+v", id, err) } d.SetId(id.ID()) @@ -115,33 +106,38 @@ func resourceSshPublicKeyRead(d *pluginsdk.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SSHPublicKeyID(d.Id()) + id, err := sshpublickeys.ParseSshPublicKeyID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[DEBUG] SSH Public Key %q was not found in Resource Group %q - removing from state!", id.Name, id.ResourceGroup) + if response.WasNotFound(resp.HttpResponse) { + log.Printf("[DEBUG] %s was not found - removing from state!", *id) d.SetId("") return nil } - return fmt.Errorf("retrieving SSH Public Key %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %+v", *id, err) } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } + d.Set("name", id.SshPublicKeyName) + d.Set("resource_group_name", id.ResourceGroupName) + + if model := resp.Model; model != nil { + d.Set("location", location.Normalize(model.Location)) + + if props := model.Properties; props != nil { + d.Set("public_key", props.PublicKey) + } - if props := resp.SSHPublicKeyResourceProperties; props != nil { - d.Set("public_key", props.PublicKey) + if err := tags.FlattenAndSet(d, model.Tags); err != nil { + return err + } } - return tags.FlattenAndSet(d, resp.Tags) + return nil } func resourceSshPublicKeyUpdate(d *pluginsdk.ResourceData, meta interface{}) error { @@ -149,44 +145,35 @@ func resourceSshPublicKeyUpdate(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SSHPublicKeyID(d.Id()) + id, err := sshpublickeys.ParseSshPublicKeyID(d.Id()) if err != nil { return err } - log.Printf("[DEBUG] Retrieving SSH Public Key %q (Resource Group %q)..", id.Name, id.ResourceGroup) - existing, err := client.Get(ctx, id.ResourceGroup, id.Name) + existing, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse) { return nil } - return fmt.Errorf("retrieving SSH Public Key %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %+v", *id, err) } - props := compute.SSHPublicKeyResourceProperties{} - + payload := sshpublickeys.SshPublicKeyUpdateResource{} if d.HasChange("public_key") { - props.PublicKey = utils.String(d.Get("public_key").(string)) - } - - update := compute.SSHPublicKeyUpdateResource{ - SSHPublicKeyResourceProperties: &props, + payload.Properties = &sshpublickeys.SshPublicKeyResourceProperties{ + PublicKey: utils.String(d.Get("public_key").(string)), + } } - if d.HasChange("tags") { tagsRaw := d.Get("tags").(map[string]interface{}) - update.Tags = tags.Expand(tagsRaw) + payload.Tags = tags.Expand(tagsRaw) } - log.Printf("[DEBUG] Updating SSH Public Key %q (Resource Group %q)..", id.Name, id.ResourceGroup) - - if _, err := client.Update(ctx, id.ResourceGroup, id.Name, update); err != nil { - return fmt.Errorf("updating SSH Public Key %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + if _, err := client.Update(ctx, *id, payload); err != nil { + return fmt.Errorf("updating %s: %+v", *id, err) } - log.Printf("[DEBUG] Updated SSH Public Key %q (Resource Group %q).", id.Name, id.ResourceGroup) - return resourceSshPublicKeyRead(d, meta) } @@ -195,31 +182,14 @@ func resourceSshPublicKeyDelete(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SSHPublicKeyID(d.Id()) + id, err := sshpublickeys.ParseSshPublicKeyID(d.Id()) if err != nil { return err } - log.Printf("[DEBUG] Retrieving SSH Public Key %q (Resource Group %q)..", id.Name, id.ResourceGroup) - existing, err := client.Get(ctx, id.ResourceGroup, id.Name) - if err != nil { - if utils.ResponseWasNotFound(existing.Response) { - return nil - } - - return fmt.Errorf("retrieving SSH Public Key %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) - } - - log.Printf("[DEBUG] Deleting SSH Public Key %q (Resource Group %q)..", id.Name, id.ResourceGroup) - resp, err := client.Delete(ctx, id.ResourceGroup, id.Name) - if err != nil { - if response.WasNotFound(resp.Response) { - return nil - } - return fmt.Errorf("deleting SSH Public Key %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + if _, err := client.Delete(ctx, *id); err != nil { + return fmt.Errorf("deleting %s: %+v", *id, err) } - log.Printf("[DEBUG] Deleted SSH Public Key %q (Resource Group %q).", id.Name, id.ResourceGroup) - return nil } diff --git a/internal/services/compute/ssh_public_key_resource_test.go b/internal/services/compute/ssh_public_key_resource_test.go index f53956f19fc9..3f0610e44aba 100644 --- a/internal/services/compute/ssh_public_key_resource_test.go +++ b/internal/services/compute/ssh_public_key_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -43,17 +43,17 @@ func TestAccSshPublicKey_CreateUpdate(t *testing.T) { } func (t SSHPublicKeyResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.SSHPublicKeyID(state.ID) + id, err := sshpublickeys.ParseSshPublicKeyID(state.ID) if err != nil { return nil, err } - resp, err := clients.Compute.SSHPublicKeysClient.Get(ctx, id.ResourceGroup, id.Name) + resp, err := clients.Compute.SSHPublicKeysClient.Get(ctx, *id) if err != nil { - return nil, fmt.Errorf("retrieving Compute SSH Public Key %q", id.String()) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (SSHPublicKeyResource) template(data acceptance.TestData, sshKey string) string { diff --git a/internal/services/compute/validate/compute.go b/internal/services/compute/validate/compute.go index 6b2910f6c781..3b23edd19c41 100644 --- a/internal/services/compute/validate/compute.go +++ b/internal/services/compute/validate/compute.go @@ -50,6 +50,31 @@ func SharedImageVersionName(v interface{}, k string) (warnings []string, errors return warnings, errors } +func GalleryApplicationName(v interface{}, k string) (warnings []string, errors []error) { + value := v.(string) + + if !regexp.MustCompile(`^[A-Za-z0-9._-]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf("%s can only contain alphanumeric, full stops, dashes and underscores. Got %q.", k, value)) + } + + length := len(value) + if length > 80 { + errors = append(errors, fmt.Errorf("%s can be up to 80 characters, currently %d.", k, length)) + } + + return warnings, errors +} + +func GalleryApplicationVersionName(v interface{}, k string) (warnings []string, errors []error) { + value := v.(string) + + if !regexp.MustCompile(`^([0-9]{1,10}\.[0-9]{1,10}\.[0-9]{1,10})$`).MatchString(value) && value != "latest" && value != "recent" { + errors = append(errors, fmt.Errorf("Expected %s to be in the format `1.2.3`, `latest`, or `recent` but got %q.", k, value)) + } + + return warnings, errors +} + // VirtualMachineTimeZone returns a case-sensitive validation function for the Time Zones for a Virtual Machine func VirtualMachineTimeZone() pluginsdk.SchemaValidateFunc { return virtualMachineTimeZone(false) diff --git a/internal/services/compute/validate/compute_test.go b/internal/services/compute/validate/compute_test.go index a018cd888871..f7773a8c8221 100644 --- a/internal/services/compute/validate/compute_test.go +++ b/internal/services/compute/validate/compute_test.go @@ -174,6 +174,116 @@ func TestSharedImageVersionName(t *testing.T) { } } +func TestGalleryApplicationName(t *testing.T) { + cases := []struct { + Input string + ShouldError bool + }{ + { + Input: "", + ShouldError: true, + }, + { + Input: "hello", + ShouldError: false, + }, + { + Input: "hello123", + ShouldError: false, + }, + { + Input: "hello.123", + ShouldError: false, + }, + { + Input: "hello,123", + ShouldError: true, + }, + { + Input: "hello_123", + ShouldError: false, + }, + { + Input: "hello-123", + ShouldError: false, + }, + { + Input: strings.Repeat("a", 80), + ShouldError: false, + }, + { + Input: strings.Repeat("a", 81), + ShouldError: true, + }, + } + + for _, tc := range cases { + t.Run(tc.Input, func(t *testing.T) { + _, errors := GalleryApplicationName(tc.Input, "test") + + hasErrors := len(errors) > 0 + if !hasErrors && tc.ShouldError { + t.Fatalf("Expected an error but didn't get one for %q", tc.Input) + } + + if hasErrors && !tc.ShouldError { + t.Fatalf("Expected to get no errors for %q but got %d", tc.Input, len(errors)) + } + }) + } +} + +func TestGalleryApplicationVersionName(t *testing.T) { + cases := []struct { + Input string + ShouldError bool + }{ + { + Input: "", + ShouldError: true, + }, + { + Input: "a.b.c", + ShouldError: true, + }, + { + Input: "1.2.3", + ShouldError: false, + }, + { + Input: "0.0.1", + ShouldError: false, + }, + { + Input: "hello", + ShouldError: true, + }, + { + Input: "1.2.3.4", + ShouldError: true, + }, + { + Input: "hell0-there", + ShouldError: true, + }, + } + + for _, tc := range cases { + t.Run(tc.Input, func(t *testing.T) { + _, errors := GalleryApplicationVersionName(tc.Input, "test") + + hasErrors := len(errors) > 0 + if !hasErrors && tc.ShouldError { + t.Fatalf("Expected an error but didn't get one for %q", tc.Input) + } + + if hasErrors && !tc.ShouldError { + t.Fatalf("Expected to get no errors for %q but got %d", tc.Input, len(errors)) + } + }) + } +} + func TestVirtualMachineTimeZone(t *testing.T) { cases := []struct { Value string diff --git a/internal/services/compute/validate/gallery_application_id.go b/internal/services/compute/validate/gallery_application_id.go new file mode 100644 index 000000000000..74d3c84c52d4 --- /dev/null +++ b/internal/services/compute/validate/gallery_application_id.go @@ -0,0 +1,23 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + + "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" +) + +func GalleryApplicationID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := parse.GalleryApplicationID(v); err != nil { + errors = append(errors, err) + } + + return +} diff --git a/internal/services/compute/validate/gallery_application_id_test.go b/internal/services/compute/validate/gallery_application_id_test.go new file mode 100644 index 000000000000..3fa7f71d9aab --- /dev/null +++ b/internal/services/compute/validate/gallery_application_id_test.go @@ -0,0 +1,88 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import "testing" + +func TestGalleryApplicationID(t *testing.T) { + cases := []struct { + Input string + Valid bool + }{ + + { + // empty + Input: "", + Valid: false, + }, + + { + // missing SubscriptionId + Input: "/", + Valid: false, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Valid: false, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Valid: false, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", + Valid: false, + }, + + { + // missing GalleryName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/", + Valid: false, + }, + + { + // missing value for GalleryName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/", + Valid: false, + }, + + { + // missing ApplicationName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/", + Valid: false, + }, + + { + // missing value for ApplicationName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/", + Valid: false, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1", + Valid: true, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.COMPUTE/GALLERIES/GALLERY1/APPLICATIONS/GALLERYAPPLICATION1", + Valid: false, + }, + } + for _, tc := range cases { + t.Logf("[DEBUG] Testing Value %s", tc.Input) + _, errors := GalleryApplicationID(tc.Input, "test") + valid := len(errors) == 0 + + if tc.Valid != valid { + t.Fatalf("Expected %t but got %t", tc.Valid, valid) + } + } +} diff --git a/internal/services/compute/validate/gallery_application_version_id.go b/internal/services/compute/validate/gallery_application_version_id.go new file mode 100644 index 000000000000..4865352012e6 --- /dev/null +++ b/internal/services/compute/validate/gallery_application_version_id.go @@ -0,0 +1,23 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + + "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" +) + +func GalleryApplicationVersionID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := parse.GalleryApplicationVersionID(v); err != nil { + errors = append(errors, err) + } + + return +} diff --git a/internal/services/compute/validate/gallery_application_version_id_test.go b/internal/services/compute/validate/gallery_application_version_id_test.go new file mode 100644 index 000000000000..11deac673b9c --- /dev/null +++ b/internal/services/compute/validate/gallery_application_version_id_test.go @@ -0,0 +1,100 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import "testing" + +func TestGalleryApplicationVersionID(t *testing.T) { + cases := []struct { + Input string + Valid bool + }{ + + { + // empty + Input: "", + Valid: false, + }, + + { + // missing SubscriptionId + Input: "/", + Valid: false, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Valid: false, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Valid: false, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", + Valid: false, + }, + + { + // missing GalleryName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/", + Valid: false, + }, + + { + // missing value for GalleryName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/", + Valid: false, + }, + + { + // missing ApplicationName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/", + Valid: false, + }, + + { + // missing value for ApplicationName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/", + Valid: false, + }, + + { + // missing VersionName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1/", + Valid: false, + }, + + { + // missing value for VersionName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1/versions/", + Valid: false, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1/versions/galleryApplicationVersion1", + Valid: true, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESGROUP1/PROVIDERS/MICROSOFT.COMPUTE/GALLERIES/GALLERY1/APPLICATIONS/GALLERYAPPLICATION1/VERSIONS/GALLERYAPPLICATIONVERSION1", + Valid: false, + }, + } + for _, tc := range cases { + t.Logf("[DEBUG] Testing Value %s", tc.Input) + _, errors := GalleryApplicationVersionID(tc.Input, "test") + valid := len(errors) == 0 + + if tc.Valid != valid { + t.Fatalf("Expected %t but got %t", tc.Valid, valid) + } + } +} diff --git a/internal/services/compute/virtual_machine_scale_set.go b/internal/services/compute/virtual_machine_scale_set.go index 3bc59ecf4888..b018a8765e83 100644 --- a/internal/services/compute/virtual_machine_scale_set.go +++ b/internal/services/compute/virtual_machine_scale_set.go @@ -4,9 +4,8 @@ import ( "bytes" "fmt" - identity "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" + identity "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" azValidate "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/validate" @@ -1101,6 +1100,16 @@ func VirtualMachineScaleSetOSDiskSchema() *pluginsdk.Schema { string(compute.DiffDiskOptionsLocal), }, false), }, + "placement": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + Default: string(compute.DiffDiskPlacementCacheDisk), + ValidateFunc: validation.StringInSlice([]string{ + string(compute.DiffDiskPlacementCacheDisk), + string(compute.DiffDiskPlacementResourceDisk), + }, false), + }, }, }, }, @@ -1153,8 +1162,9 @@ func VirtualMachineScaleSetOSDiskSchema() *pluginsdk.Schema { func ExpandVirtualMachineScaleSetOSDisk(input []interface{}, osType compute.OperatingSystemTypes) (*compute.VirtualMachineScaleSetOSDisk, error) { raw := input[0].(map[string]interface{}) + caching := raw["caching"].(string) disk := compute.VirtualMachineScaleSetOSDisk{ - Caching: compute.CachingTypes(raw["caching"].(string)), + Caching: compute.CachingTypes(caching), ManagedDisk: &compute.VirtualMachineScaleSetManagedDiskParameters{ StorageAccountType: compute.StorageAccountTypes(raw["storage_account_type"].(string)), }, @@ -1191,9 +1201,15 @@ func ExpandVirtualMachineScaleSetOSDisk(input []interface{}, osType compute.Oper } if diffDiskSettingsRaw := raw["diff_disk_settings"].([]interface{}); len(diffDiskSettingsRaw) > 0 { + if caching != string(compute.CachingTypesReadOnly) { + // Restriction per https://docs.microsoft.com/azure/virtual-machines/ephemeral-os-disks-deploy#vm-template-deployment + return nil, fmt.Errorf("`diff_disk_settings` can only be set when `caching` is set to `ReadOnly`") + } + diffDiskRaw := diffDiskSettingsRaw[0].(map[string]interface{}) disk.DiffDiskSettings = &compute.DiffDiskSettings{ - Option: compute.DiffDiskOptions(diffDiskRaw["option"].(string)), + Option: compute.DiffDiskOptions(diffDiskRaw["option"].(string)), + Placement: compute.DiffDiskPlacement(diffDiskRaw["placement"].(string)), } } @@ -1231,7 +1247,8 @@ func FlattenVirtualMachineScaleSetOSDisk(input *compute.VirtualMachineScaleSetOS diffDiskSettings := make([]interface{}, 0) if input.DiffDiskSettings != nil { diffDiskSettings = append(diffDiskSettings, map[string]interface{}{ - "option": string(input.DiffDiskSettings.Option), + "option": string(input.DiffDiskSettings.Option), + "placement": string(input.DiffDiskSettings.Placement), }) } diff --git a/internal/services/compute/windows_virtual_machine_resource.go b/internal/services/compute/windows_virtual_machine_resource.go index 58a4a6fced78..0a68f6a74a16 100644 --- a/internal/services/compute/windows_virtual_machine_resource.go +++ b/internal/services/compute/windows_virtual_machine_resource.go @@ -7,11 +7,11 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" azValidate "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" @@ -109,11 +109,12 @@ func resourceWindowsVirtualMachine() *pluginsdk.Resource { Type: pluginsdk.TypeString, Optional: true, ForceNew: true, - ValidateFunc: computeValidate.AvailabilitySetID, + ValidateFunc: availabilitysets.ValidateAvailabilitySetID, // the Compute/VM API is broken and returns the Availability Set name in UPPERCASE :shrug: // tracked by https://github.com/Azure/azure-rest-api-specs/issues/19424 DiffSuppressFunc: suppress.CaseDifference, ConflictsWith: []string{ + "capacity_reservation_group_id", "virtual_machine_scale_set_id", "zone", }, @@ -121,6 +122,19 @@ func resourceWindowsVirtualMachine() *pluginsdk.Resource { "boot_diagnostics": bootDiagnosticsSchema(), + "capacity_reservation_group_id": { + Type: pluginsdk.TypeString, + Optional: true, + // the Compute/VM API is broken and returns the Resource Group name in UPPERCASE + // tracked by https://github.com/Azure/azure-rest-api-specs/issues/19424 + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: computeValidate.CapacityReservationGroupID, + ConflictsWith: []string{ + "availability_set_id", + "proximity_placement_group_id", + }, + }, + "computer_name": { Type: pluginsdk.TypeString, Optional: true, @@ -261,6 +275,9 @@ func resourceWindowsVirtualMachine() *pluginsdk.Resource { // the Compute/VM API is broken and returns the Resource Group name in UPPERCASE :shrug: // tracked by https://github.com/Azure/azure-rest-api-specs/issues/19424 DiffSuppressFunc: suppress.CaseDifference, + ConflictsWith: []string{ + "capacity_reservation_group_id", + }, }, "secret": windowsSecretSchema(), @@ -541,6 +558,14 @@ func resourceWindowsVirtualMachineCreate(d *pluginsdk.ResourceData, meta interfa } } + if v, ok := d.GetOk("capacity_reservation_group_id"); ok { + params.CapacityReservation = &compute.CapacityReservationProfile{ + CapacityReservationGroup: &compute.SubResource{ + ID: utils.String(v.(string)), + }, + } + } + if v, ok := d.GetOk("custom_data"); ok { params.OsProfile.CustomData = utils.String(v.(string)) } @@ -742,6 +767,12 @@ func resourceWindowsVirtualMachineRead(d *pluginsdk.ResourceData, meta interface } d.Set("availability_set_id", availabilitySetId) + capacityReservationGroupId := "" + if props.CapacityReservation != nil && props.CapacityReservation.CapacityReservationGroup != nil && props.CapacityReservation.CapacityReservationGroup.ID != nil { + capacityReservationGroupId = *props.CapacityReservation.CapacityReservationGroup.ID + } + d.Set("capacity_reservation_group_id", capacityReservationGroupId) + if err := d.Set("boot_diagnostics", flattenBootDiagnostics(props.DiagnosticsProfile)); err != nil { return fmt.Errorf("setting `boot_diagnostics`: %+v", err) } @@ -1037,6 +1068,23 @@ func resourceWindowsVirtualMachineUpdate(d *pluginsdk.ResourceData, meta interfa update.Identity = identity } + if d.HasChange("capacity_reservation_group_id") { + shouldUpdate = true + shouldDeallocate = true + + if v, ok := d.GetOk("capacity_reservation_group_id"); ok { + update.CapacityReservation = &compute.CapacityReservationProfile{ + CapacityReservationGroup: &compute.SubResource{ + ID: utils.String(v.(string)), + }, + } + } else { + update.CapacityReservation = &compute.CapacityReservationProfile{ + CapacityReservationGroup: &compute.SubResource{}, + } + } + } + if d.HasChange("dedicated_host_id") { shouldUpdate = true diff --git a/internal/services/compute/windows_virtual_machine_resource_scaling_test.go b/internal/services/compute/windows_virtual_machine_resource_scaling_test.go index d894a67fa625..b01c3914c9b1 100644 --- a/internal/services/compute/windows_virtual_machine_resource_scaling_test.go +++ b/internal/services/compute/windows_virtual_machine_resource_scaling_test.go @@ -39,6 +39,57 @@ func TestAccWindowsVirtualMachine_scalingAvailabilitySet(t *testing.T) { }) } +func TestAccWindowsVirtualMachine_scalingCapacityReservationGroup(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_windows_virtual_machine", "test") + r := WindowsVirtualMachineResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.scalingCapacityReservationGroup(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("admin_password"), + }) +} + +func TestAccWindowsVirtualMachine_scalingCapacityReservationGroupUpdate(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_windows_virtual_machine", "test") + r := WindowsVirtualMachineResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.scalingCapacityReservationGroupInitial(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("admin_password"), + { + Config: r.scalingCapacityReservationGroup(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("admin_password"), + { + Config: r.scalingCapacityReservationGroupUpdate(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("admin_password"), + { + Config: r.scalingCapacityReservationGroupRemoved(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("admin_password"), + }) +} + func TestAccWindowsVirtualMachine_scalingDedicatedHost(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_windows_virtual_machine", "test") r := WindowsVirtualMachineResource{} @@ -317,6 +368,216 @@ resource "azurerm_windows_virtual_machine" "test" { `, r.template(data), data.RandomInteger) } +func (r WindowsVirtualMachineResource) scalingCapacityReservationGroupInitial(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_windows_virtual_machine" "test" { + name = local.vm_name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + size = "Standard_F2" + admin_username = "adminuser" + admin_password = "P@$$w0rd1234!" + network_interface_ids = [ + azurerm_network_interface.test.id, + ] + + os_disk { + caching = "ReadWrite" + storage_account_type = "Standard_LRS" + } + + source_image_reference { + publisher = "MicrosoftWindowsServer" + offer = "WindowsServer" + sku = "2016-Datacenter" + version = "latest" + } +} +`, r.template(data), data.RandomInteger) +} + +func (r WindowsVirtualMachineResource) scalingCapacityReservationGroup(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_windows_virtual_machine" "test" { + name = local.vm_name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + size = "Standard_F2" + admin_username = "adminuser" + admin_password = "P@$$w0rd1234!" + + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + + network_interface_ids = [ + azurerm_network_interface.test.id, + ] + + os_disk { + caching = "ReadWrite" + storage_account_type = "Standard_LRS" + } + + source_image_reference { + publisher = "MicrosoftWindowsServer" + offer = "WindowsServer" + sku = "2016-Datacenter" + version = "latest" + } + + depends_on = [ + azurerm_capacity_reservation.test, + ] +} +`, r.template(data), data.RandomInteger) +} + +func (r WindowsVirtualMachineResource) scalingCapacityReservationGroupUpdate(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_capacity_reservation_group" "test2" { + name = "acctest-ccrg2-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test2" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test2.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_windows_virtual_machine" "test" { + name = local.vm_name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + size = "Standard_F2" + admin_username = "adminuser" + admin_password = "P@$$w0rd1234!" + + capacity_reservation_group_id = azurerm_capacity_reservation_group.test2.id + + network_interface_ids = [ + azurerm_network_interface.test.id, + ] + + os_disk { + caching = "ReadWrite" + storage_account_type = "Standard_LRS" + } + + source_image_reference { + publisher = "MicrosoftWindowsServer" + offer = "WindowsServer" + sku = "2016-Datacenter" + version = "latest" + } + + depends_on = [ + azurerm_capacity_reservation.test2, + ] +} +`, r.template(data), data.RandomInteger) +} + +func (r WindowsVirtualMachineResource) scalingCapacityReservationGroupRemoved(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test2" { + name = "acctest-ccrg2-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test2" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test2.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_windows_virtual_machine" "test" { + name = local.vm_name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + size = "Standard_F2" + admin_username = "adminuser" + admin_password = "P@$$w0rd1234!" + + network_interface_ids = [ + azurerm_network_interface.test.id, + ] + + os_disk { + caching = "ReadWrite" + storage_account_type = "Standard_LRS" + } + + source_image_reference { + publisher = "MicrosoftWindowsServer" + offer = "WindowsServer" + sku = "2016-Datacenter" + version = "latest" + } +} +`, r.template(data), data.RandomInteger) +} + func (r WindowsVirtualMachineResource) scalingDedicatedHostInitial(data acceptance.TestData) string { return fmt.Sprintf(` %s diff --git a/internal/services/compute/windows_virtual_machine_scale_set_disk_os_resource_test.go b/internal/services/compute/windows_virtual_machine_scale_set_disk_os_resource_test.go index b64f9fea3458..2ddb31d12bd3 100644 --- a/internal/services/compute/windows_virtual_machine_scale_set_disk_os_resource_test.go +++ b/internal/services/compute/windows_virtual_machine_scale_set_disk_os_resource_test.go @@ -72,6 +72,21 @@ func TestAccWindowsVirtualMachineScaleSet_disksOSDiskEphemeral(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_windows_virtual_machine_scale_set", "test") r := WindowsVirtualMachineScaleSetResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.disksOSDiskEphemeralResourceDisk(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("admin_password"), + }) +} + +func TestAccWindowsVirtualMachineScaleSet_disksOSDiskEphemeralResourceDisk(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_windows_virtual_machine_scale_set", "test") + r := WindowsVirtualMachineScaleSetResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ { Config: r.disksOSDiskEphemeral(data), @@ -478,6 +493,50 @@ resource "azurerm_windows_virtual_machine_scale_set" "test" { `, r.template(data)) } +func (r WindowsVirtualMachineScaleSetResource) disksOSDiskEphemeralResourceDisk(data acceptance.TestData) string { + return fmt.Sprintf(` +%s + +resource "azurerm_windows_virtual_machine_scale_set" "test" { + name = local.vm_name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + sku = "Standard_F8s_v2" # has to be this large for ephemeral disks on Windows + instances = 1 + admin_username = "adminuser" + admin_password = "P@ssword1234!" + + source_image_reference { + publisher = "MicrosoftWindowsServer" + offer = "WindowsServer" + sku = "2019-Datacenter" + version = "latest" + } + + os_disk { + storage_account_type = "Standard_LRS" + caching = "ReadOnly" + + diff_disk_settings { + option = "Local" + placement = "ResourceDisk" + } + } + + network_interface { + name = "example" + primary = true + + ip_configuration { + name = "internal" + primary = true + subnet_id = azurerm_subnet.test.id + } + } +} +`, r.template(data)) +} + func (r WindowsVirtualMachineScaleSetResource) disksOSDiskStorageAccountType(data acceptance.TestData, storageAccountType string) string { return fmt.Sprintf(` %s diff --git a/internal/services/compute/windows_virtual_machine_scale_set_resource.go b/internal/services/compute/windows_virtual_machine_scale_set_resource.go index ffdaea49b38d..dd05a1f74162 100644 --- a/internal/services/compute/windows_virtual_machine_scale_set_resource.go +++ b/internal/services/compute/windows_virtual_machine_scale_set_resource.go @@ -5,19 +5,16 @@ import ( "log" "time" + "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - "github.com/hashicorp/go-azure-helpers/resourcemanager/zones" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-provider-azurerm/internal/features" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/features" "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse" computeValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" @@ -194,6 +191,17 @@ func resourceWindowsVirtualMachineScaleSetCreate(d *pluginsdk.ResourceData, meta }, } + if v, ok := d.GetOk("capacity_reservation_group_id"); ok { + if d.Get("single_placement_group").(bool) { + return fmt.Errorf("`single_placement_group` must be set to `false` when `capacity_reservation_group_id` is specified") + } + virtualMachineProfile.CapacityReservation = &compute.CapacityReservationProfile{ + CapacityReservationGroup: &compute.SubResource{ + ID: utils.String(v.(string)), + }, + } + } + hasHealthExtension := false if vmExtensionsRaw, ok := d.GetOk("extension"); ok { virtualMachineProfile.ExtensionProfile, hasHealthExtension, err = expandVirtualMachineScaleSetExtensions(vmExtensionsRaw.(*pluginsdk.Set).List()) @@ -842,6 +850,12 @@ func resourceWindowsVirtualMachineScaleSetRead(d *pluginsdk.ResourceData, meta i return fmt.Errorf("setting `boot_diagnostics`: %+v", err) } + capacityReservationGroupId := "" + if profile.CapacityReservation != nil && profile.CapacityReservation.CapacityReservationGroup != nil && profile.CapacityReservation.CapacityReservationGroup.ID != nil { + capacityReservationGroupId = *profile.CapacityReservation.CapacityReservationGroup.ID + } + d.Set("capacity_reservation_group_id", capacityReservationGroupId) + // defaulted since BillingProfile isn't returned if it's unset maxBidPrice := float64(-1.0) if profile.BillingProfile != nil && profile.BillingProfile.MaxPrice != nil { @@ -1105,6 +1119,16 @@ func resourceWindowsVirtualMachineScaleSetSchema() map[string]*pluginsdk.Schema "boot_diagnostics": bootDiagnosticsSchema(), + "capacity_reservation_group_id": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: computeValidate.CapacityReservationGroupID, + ConflictsWith: []string{ + "proximity_placement_group_id", + }, + }, + "computer_name_prefix": { Type: pluginsdk.TypeString, Optional: true, @@ -1232,6 +1256,9 @@ func resourceWindowsVirtualMachineScaleSetSchema() map[string]*pluginsdk.Schema ValidateFunc: azure.ValidateResourceID, // the Compute API is broken and returns the Resource Group name in UPPERCASE :shrug:, github issue: https://github.com/Azure/azure-rest-api-specs/issues/10016 DiffSuppressFunc: suppress.CaseDifference, + ConflictsWith: []string{ + "capacity_reservation_group_id", + }, }, "rolling_upgrade_policy": VirtualMachineScaleSetRollingUpgradePolicySchema(), diff --git a/internal/services/compute/windows_virtual_machine_scale_set_scaling_resource_test.go b/internal/services/compute/windows_virtual_machine_scale_set_scaling_resource_test.go index ab7c7ec67e25..4af81ff2ff22 100644 --- a/internal/services/compute/windows_virtual_machine_scale_set_scaling_resource_test.go +++ b/internal/services/compute/windows_virtual_machine_scale_set_scaling_resource_test.go @@ -23,6 +23,21 @@ func TestAccWindowsVirtualMachineScaleSet_scalingAutoScale(t *testing.T) { }) } +func TestAccWindowsVirtualMachineScaleSet_scalingCapacityReservationGroupId(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_windows_virtual_machine_scale_set", "test") + r := WindowsVirtualMachineScaleSetResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.scalingCapacityReservationGroupId(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("admin_password"), + }) +} + func TestAccWindowsVirtualMachineScaleSet_scalingInstanceCount(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_windows_virtual_machine_scale_set", "test") r := WindowsVirtualMachineScaleSetResource{} @@ -314,6 +329,68 @@ resource "azurerm_monitor_autoscale_setting" "test" { `, r.template(data)) } +func (r WindowsVirtualMachineScaleSetResource) scalingCapacityReservationGroupId(data acceptance.TestData) string { + return fmt.Sprintf(` +%[1]s + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[2]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + sku { + name = "Standard_F2" + capacity = 1 + } +} + +resource "azurerm_windows_virtual_machine_scale_set" "test" { + name = local.vm_name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + sku = "Standard_F2" + instances = 1 + admin_username = "adminuser" + admin_password = "P@ssword1234!" + + single_placement_group = false + platform_fault_domain_count = 3 + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + + source_image_reference { + publisher = "MicrosoftWindowsServer" + offer = "WindowsServer" + sku = "2019-Datacenter" + version = "latest" + } + + os_disk { + storage_account_type = "Standard_LRS" + caching = "ReadWrite" + } + + network_interface { + name = "example" + primary = true + + ip_configuration { + name = "internal" + primary = true + subnet_id = azurerm_subnet.test.id + } + } + + depends_on = [ + azurerm_capacity_reservation.test, + ] +} +`, r.template(data), data.RandomInteger) +} + func (r WindowsVirtualMachineScaleSetResource) scalingInstanceCount(data acceptance.TestData, instanceCount int) string { return fmt.Sprintf(` %s diff --git a/internal/services/containers/client/client.go b/internal/services/containers/client/client.go index 39101e66f4c7..f9d963845a92 100644 --- a/internal/services/containers/client/client.go +++ b/internal/services/containers/client/client.go @@ -1,19 +1,19 @@ package client import ( - "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance" legacy "github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2019-08-01/containerservice" legacyacr "github.com/Azure/azure-sdk-for-go/services/preview/containerregistry/mgmt/2019-06-01-preview/containerregistry" "github.com/Azure/azure-sdk-for-go/services/preview/containerregistry/mgmt/2021-08-01-preview/containerregistry" "github.com/Azure/azure-sdk-for-go/services/preview/containerservice/mgmt/2022-03-02-preview/containerservice" "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance" "github.com/hashicorp/terraform-provider-azurerm/internal/common" ) type Client struct { AgentPoolsClient *containerservice.AgentPoolsClient ContainerRegistryAgentPoolsClient *containerregistry.AgentPoolsClient - GroupsClient *containerinstance.ContainerGroupsClient + ContainerInstanceClient *containerinstance.ContainerInstanceClient KubernetesClustersClient *containerservice.ManagedClustersClient MaintenanceConfigurationsClient *containerservice.MaintenanceConfigurationsClient RegistriesClient *containerregistry.RegistriesClient @@ -50,8 +50,8 @@ func NewClient(o *common.ClientOptions) *Client { tasksClient := legacyacr.NewTasksClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&tasksClient.Client, o.ResourceManagerAuthorizer) - groupsClient := containerinstance.NewContainerGroupsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) - o.ConfigureClient(&groupsClient.Client, o.ResourceManagerAuthorizer) + containerInstanceClient := containerinstance.NewContainerInstanceClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&containerInstanceClient.Client, o.ResourceManagerAuthorizer) // AKS kubernetesClustersClient := containerservice.NewManagedClustersClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) @@ -73,7 +73,7 @@ func NewClient(o *common.ClientOptions) *Client { AgentPoolsClient: &agentPoolsClient, ContainerRegistryAgentPoolsClient: ®istryAgentPoolsClient, KubernetesClustersClient: &kubernetesClustersClient, - GroupsClient: &groupsClient, + ContainerInstanceClient: &containerInstanceClient, MaintenanceConfigurationsClient: &maintenanceConfigurationsClient, RegistriesClient: ®istriesClient, WebhooksClient: &webhooksClient, diff --git a/internal/services/containers/container_group_data_source.go b/internal/services/containers/container_group_data_source.go index 00cf207bb797..4df21b832c1f 100644 --- a/internal/services/containers/container_group_data_source.go +++ b/internal/services/containers/container_group_data_source.go @@ -4,15 +4,15 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/containers/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceContainerGroup() *pluginsdk.Resource { @@ -44,22 +44,22 @@ func dataSourceContainerGroup() *pluginsdk.Resource { Computed: true, }, - "tags": tags.SchemaDataSource(), + "tags": commonschema.TagsDataSource(), }, } } func dataSourceContainerGroupRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Containers.GroupsClient + client := meta.(*clients.Client).Containers.ContainerInstanceClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewContainerGroupID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := containerinstance.NewContainerGroupID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + resp, err := client.ContainerGroupsGet(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } @@ -67,16 +67,20 @@ func dataSourceContainerGroupRead(d *pluginsdk.ResourceData, meta interface{}) e } d.SetId(id.ID()) - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("location", location.NormalizeNilable(resp.Location)) + d.Set("name", id.ContainerGroupName) + d.Set("resource_group_name", id.ResourceGroupName) - if props := resp.ContainerGroupProperties; props != nil { - if address := props.IPAddress; address != nil { - d.Set("ip_address", address.IP) + if model := resp.Model; model != nil { + d.Set("location", location.NormalizeNilable(model.Location)) + if err := tags.FlattenAndSet(d, model.Tags); err != nil { + return err + } + props := model.Properties + if address := props.IpAddress; address != nil { + d.Set("ip_address", address.Ip) d.Set("fqdn", address.Fqdn) } } - return tags.FlattenAndSet(d, resp.Tags) + return nil } diff --git a/internal/services/containers/container_group_resource.go b/internal/services/containers/container_group_resource.go index b52e43fbd1a2..e97f5dd8b2c6 100644 --- a/internal/services/containers/container_group_resource.go +++ b/internal/services/containers/container_group_resource.go @@ -8,21 +8,22 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" - "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/containers/parse" keyVaultParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate" networkParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/parse" networkValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -36,7 +37,7 @@ func resourceContainerGroup() *pluginsdk.Resource { Delete: resourceContainerGroupDelete, Update: resourceContainerGroupUpdate, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.ContainerGroupID(id) + _, err := containerinstance.ParseContainerGroupID(id) return err }), @@ -55,18 +56,18 @@ func resourceContainerGroup() *pluginsdk.Resource { ValidateFunc: validation.StringIsNotEmpty, }, - "location": azure.SchemaLocation(), + "location": commonschema.Location(), - "resource_group_name": azure.SchemaResourceGroupName(), + "resource_group_name": commonschema.ResourceGroupName(), "ip_address_type": { Type: pluginsdk.TypeString, Optional: true, - Default: string(containerinstance.ContainerGroupIPAddressTypePublic), + Default: string(containerinstance.ContainerGroupIpAddressTypePublic), ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ - string(containerinstance.ContainerGroupIPAddressTypePublic), - string(containerinstance.ContainerGroupIPAddressTypePrivate), + string(containerinstance.ContainerGroupIpAddressTypePublic), + string(containerinstance.ContainerGroupIpAddressTypePrivate), "None", }, false), }, @@ -122,7 +123,7 @@ func resourceContainerGroup() *pluginsdk.Resource { "identity": commonschema.SystemAssignedUserAssignedIdentityOptional(), - "tags": tags.Schema(), + "tags": commonschema.Tags(), "restart_policy": { Type: pluginsdk.TypeString, @@ -607,30 +608,29 @@ func containerVolumeSchema() *pluginsdk.Schema { } func resourceContainerGroupCreate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Containers.GroupsClient + client := meta.(*clients.Client).Containers.ContainerInstanceClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewContainerGroupID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := containerinstance.NewContainerGroupID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, id.ResourceGroup, id.Name) + existing, err := client.ContainerGroupsGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_container_group", id.ID()) } } - location := azure.NormalizeLocation(d.Get("location").(string)) + location := location.Normalize(d.Get("location").(string)) OSType := d.Get("os_type").(string) IPAddressType := d.Get("ip_address_type").(string) - t := d.Get("tags").(map[string]interface{}) - restartPolicy := d.Get("restart_policy").(string) + restartPolicy := containerinstance.ContainerGroupRestartPolicy(d.Get("restart_policy").(string)) diagnosticsRaw := d.Get("diagnostics").([]interface{}) diagnostics := expandContainerGroupDiagnostics(diagnosticsRaw) dnsConfig := d.Get("dns_config").([]interface{}) @@ -652,25 +652,25 @@ func resourceContainerGroupCreate(d *pluginsdk.ResourceData, meta interface{}) e } containerGroup := containerinstance.ContainerGroup{ - Name: utils.String(id.Name), + Name: pointer.FromString(id.ContainerGroupName), Location: &location, - Tags: tags.Expand(t), - ContainerGroupProperties: &containerinstance.ContainerGroupProperties{ + Tags: tags.Expand(d.Get("tags").(map[string]interface{})), + Properties: containerinstance.ContainerGroupProperties{ InitContainers: initContainers, Containers: containers, Diagnostics: diagnostics, - RestartPolicy: containerinstance.ContainerGroupRestartPolicy(restartPolicy), + RestartPolicy: &restartPolicy, OsType: containerinstance.OperatingSystemTypes(OSType), Volumes: &containerGroupVolumes, ImageRegistryCredentials: expandContainerImageRegistryCredentials(d), - DNSConfig: expandContainerGroupDnsConfig(dnsConfig), + DnsConfig: expandContainerGroupDnsConfig(dnsConfig), }, } // Container Groups with OS Type Windows do not support managed identities but the API also does not accept Identity Type: None // https://github.com/Azure/azure-rest-api-specs/issues/18122 if OSType != string(containerinstance.OperatingSystemTypesWindows) { - expandedIdentity, err := expandContainerGroupIdentity(d.Get("identity").([]interface{})) + expandedIdentity, err := identity.ExpandSystemAndUserAssignedMap(d.Get("identity").([]interface{})) if err != nil { return fmt.Errorf("expanding `identity`: %+v", err) } @@ -678,13 +678,13 @@ func resourceContainerGroupCreate(d *pluginsdk.ResourceData, meta interface{}) e } if IPAddressType != "None" { - containerGroup.ContainerGroupProperties.IPAddress = &containerinstance.IPAddress{ + containerGroup.Properties.IpAddress = &containerinstance.IpAddress{ Ports: containerGroupPorts, - Type: containerinstance.ContainerGroupIPAddressType(IPAddressType), + Type: containerinstance.ContainerGroupIpAddressType(IPAddressType), } if dnsNameLabel := d.Get("dns_name_label").(string); dnsNameLabel != "" { - containerGroup.ContainerGroupProperties.IPAddress.DNSNameLabel = &dnsNameLabel + containerGroup.Properties.IpAddress.DnsNameLabel = &dnsNameLabel } } @@ -701,8 +701,8 @@ func resourceContainerGroupCreate(d *pluginsdk.ResourceData, meta interface{}) e if strings.ToLower(OSType) != "linux" { return fmt.Errorf("Currently only Linux containers can be deployed to virtual networks") } - containerGroup.ContainerGroupProperties.NetworkProfile = &containerinstance.ContainerGroupNetworkProfile{ - ID: &networkProfileIDNorm, + containerGroup.Properties.NetworkProfile = &containerinstance.ContainerGroupNetworkProfile{ + Id: networkProfileIDNorm, } } @@ -711,20 +711,15 @@ func resourceContainerGroupCreate(d *pluginsdk.ResourceData, meta interface{}) e if err != nil { return fmt.Errorf("parsing Key Vault Key ID: %+v", err) } - containerGroup.ContainerGroupProperties.EncryptionProperties = &containerinstance.EncryptionProperties{ - VaultBaseURL: utils.String(keyId.KeyVaultBaseUrl), - KeyName: utils.String(keyId.Name), - KeyVersion: utils.String(keyId.Version), + containerGroup.Properties.EncryptionProperties = &containerinstance.EncryptionProperties{ + VaultBaseUrl: keyId.KeyVaultBaseUrl, + KeyName: keyId.Name, + KeyVersion: keyId.Version, } } - future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.Name, containerGroup) - if err != nil { - return fmt.Errorf("creating/updating %s: %+v", id, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation/update of %s: %+v", id, err) + if err := client.ContainerGroupsCreateOrUpdateThenPoll(ctx, id, containerGroup); err != nil { + return fmt.Errorf("creating %s: %+v", id, err) } d.SetId(id.ID()) @@ -732,11 +727,11 @@ func resourceContainerGroupCreate(d *pluginsdk.ResourceData, meta interface{}) e } func resourceContainerGroupUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Containers.GroupsClient + client := meta.(*clients.Client).Containers.ContainerInstanceClient ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.ContainerGroupID(d.Id()) + id, err := containerinstance.ParseContainerGroupID(d.Id()) if err != nil { return err } @@ -747,7 +742,7 @@ func resourceContainerGroupUpdate(d *pluginsdk.ResourceData, meta interface{}) e Tags: tags.Expand(t), } - if _, err := client.Update(ctx, id.ResourceGroup, id.Name, parameters); err != nil { + if _, err := client.ContainerGroupsUpdate(ctx, *id, parameters); err != nil { return fmt.Errorf("updating %s: %+v", *id, err) } @@ -755,18 +750,18 @@ func resourceContainerGroupUpdate(d *pluginsdk.ResourceData, meta interface{}) e } func resourceContainerGroupRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Containers.GroupsClient + client := meta.(*clients.Client).Containers.ContainerInstanceClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.ContainerGroupID(d.Id()) + id, err := containerinstance.ParseContainerGroupID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + resp, err := client.ContainerGroupsGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[DEBUG] %s was not found - removing from state!", *id) d.SetId("") return nil @@ -774,26 +769,29 @@ func resourceContainerGroupRead(d *pluginsdk.ResourceData, meta interface{}) err return err } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } + d.Set("name", id.ContainerGroupName) + d.Set("resource_group_name", id.ResourceGroupName) - identity, err := flattenContainerGroupIdentity(resp.Identity) - if err != nil { - return fmt.Errorf("flattening `identity`: %+v", err) - } - if err := d.Set("identity", identity); err != nil { - return fmt.Errorf("setting `identity`: %+v", err) - } + if model := resp.Model; model != nil { + d.Set("location", location.NormalizeNilable(model.Location)) + identity, err := identity.FlattenSystemAndUserAssignedMap(model.Identity) + if err != nil { + return fmt.Errorf("flattening `identity`: %+v", err) + } + if err := d.Set("identity", identity); err != nil { + return fmt.Errorf("setting `identity`: %+v", err) + } - if props := resp.ContainerGroupProperties; props != nil { - containerConfigs := flattenContainerGroupContainers(d, resp.Containers, props.Volumes) + if err := tags.FlattenAndSet(d, model.Tags); err != nil { + return err + } + + props := model.Properties + containerConfigs := flattenContainerGroupContainers(d, &props.Containers, props.Volumes) if err := d.Set("container", containerConfigs); err != nil { return fmt.Errorf("setting `container`: %+v", err) } - initContainerConfigs := flattenContainerGroupInitContainers(d, resp.InitContainers, props.Volumes) + initContainerConfigs := flattenContainerGroupInitContainers(d, props.InitContainers, props.Volumes) if err := d.Set("init_container", initContainerConfigs); err != nil { return fmt.Errorf("setting `init_container`: %+v", err) } @@ -802,21 +800,26 @@ func resourceContainerGroupRead(d *pluginsdk.ResourceData, meta interface{}) err return fmt.Errorf("setting `image_registry_credential`: %+v", err) } - if address := props.IPAddress; address != nil { + if address := props.IpAddress; address != nil { d.Set("ip_address_type", address.Type) - d.Set("ip_address", address.IP) - exposedPorts := make([]interface{}, len(*resp.ContainerGroupProperties.IPAddress.Ports)) - for i := range *resp.ContainerGroupProperties.IPAddress.Ports { - exposedPorts[i] = (*resp.ContainerGroupProperties.IPAddress.Ports)[i] + d.Set("ip_address", address.Ip) + exposedPorts := make([]interface{}, len(address.Ports)) + for i := range address.Ports { + exposedPorts[i] = (address.Ports)[i] } d.Set("exposed_port", flattenPorts(exposedPorts)) - d.Set("dns_name_label", address.DNSNameLabel) + d.Set("dns_name_label", address.DnsNameLabel) d.Set("fqdn", address.Fqdn) } - d.Set("restart_policy", string(props.RestartPolicy)) + restartPolicy := "" + if props.RestartPolicy != nil { + restartPolicy = string(*props.RestartPolicy) + } + d.Set("restart_policy", restartPolicy) + d.Set("os_type", string(props.OsType)) - d.Set("dns_config", flattenContainerGroupDnsConfig(resp.DNSConfig)) + d.Set("dns_config", flattenContainerGroupDnsConfig(props.DnsConfig)) if err := d.Set("diagnostics", flattenContainerGroupDiagnostics(d, props.Diagnostics)); err != nil { return fmt.Errorf("setting `diagnostics`: %+v", err) @@ -824,19 +827,17 @@ func resourceContainerGroupRead(d *pluginsdk.ResourceData, meta interface{}) err if kvProps := props.EncryptionProperties; kvProps != nil { var keyVaultUri, keyName, keyVersion string - if kvProps.VaultBaseURL != nil && *kvProps.VaultBaseURL != "" { - keyVaultUri = *kvProps.VaultBaseURL + if kvProps.VaultBaseUrl != "" { + keyVaultUri = kvProps.VaultBaseUrl } else { return fmt.Errorf("empty value returned for Key Vault URI") } - if kvProps.KeyName != nil && *kvProps.KeyName != "" { - keyName = *kvProps.KeyName + if kvProps.KeyName != "" { + keyName = kvProps.KeyName } else { return fmt.Errorf("empty value returned for Key Vault Key Name") } - if kvProps.KeyVersion != nil { - keyVersion = *kvProps.KeyVersion - } + keyVersion = kvProps.KeyVersion keyId, err := keyVaultParse.NewNestedItemID(keyVaultUri, "keys", keyName, keyVersion) if err != nil { return err @@ -845,7 +846,7 @@ func resourceContainerGroupRead(d *pluginsdk.ResourceData, meta interface{}) err } } - return tags.FlattenAndSet(d, resp.Tags) + return nil } func flattenPorts(ports []interface{}) *pluginsdk.Set { @@ -855,15 +856,19 @@ func flattenPorts(ports []interface{}) *pluginsdk.Set { port := make(map[string]interface{}) switch t := p.(type) { case containerinstance.Port: - if v := t.Port; v != nil { - port["port"] = int(*v) + port["port"] = int(t.Port) + proto := "" + if t.Protocol != nil { + proto = string(*t.Protocol) } - port["protocol"] = string(t.Protocol) + port["protocol"] = proto case containerinstance.ContainerPort: - if v := t.Port; v != nil { - port["port"] = int(*v) + port["port"] = int(t.Port) + proto := "" + if t.Protocol != nil { + proto = string(*t.Protocol) } - port["protocol"] = string(t.Protocol) + port["protocol"] = proto } flatPorts = append(flatPorts, port) } @@ -873,35 +878,35 @@ func flattenPorts(ports []interface{}) *pluginsdk.Set { } func resourceContainerGroupDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Containers.GroupsClient + client := meta.(*clients.Client).Containers.ContainerInstanceClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.ContainerGroupID(d.Id()) + id, err := containerinstance.ParseContainerGroupID(d.Id()) if err != nil { return err } networkProfileId := "" - existing, err := client.Get(ctx, id.ResourceGroup, id.Name) + existing, err := client.ContainerGroupsGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse) { // already deleted return nil } - return fmt.Errorf("retrieving Container Group %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("retrieving %q: %+v", id, err) } - if props := existing.ContainerGroupProperties; props != nil { + if model := existing.Model; model != nil { + props := model.Properties if profile := props.NetworkProfile; profile != nil { - if profile.ID != nil { - id, err := networkParse.NetworkProfileID(*profile.ID) - if err != nil { - return err - } - networkProfileId = id.ID() + id, err := networkParse.NetworkProfileID(profile.Id) + if err != nil { + return err } + networkProfileId = id.ID() + // Avoid parallel deletion if "network_profile_id" is given. (not sure whether this is necessary) // See: https://github.com/hashicorp/terraform-provider-azurerm/issues/15025 locks.ByID(networkProfileId) @@ -909,12 +914,8 @@ func resourceContainerGroupDelete(d *pluginsdk.ResourceData, meta interface{}) e } } - future, err := client.Delete(ctx, id.ResourceGroup, id.Name) - if err != nil { - return fmt.Errorf("deleting Container Group %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) - } - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for deletion of Container Group %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + if err := client.ContainerGroupsDeleteThenPoll(ctx, *id); err != nil { + return fmt.Errorf("deleting %q: %+v", id, err) } if networkProfileId != "" { @@ -925,11 +926,11 @@ func resourceContainerGroupDelete(d *pluginsdk.ResourceData, meta interface{}) e } // TODO: remove when https://github.com/Azure/azure-sdk-for-go/issues/5082 has been fixed - log.Printf("[DEBUG] Waiting for Container Group %q (Resource Group %q) to be finish deleting", id.Name, id.ResourceGroup) + log.Printf("[DEBUG] Waiting for %q to be finish deleting", id) stateConf := &pluginsdk.StateChangeConf{ Pending: []string{"Attached"}, Target: []string{"Detached"}, - Refresh: containerGroupEnsureDetachedFromNetworkProfileRefreshFunc(ctx, networkProfileClient, networkProfileId.ResourceGroup, networkProfileId.Name, id.ResourceGroup, id.Name), + Refresh: containerGroupEnsureDetachedFromNetworkProfileRefreshFunc(ctx, networkProfileClient, networkProfileId.ResourceGroup, networkProfileId.Name, id.ResourceGroupName, id.ContainerGroupName), MinTimeout: 15 * time.Second, ContinuousTargetOccurence: 5, Timeout: d.Timeout(pluginsdk.TimeoutDelete), @@ -937,7 +938,7 @@ func resourceContainerGroupDelete(d *pluginsdk.ResourceData, meta interface{}) e } if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for Container Group %q (Resource Group %q) to finish deleting: %s", id.Name, id.ResourceGroup, err) + return fmt.Errorf("waiting for %q to finish deleting: %s", id, err) } } @@ -963,16 +964,16 @@ func containerGroupEnsureDetachedFromNetworkProfileRefreshFunc(ctx context.Conte continue } - parsedId, err := parse.ContainerGroupID(*nicProps.Container.ID) + parsedId, err := containerinstance.ParseContainerGroupID(*nicProps.Container.ID) if err != nil { return nil, "", err } - if parsedId.ResourceGroup != containerResourceGroupName { + if parsedId.ResourceGroupName != containerResourceGroupName { continue } - if parsedId.Name == "" || parsedId.Name != containerName { + if parsedId.ContainerGroupName == "" || parsedId.ContainerGroupName != containerName { continue } @@ -1001,9 +1002,9 @@ func expandContainerGroupInitContainers(d *pluginsdk.ResourceData, addedEmptyDir image := data["image"].(string) container := containerinstance.InitContainerDefinition{ - Name: utils.String(name), - InitContainerPropertiesDefinition: &containerinstance.InitContainerPropertiesDefinition{ - Image: utils.String(image), + Name: name, + Properties: containerinstance.InitContainerPropertiesDefinition{ + Image: pointer.FromString(image), }, } @@ -1025,7 +1026,7 @@ func expandContainerGroupInitContainers(d *pluginsdk.ResourceData, addedEmptyDir *envVars = append(*envVars, *secEnvVars...) // Set both secure and non secure environment variables - container.EnvironmentVariables = envVars + container.Properties.EnvironmentVariables = envVars if v, ok := data["commands"]; ok { c := v.([]interface{}) @@ -1034,7 +1035,7 @@ func expandContainerGroupInitContainers(d *pluginsdk.ResourceData, addedEmptyDir command = append(command, v.(string)) } - container.Command = &command + container.Properties.Command = &command } if v, ok := data["volume"]; ok { @@ -1042,7 +1043,7 @@ func expandContainerGroupInitContainers(d *pluginsdk.ResourceData, addedEmptyDir if err != nil { return nil, nil, err } - container.VolumeMounts = volumeMounts + container.Properties.VolumeMounts = volumeMounts expandedContainerGroupVolumes, err := expandContainerVolume(v, addedEmptyDirs, containerGroupVolumes) if err != nil { @@ -1057,7 +1058,7 @@ func expandContainerGroupInitContainers(d *pluginsdk.ResourceData, addedEmptyDir return &containers, containerGroupVolumes, nil } -func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs map[string]bool) (*[]containerinstance.Container, *[]containerinstance.Port, []containerinstance.Volume, error) { +func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs map[string]bool) ([]containerinstance.Container, []containerinstance.Port, []containerinstance.Volume, error) { containersConfig := d.Get("container").([]interface{}) containers := make([]containerinstance.Container, 0) containerInstancePorts := make([]containerinstance.Port, 0) @@ -1073,13 +1074,13 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma memory := data["memory"].(float64) container := containerinstance.Container{ - Name: utils.String(name), - ContainerProperties: &containerinstance.ContainerProperties{ - Image: utils.String(image), - Resources: &containerinstance.ResourceRequirements{ - Requests: &containerinstance.ResourceRequests{ - MemoryInGB: utils.Float(memory), - CPU: utils.Float(cpu), + Name: name, + Properties: containerinstance.ContainerProperties{ + Image: image, + Resources: containerinstance.ResourceRequirements{ + Requests: containerinstance.ResourceRequests{ + MemoryInGB: memory, + Cpu: cpu, }, }, }, @@ -1096,10 +1097,10 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma gpuSku := containerinstance.GpuSku(v["sku"].(string)) gpus := containerinstance.GpuResource{ - Count: &gpuCount, + Count: int64(gpuCount), Sku: gpuSku, } - container.Resources.Requests.Gpu = &gpus + container.Properties.Resources.Requests.Gpu = &gpus } } @@ -1110,7 +1111,7 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma if !(cpuLimit == 0.0 && memLimit == 0.0 && len(gpuLimit) == 0) { limits := &containerinstance.ResourceLimits{} if cpuLimit != 0.0 { - limits.CPU = &cpuLimit + limits.Cpu = &cpuLimit } if memLimit != 0.0 { limits.MemoryInGB = &memLimit @@ -1118,14 +1119,14 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma if len(gpuLimit) == 1 && gpuLimit[0] != nil { v := gpuLimit[0].(map[string]interface{}) limits.Gpu = &containerinstance.GpuResource{} - if v := int32(v["count"].(int)); v != 0 { - limits.Gpu.Count = &v + if v := int64(v["count"].(int)); v != 0 { + limits.Gpu.Count = v } if v := containerinstance.GpuSku(v["sku"].(string)); v != "" { limits.Gpu.Sku = v } } - container.Resources.Limits = limits + container.Properties.Resources.Limits = limits } if v, ok := data["ports"].(*pluginsdk.Set); ok && len(v.List()) > 0 { @@ -1133,19 +1134,21 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma for _, v := range v.List() { portObj := v.(map[string]interface{}) - port := int32(portObj["port"].(int)) + port := int64(portObj["port"].(int)) proto := portObj["protocol"].(string) + containerProtocol := containerinstance.ContainerNetworkProtocol(proto) ports = append(ports, containerinstance.ContainerPort{ - Port: &port, - Protocol: containerinstance.ContainerNetworkProtocol(proto), + Port: port, + Protocol: &containerProtocol, }) + groupProtocol := containerinstance.ContainerGroupNetworkProtocol(proto) containerInstancePorts = append(containerInstancePorts, containerinstance.Port{ - Port: &port, - Protocol: containerinstance.ContainerGroupNetworkProtocol(proto), + Port: port, + Protocol: &groupProtocol, }) } - container.Ports = &ports + container.Properties.Ports = &ports } // Set both sensitive and non-secure environment variables @@ -1166,7 +1169,7 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma *envVars = append(*envVars, *secEnvVars...) // Set both secure and non secure environment variables - container.EnvironmentVariables = envVars + container.Properties.EnvironmentVariables = envVars if v, ok := data["commands"]; ok { c := v.([]interface{}) @@ -1175,7 +1178,7 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma command = append(command, v.(string)) } - container.Command = &command + container.Properties.Command = &command } if v, ok := data["volume"]; ok { @@ -1183,7 +1186,7 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma if err != nil { return nil, nil, nil, err } - container.VolumeMounts = volumeMounts + container.Properties.VolumeMounts = volumeMounts expandedContainerGroupVolumes, err := expandContainerVolume(v, addedEmptyDirs, containerGroupVolumes) if err != nil { @@ -1193,11 +1196,11 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma } if v, ok := data["liveness_probe"]; ok { - container.ContainerProperties.LivenessProbe = expandContainerProbe(v) + container.Properties.LivenessProbe = expandContainerProbe(v) } if v, ok := data["readiness_probe"]; ok { - container.ContainerProperties.ReadinessProbe = expandContainerProbe(v) + container.Properties.ReadinessProbe = expandContainerProbe(v) } containers = append(containers, container) @@ -1206,20 +1209,25 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma // Determine ports to be exposed on the group level, based on exposed_ports // and on what ports have been exposed on individual containers. if v, ok := d.Get("exposed_port").(*pluginsdk.Set); ok && len(v.List()) > 0 { - cgpMap := make(map[int32]map[containerinstance.ContainerGroupNetworkProtocol]bool) + cgpMap := make(map[int64]map[containerinstance.ContainerGroupNetworkProtocol]bool) for _, p := range containerInstancePorts { - if val, ok := cgpMap[*p.Port]; ok { - val[p.Protocol] = true - cgpMap[*p.Port] = val + if p.Protocol == nil { + continue + } + protocol := *p.Protocol + + if val, ok := cgpMap[p.Port]; ok { + val[protocol] = true + cgpMap[p.Port] = val } else { - protoMap := map[containerinstance.ContainerGroupNetworkProtocol]bool{p.Protocol: true} - cgpMap[*p.Port] = protoMap + protoMap := map[containerinstance.ContainerGroupNetworkProtocol]bool{protocol: true} + cgpMap[p.Port] = protoMap } } for _, p := range v.List() { portConfig := p.(map[string]interface{}) - port := int32(portConfig["port"].(int)) + port := int64(portConfig["port"].(int)) proto := portConfig["protocol"].(string) if !cgpMap[port][containerinstance.ContainerGroupNetworkProtocol(proto)] { return nil, nil, nil, fmt.Errorf("Port %d/%s is not exposed on any individual container in the container group.\n"+ @@ -1227,16 +1235,17 @@ func expandContainerGroupContainers(d *pluginsdk.ResourceData, addedEmptyDirs ma "and protocol. Any ports exposed on the container group must also be exposed on an individual container.", port, proto, port, proto) } + portProtocol := containerinstance.ContainerGroupNetworkProtocol(proto) containerGroupPorts = append(containerGroupPorts, containerinstance.Port{ - Port: &port, - Protocol: containerinstance.ContainerGroupNetworkProtocol(proto), + Port: port, + Protocol: &portProtocol, }) } } else { containerGroupPorts = containerInstancePorts // remove in 3.0 of the provider } - return &containers, &containerGroupPorts, containerGroupVolumes, nil + return containers, containerGroupPorts, containerGroupVolumes, nil } func expandContainerVolume(v interface{}, addedEmptyDirs map[string]bool, containerGroupVolumes []containerinstance.Volume) ([]containerinstance.Volume, error) { @@ -1247,12 +1256,12 @@ func expandContainerVolume(v interface{}, addedEmptyDirs map[string]bool, contai if containerVolumes != nil { for _, cgVol := range *containerVolumes { if cgVol.EmptyDir != nil { - if addedEmptyDirs[*cgVol.Name] { + if addedEmptyDirs[cgVol.Name] { // empty_dir-volumes are allowed to overlap across containers, in fact that is their primary purpose, // but the containerGroup must not declare same name of such volumes twice. continue } - addedEmptyDirs[*cgVol.Name] = true + addedEmptyDirs[cgVol.Name] = true } containerGroupVolumes = append(containerGroupVolumes, cgVol) } @@ -1267,8 +1276,8 @@ func expandContainerEnvironmentVariables(input interface{}, secure bool) *[]cont if secure { for k, v := range envVars { ev := containerinstance.EnvironmentVariable{ - Name: utils.String(k), - SecureValue: utils.String(v.(string)), + Name: k, + SecureValue: pointer.FromString(v.(string)), } output = append(output, ev) @@ -1276,8 +1285,8 @@ func expandContainerEnvironmentVariables(input interface{}, secure bool) *[]cont } else { for k, v := range envVars { ev := containerinstance.EnvironmentVariable{ - Name: utils.String(k), - Value: utils.String(v.(string)), + Name: k, + Value: pointer.FromString(v.(string)), } output = append(output, ev) @@ -1286,27 +1295,6 @@ func expandContainerEnvironmentVariables(input interface{}, secure bool) *[]cont return &output } -func expandContainerGroupIdentity(input []interface{}) (*containerinstance.ContainerGroupIdentity, error) { - expanded, err := identity.ExpandSystemAndUserAssignedMap(input) - if err != nil { - return nil, err - } - - out := containerinstance.ContainerGroupIdentity{ - Type: containerinstance.ResourceIdentityType(string(expanded.Type)), - } - if expanded.Type == identity.TypeUserAssigned || expanded.Type == identity.TypeSystemAssignedUserAssigned { - out.UserAssignedIdentities = make(map[string]*containerinstance.ContainerGroupIdentityUserAssignedIdentitiesValue) - for k := range expanded.IdentityIds { - out.UserAssignedIdentities[k] = &containerinstance.ContainerGroupIdentityUserAssignedIdentitiesValue{ - // intentionally empty - } - } - } - - return &out, nil -} - func expandContainerImageRegistryCredentials(d *pluginsdk.ResourceData) *[]containerinstance.ImageRegistryCredential { credsRaw := d.Get("image_registry_credential").([]interface{}) if len(credsRaw) == 0 { @@ -1319,9 +1307,9 @@ func expandContainerImageRegistryCredentials(d *pluginsdk.ResourceData) *[]conta credConfig := c.(map[string]interface{}) output = append(output, containerinstance.ImageRegistryCredential{ - Server: utils.String(credConfig["server"].(string)), - Password: utils.String(credConfig["password"].(string)), - Username: utils.String(credConfig["username"].(string)), + Server: credConfig["server"].(string), + Password: pointer.FromString(credConfig["password"].(string)), + Username: credConfig["username"].(string), }) } @@ -1350,15 +1338,15 @@ func expandSingleContainerVolume(input interface{}) (*[]containerinstance.Volume storageAccountKey := volumeConfig["storage_account_key"].(string) vm := containerinstance.VolumeMount{ - Name: utils.String(name), - MountPath: utils.String(mountPath), - ReadOnly: utils.Bool(readOnly), + Name: name, + MountPath: mountPath, + ReadOnly: pointer.FromBool(readOnly), } volumeMounts = append(volumeMounts, vm) cv := containerinstance.Volume{ - Name: utils.String(name), + Name: name, } secret := expandSecrets(volumeConfig["secret"].(map[string]interface{})) @@ -1370,7 +1358,8 @@ func expandSingleContainerVolume(input interface{}) (*[]containerinstance.Volume if shareName != "" || storageAccountName != "" || storageAccountKey != "" || secret != nil || gitRepoVolume != nil { return nil, nil, fmt.Errorf("only one of `empty_dir` volume, `git_repo` volume, `secret` volume or storage account volume (`share_name`, `storage_account_name`, and `storage_account_key`) can be specified") } - cv.EmptyDir = map[string]string{} + var m interface{} = map[string]string{} + cv.EmptyDir = &m case gitRepoVolume != nil: if shareName != "" || storageAccountName != "" || storageAccountKey != "" || secret != nil { return nil, nil, fmt.Errorf("only one of `empty_dir` volume, `git_repo` volume, `secret` volume or storage account volume (`share_name`, `storage_account_name`, and `storage_account_key`) can be specified") @@ -1380,7 +1369,7 @@ func expandSingleContainerVolume(input interface{}) (*[]containerinstance.Volume if shareName != "" || storageAccountName != "" || storageAccountKey != "" { return nil, nil, fmt.Errorf("only one of `empty_dir` volume, `git_repo` volume, `secret` volume or storage account volume (`share_name`, `storage_account_name`, and `storage_account_key`) can be specified") } - cv.Secret = secret + cv.Secret = &secret default: if shareName == "" && storageAccountName == "" && storageAccountKey == "" { return nil, nil, fmt.Errorf("only one of `empty_dir` volume, `git_repo` volume, `secret` volume or storage account volume (`share_name`, `storage_account_name`, and `storage_account_key`) can be specified") @@ -1388,10 +1377,10 @@ func expandSingleContainerVolume(input interface{}) (*[]containerinstance.Volume return nil, nil, fmt.Errorf("when using a storage account volume, all of `share_name`, `storage_account_name`, `storage_account_key` must be specified") } cv.AzureFile = &containerinstance.AzureFileVolume{ - ShareName: utils.String(shareName), - ReadOnly: utils.Bool(readOnly), - StorageAccountName: utils.String(storageAccountName), - StorageAccountKey: utils.String(storageAccountKey), + ShareName: shareName, + ReadOnly: pointer.FromBool(readOnly), + StorageAccountName: storageAccountName, + StorageAccountKey: pointer.FromString(storageAccountKey), } } @@ -1407,25 +1396,25 @@ func expandGitRepoVolume(input []interface{}) *containerinstance.GitRepoVolume { } v := input[0].(map[string]interface{}) gitRepoVolume := &containerinstance.GitRepoVolume{ - Repository: utils.String(v["url"].(string)), + Repository: v["url"].(string), } if directory := v["directory"].(string); directory != "" { - gitRepoVolume.Directory = utils.String(directory) + gitRepoVolume.Directory = pointer.FromString(directory) } if revision := v["revision"].(string); revision != "" { - gitRepoVolume.Revision = utils.String(revision) + gitRepoVolume.Revision = pointer.FromString(revision) } return gitRepoVolume } -func expandSecrets(secretsMap map[string]interface{}) map[string]*string { +func expandSecrets(secretsMap map[string]interface{}) map[string]string { if len(secretsMap) == 0 { return nil } - output := make(map[string]*string, len(secretsMap)) + output := make(map[string]string, len(secretsMap)) for name, value := range secretsMap { - output[name] = utils.String(value.(string)) + output[name] = value.(string) } return output @@ -1446,23 +1435,23 @@ func expandContainerProbe(input interface{}) *containerinstance.ContainerProbe { probeConfig := p.(map[string]interface{}) if v := probeConfig["initial_delay_seconds"].(int); v > 0 { - probe.InitialDelaySeconds = utils.Int32(int32(v)) + probe.InitialDelaySeconds = pointer.FromInt64(int64(v)) } if v := probeConfig["period_seconds"].(int); v > 0 { - probe.PeriodSeconds = utils.Int32(int32(v)) + probe.PeriodSeconds = pointer.FromInt64(int64(v)) } if v := probeConfig["failure_threshold"].(int); v > 0 { - probe.FailureThreshold = utils.Int32(int32(v)) + probe.FailureThreshold = pointer.FromInt64(int64(v)) } if v := probeConfig["success_threshold"].(int); v > 0 { - probe.SuccessThreshold = utils.Int32(int32(v)) + probe.SuccessThreshold = pointer.FromInt64(int64(v)) } if v := probeConfig["timeout_seconds"].(int); v > 0 { - probe.TimeoutSeconds = utils.Int32(int32(v)) + probe.TimeoutSeconds = pointer.FromInt64(int64(v)) } commands := probeConfig["exec"].([]interface{}) @@ -1485,10 +1474,12 @@ func expandContainerProbe(input interface{}) *containerinstance.ContainerProbe { port := x["port"].(int) scheme := x["scheme"].(string) - probe.HTTPGet = &containerinstance.ContainerHTTPGet{ - Path: utils.String(path), - Port: utils.Int32(int32(port)), - Scheme: containerinstance.Scheme(scheme), + httpGetScheme := containerinstance.Scheme(scheme) + probe.HttpGet = &containerinstance.ContainerHttpGet{ + Path: pointer.FromString(path), + Port: int64(port), + Scheme: &httpGetScheme, + HttpHeaders: expandContainerProbeHttpHeaders(x["http_headers"].(map[string]interface{})), } } } @@ -1496,29 +1487,40 @@ func expandContainerProbe(input interface{}) *containerinstance.ContainerProbe { return &probe } -func flattenContainerGroupIdentity(input *containerinstance.ContainerGroupIdentity) (*[]interface{}, error) { - var transform *identity.SystemAndUserAssignedMap +func expandContainerProbeHttpHeaders(input map[string]interface{}) *[]containerinstance.HttpHeader { + if len(input) == 0 { + return nil + } - if input != nil { - transform = &identity.SystemAndUserAssignedMap{ - Type: identity.Type(string(input.Type)), - IdentityIds: make(map[string]identity.UserAssignedIdentityDetails), - } - if input.PrincipalID != nil { - transform.PrincipalId = *input.PrincipalID + headers := []containerinstance.HttpHeader{} + for k, v := range input { + header := containerinstance.HttpHeader{ + Name: pointer.FromString(k), + Value: pointer.FromString(v.(string)), } - if input.TenantID != nil { - transform.TenantId = *input.TenantID + headers = append(headers, header) + } + return &headers +} + +func flattenContainerProbeHttpHeaders(input *[]containerinstance.HttpHeader) map[string]interface{} { + if input == nil { + return nil + } + + output := map[string]interface{}{} + for _, header := range *input { + name := "" + if header.Name != nil { + name = *header.Name } - for k, v := range input.UserAssignedIdentities { - transform.IdentityIds[k] = identity.UserAssignedIdentityDetails{ - ClientId: v.ClientID, - PrincipalId: v.PrincipalID, - } + value := "" + if header.Value != nil { + value = *header.Value } + output[name] = value } - - return identity.FlattenSystemAndUserAssignedMap(transform) + return output } func flattenContainerImageRegistryCredentials(d *pluginsdk.ResourceData, input *[]containerinstance.ImageRegistryCredential) []interface{} { @@ -1530,17 +1532,13 @@ func flattenContainerImageRegistryCredentials(d *pluginsdk.ResourceData, input * output := make([]interface{}, 0) for i, cred := range *input { credConfig := make(map[string]interface{}) - if cred.Server != nil { - credConfig["server"] = *cred.Server - } - if cred.Username != nil { - credConfig["username"] = *cred.Username - } + credConfig["server"] = cred.Server + credConfig["username"] = cred.Username if len(configsOld) > i { data := configsOld[i].(map[string]interface{}) oldServer := data["server"].(string) - if cred.Server != nil && *cred.Server == oldServer { + if cred.Server == oldServer { if v, ok := d.GetOk(fmt.Sprintf("image_registry_credential.%d.password", i)); ok { credConfig["password"] = v.(string) } @@ -1565,8 +1563,7 @@ func flattenContainerGroupInitContainers(d *pluginsdk.ResourceData, initContaine containerCfg := make([]interface{}, 0, len(*initContainers)) for _, container := range *initContainers { - // TODO fix this crash point - name := *container.Name + name := container.Name // get index from name index := nameIndexMap[name] @@ -1574,26 +1571,26 @@ func flattenContainerGroupInitContainers(d *pluginsdk.ResourceData, initContaine containerConfig := make(map[string]interface{}) containerConfig["name"] = name - if v := container.Image; v != nil { + if v := container.Properties.Image; v != nil { containerConfig["image"] = *v } - if container.EnvironmentVariables != nil { - if len(*container.EnvironmentVariables) > 0 { - containerConfig["environment_variables"] = flattenContainerEnvironmentVariables(container.EnvironmentVariables, false, d, index) - containerConfig["secure_environment_variables"] = flattenContainerEnvironmentVariables(container.EnvironmentVariables, true, d, index) + if container.Properties.EnvironmentVariables != nil { + if len(*container.Properties.EnvironmentVariables) > 0 { + containerConfig["environment_variables"] = flattenContainerEnvironmentVariables(container.Properties.EnvironmentVariables, false, d, index) + containerConfig["secure_environment_variables"] = flattenContainerEnvironmentVariables(container.Properties.EnvironmentVariables, true, d, index) } } commands := make([]string, 0) - if command := container.Command; command != nil { + if command := container.Properties.Command; command != nil { commands = *command } containerConfig["commands"] = commands - if containerGroupVolumes != nil && container.VolumeMounts != nil { + if containerGroupVolumes != nil && container.Properties.VolumeMounts != nil { containersConfigRaw := d.Get("container").([]interface{}) - flattenContainerVolume(containerConfig, containersConfigRaw, *container.Name, container.VolumeMounts, containerGroupVolumes) + flattenContainerVolume(containerConfig, containersConfigRaw, container.Name, container.Properties.VolumeMounts, containerGroupVolumes) } containerCfg = append(containerCfg, containerConfig) } @@ -1611,8 +1608,7 @@ func flattenContainerGroupContainers(d *pluginsdk.ResourceData, containers *[]co containerCfg := make([]interface{}, 0, len(*containers)) for _, container := range *containers { - // TODO fix this crash point - name := *container.Name + name := container.Name // get index from name index := nameIndexMap[name] @@ -1620,77 +1616,68 @@ func flattenContainerGroupContainers(d *pluginsdk.ResourceData, containers *[]co containerConfig := make(map[string]interface{}) containerConfig["name"] = name - if v := container.Image; v != nil { - containerConfig["image"] = *v - } + containerConfig["image"] = container.Properties.Image - if resources := container.Resources; resources != nil { - if resourceRequests := resources.Requests; resourceRequests != nil { - if v := resourceRequests.CPU; v != nil { - containerConfig["cpu"] = *v - } - if v := resourceRequests.MemoryInGB; v != nil { - containerConfig["memory"] = *v - } + resources := container.Properties.Resources + resourceRequests := resources.Requests + containerConfig["cpu"] = resourceRequests.Cpu + containerConfig["memory"] = resourceRequests.MemoryInGB - gpus := make([]interface{}, 0) - if v := resourceRequests.Gpu; v != nil { - gpu := make(map[string]interface{}) - if v.Count != nil { - gpu["count"] = *v.Count - } - gpu["sku"] = string(v.Sku) - gpus = append(gpus, gpu) - } - containerConfig["gpu"] = gpus + gpus := make([]interface{}, 0) + if v := resourceRequests.Gpu; v != nil { + gpu := make(map[string]interface{}) + gpu["count"] = v.Count + gpu["sku"] = string(v.Sku) + gpus = append(gpus, gpu) + } + containerConfig["gpu"] = gpus + + if resourceLimits := resources.Limits; resourceLimits != nil { + if v := resourceLimits.Cpu; v != nil { + containerConfig["cpu_limit"] = *v + } + if v := resourceLimits.MemoryInGB; v != nil { + containerConfig["memory_limit"] = *v } - if resourceLimits := resources.Limits; resourceLimits != nil { - if v := resourceLimits.CPU; v != nil { - containerConfig["cpu_limit"] = *v - } - if v := resourceLimits.MemoryInGB; v != nil { - containerConfig["memory_limit"] = *v - } - gpus := make([]interface{}, 0) - if v := resourceLimits.Gpu; v != nil { - gpu := make(map[string]interface{}) - if v.Count != nil { - gpu["count"] = *v.Count - } - gpu["sku"] = string(v.Sku) - gpus = append(gpus, gpu) - } - containerConfig["gpu_limit"] = gpus + gpus := make([]interface{}, 0) + if v := resourceLimits.Gpu; v != nil { + gpu := make(map[string]interface{}) + gpu["count"] = v.Count + gpu["sku"] = string(v.Sku) + gpus = append(gpus, gpu) } + containerConfig["gpu_limit"] = gpus } - containerPorts := make([]interface{}, len(*container.Ports)) - for i := range *container.Ports { - containerPorts[i] = (*container.Ports)[i] + containerPorts := make([]interface{}, len(*container.Properties.Ports)) + if container.Properties.Ports != nil { + for i := range *container.Properties.Ports { + containerPorts[i] = (*container.Properties.Ports)[i] + } } containerConfig["ports"] = flattenPorts(containerPorts) - if container.EnvironmentVariables != nil { - if len(*container.EnvironmentVariables) > 0 { - containerConfig["environment_variables"] = flattenContainerEnvironmentVariables(container.EnvironmentVariables, false, d, index) - containerConfig["secure_environment_variables"] = flattenContainerEnvironmentVariables(container.EnvironmentVariables, true, d, index) + if container.Properties.EnvironmentVariables != nil { + if len(*container.Properties.EnvironmentVariables) > 0 { + containerConfig["environment_variables"] = flattenContainerEnvironmentVariables(container.Properties.EnvironmentVariables, false, d, index) + containerConfig["secure_environment_variables"] = flattenContainerEnvironmentVariables(container.Properties.EnvironmentVariables, true, d, index) } } commands := make([]string, 0) - if command := container.Command; command != nil { + if command := container.Properties.Command; command != nil { commands = *command } containerConfig["commands"] = commands - if containerGroupVolumes != nil && container.VolumeMounts != nil { + if containerGroupVolumes != nil && container.Properties.VolumeMounts != nil { containersConfigRaw := d.Get("container").([]interface{}) - flattenContainerVolume(containerConfig, containersConfigRaw, *container.Name, container.VolumeMounts, containerGroupVolumes) + flattenContainerVolume(containerConfig, containersConfigRaw, container.Name, container.Properties.VolumeMounts, containerGroupVolumes) } - containerConfig["liveness_probe"] = flattenContainerProbes(container.LivenessProbe) - containerConfig["readiness_probe"] = flattenContainerProbes(container.ReadinessProbe) + containerConfig["liveness_probe"] = flattenContainerProbes(container.Properties.LivenessProbe) + containerConfig["readiness_probe"] = flattenContainerProbes(container.Properties.ReadinessProbe) containerCfg = append(containerCfg, containerConfig) } @@ -1722,12 +1709,8 @@ func flattenContainerVolume(containerConfig map[string]interface{}, containersCo for _, vm := range *volumeMounts { volumeConfig := make(map[string]interface{}) - if vm.Name != nil { - volumeConfig["name"] = *vm.Name - } - if vm.MountPath != nil { - volumeConfig["mount_path"] = *vm.MountPath - } + volumeConfig["name"] = vm.Name + volumeConfig["mount_path"] = vm.MountPath if vm.ReadOnly != nil { volumeConfig["read_only"] = *vm.ReadOnly } @@ -1736,18 +1719,10 @@ func flattenContainerVolume(containerConfig map[string]interface{}, containersCo // and use the data if containerGroupVolumes != nil { for _, cgv := range *containerGroupVolumes { - if cgv.Name == nil || vm.Name == nil { - continue - } - - if *cgv.Name == *vm.Name { + if cgv.Name == vm.Name { if file := cgv.AzureFile; file != nil { - if file.ShareName != nil { - volumeConfig["share_name"] = *file.ShareName - } - if file.StorageAccountName != nil { - volumeConfig["storage_account_name"] = *file.StorageAccountName - } + volumeConfig["share_name"] = file.ShareName + volumeConfig["storage_account_name"] = file.StorageAccountName // skip storage_account_key, is always nil } @@ -1766,7 +1741,7 @@ func flattenContainerVolume(containerConfig map[string]interface{}, containersCo for _, cvr := range *containerVolumesConfig { cv := cvr.(map[string]interface{}) rawName := cv["name"].(string) - if vm.Name != nil && *vm.Name == rawName { + if vm.Name == rawName { storageAccountKey := cv["storage_account_key"].(string) volumeConfig["storage_account_key"] = storageAccountKey volumeConfig["secret"] = cv["secret"] @@ -1789,16 +1764,16 @@ func flattenContainerEnvironmentVariables(input *[]containerinstance.Environment if isSecure { for _, envVar := range *input { - if envVar.Name != nil && envVar.Value == nil { - envVarValue := d.Get(fmt.Sprintf("container.%d.secure_environment_variables.%s", oldContainerIndex, *envVar.Name)) - output[*envVar.Name] = envVarValue + if envVar.Value == nil { + envVarValue := d.Get(fmt.Sprintf("container.%d.secure_environment_variables.%s", oldContainerIndex, envVar.Name)) + output[envVar.Name] = envVarValue } } } else { for _, envVar := range *input { - if envVar.Name != nil && envVar.Value != nil { - log.Printf("[DEBUG] NOT SECURE: Name: %s - Value: %s", *envVar.Name, *envVar.Value) - output[*envVar.Name] = *envVar.Value + if envVar.Value != nil { + log.Printf("[DEBUG] NOT SECURE: Name: %s - Value: %s", envVar.Name, *envVar.Value) + output[envVar.Name] = *envVar.Value } } } @@ -1817,9 +1792,7 @@ func flattenGitRepoVolume(input *containerinstance.GitRepoVolume) []interface{} if input.Revision != nil { revision = *input.Revision } - if input.Repository != nil { - repository = *input.Repository - } + repository = input.Repository return []interface{}{ map[string]interface{}{ "url": repository, @@ -1842,21 +1815,14 @@ func flattenContainerProbes(input *containerinstance.ContainerProbe) []interface } httpGets := make([]interface{}, 0) - if get := input.HTTPGet; get != nil { + if get := input.HttpGet; get != nil { httpGet := make(map[string]interface{}) - if v := get.Path; v != nil { httpGet["path"] = *v } - - if v := get.Port; v != nil { - httpGet["port"] = *v - } - - if get.Scheme != "" { - httpGet["scheme"] = get.Scheme - } - + httpGet["port"] = get.Port + httpGet["scheme"] = get.Scheme + httpGet["http_headers"] = flattenContainerProbeHttpHeaders(get.HttpHeaders) httpGets = append(httpGets, httpGet) } output["http_get"] = httpGets @@ -1899,21 +1865,22 @@ func expandContainerGroupDiagnostics(input []interface{}) *containerinstance.Con workspaceKey := analyticsV["workspace_key"].(string) logAnalytics := containerinstance.LogAnalytics{ - WorkspaceID: utils.String(workspaceId), - WorkspaceKey: utils.String(workspaceKey), + WorkspaceId: workspaceId, + WorkspaceKey: workspaceKey, } if logType := analyticsV["log_type"].(string); logType != "" { - logAnalytics.LogType = containerinstance.LogAnalyticsLogType(logType) + t := containerinstance.LogAnalyticsLogType(logType) + logAnalytics.LogType = &t metadataMap := analyticsV["metadata"].(map[string]interface{}) - metadata := make(map[string]*string) + metadata := make(map[string]string) for k, v := range metadataMap { strValue := v.(string) - metadata[k] = &strValue + metadata[k] = strValue } - logAnalytics.Metadata = metadata + logAnalytics.Metadata = &metadata } return &containerinstance.ContainerGroupDiagnostics{LogAnalytics: &logAnalytics} @@ -1929,17 +1896,20 @@ func flattenContainerGroupDiagnostics(d *pluginsdk.ResourceData, input *containe if la := input.LogAnalytics; la != nil { output := make(map[string]interface{}) - output["log_type"] = string(la.LogType) + logType := "" + if la.LogType != nil { + logType = string(*la.LogType) + } + output["log_type"] = logType metadata := make(map[string]interface{}) - for k, v := range la.Metadata { - metadata[k] = *v + if la.Metadata != nil { + for k, v := range *la.Metadata { + metadata[k] = v + } } output["metadata"] = metadata - - if la.WorkspaceID != nil { - output["workspace_id"] = *la.WorkspaceID - } + output["workspace_id"] = la.WorkspaceId // the existing config may not exist at Import time, protect against it. workspaceKey := "" @@ -1975,7 +1945,7 @@ func resourceContainerGroupPortsHash(v interface{}) int { return pluginsdk.HashString(buf.String()) } -func flattenContainerGroupDnsConfig(input *containerinstance.DNSConfiguration) []interface{} { +func flattenContainerGroupDnsConfig(input *containerinstance.DnsConfiguration) []interface{} { output := make(map[string]interface{}) if input == nil { @@ -1995,18 +1965,12 @@ func flattenContainerGroupDnsConfig(input *containerinstance.DNSConfiguration) [ options = strings.Fields(*input.Options) } output["options"] = options - - // Nameservers is already an array from the API - var nameservers []string - if input.NameServers != nil { - nameservers = *input.NameServers - } - output["nameservers"] = nameservers + output["nameservers"] = input.NameServers return []interface{}{output} } -func expandContainerGroupDnsConfig(input interface{}) *containerinstance.DNSConfiguration { +func expandContainerGroupDnsConfig(input interface{}) *containerinstance.DnsConfiguration { dnsConfigRaw := input.([]interface{}) if len(dnsConfigRaw) > 0 { config := dnsConfigRaw[0].(map[string]interface{}) @@ -2024,10 +1988,10 @@ func expandContainerGroupDnsConfig(input interface{}) *containerinstance.DNSConf searchDomains = append(searchDomains, v.(string)) } - return &containerinstance.DNSConfiguration{ - Options: utils.String(strings.Join(options, " ")), - SearchDomains: utils.String(strings.Join(searchDomains, " ")), - NameServers: &nameservers, + return &containerinstance.DnsConfiguration{ + Options: pointer.FromString(strings.Join(options, " ")), + SearchDomains: pointer.FromString(strings.Join(searchDomains, " ")), + NameServers: nameservers, } } diff --git a/internal/services/containers/container_group_resource_test.go b/internal/services/containers/container_group_resource_test.go index 9beb2be6a200..844e7ea60aea 100644 --- a/internal/services/containers/container_group_resource_test.go +++ b/internal/services/containers/container_group_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/containers/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -739,6 +739,10 @@ resource "azurerm_container_group" "test" { path = "/" port = 443 scheme = "Http" + http_headers = { + h1 = "v1" + h2 = "v2" + } } } } @@ -1763,6 +1767,10 @@ resource "azurerm_container_group" "test" { path = "/" port = 443 scheme = "Http" + http_headers = { + h1 = "v1" + h2 = "v2" + } } initial_delay_seconds = 1 @@ -1909,6 +1917,10 @@ resource "azurerm_container_group" "test" { path = "/" port = 443 scheme = "Http" + http_headers = { + h1 = "v1" + h2 = "v2" + } } initial_delay_seconds = 1 @@ -2277,17 +2289,21 @@ resource "azurerm_container_group" "test" { } func (t ContainerGroupResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.ContainerGroupID(state.ID) + id, err := containerinstance.ParseContainerGroupID(state.ID) if err != nil { return nil, err } - resp, err := clients.Containers.GroupsClient.Get(ctx, id.ResourceGroup, id.Name) + resp, err := clients.Containers.ContainerInstanceClient.ContainerGroupsGet(ctx, *id) if err != nil { return nil, fmt.Errorf("reading Container Group (%s): %+v", id.String(), err) } - return utils.Bool(resp.ID != nil), nil + if resp.Model == nil { + return nil, fmt.Errorf("unexpected nil model of %q", id) + } + + return utils.Bool(resp.Model.Id != nil), nil } func (ContainerGroupResource) withPrivateEmpty(data acceptance.TestData) string { diff --git a/internal/services/containers/kubernetes_cluster_addons_resource_test.go b/internal/services/containers/kubernetes_cluster_addons_resource_test.go index cd2b4b3db1c1..d471114735ad 100644 --- a/internal/services/containers/kubernetes_cluster_addons_resource_test.go +++ b/internal/services/containers/kubernetes_cluster_addons_resource_test.go @@ -8,7 +8,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" ) -var addOnAppGatewaySubnetCIDR string = "10.241.0.0/16" // AKS will use 10.240.0.0/16 for the aks subnet so use 10.241.0.0/16 for the app gateway subnet +var addOnAppGatewaySubnetCIDR string = "10.225.0.0/16" // AKS will use 10.224.0.0/12 for the aks subnet so use 10.225.0.0/16 for the app gateway subnet func TestAccKubernetesCluster_addonProfileAciConnectorLinux(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_kubernetes_cluster", "test") @@ -554,7 +554,11 @@ resource "azurerm_kubernetes_cluster" "test" { func (KubernetesClusterResource) addonProfileIngressApplicationGatewayAppGatewayConfig(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { - features {} + features { + resource_group { + prevent_deletion_if_contains_resources = false + } + } } resource "azurerm_resource_group" "test" { @@ -635,6 +639,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = "httplistener" backend_address_pool_name = "backendaddresspool" backend_http_settings_name = "backendhttpsettings" + priority = 1 } } @@ -672,7 +677,11 @@ resource "azurerm_kubernetes_cluster" "test" { func (KubernetesClusterResource) addonProfileIngressApplicationGatewaySubnetCIDRConfig(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { - features {} + features { + resource_group { + prevent_deletion_if_contains_resources = false + } + } } resource "azurerm_resource_group" "test" { @@ -810,7 +819,11 @@ resource "azurerm_kubernetes_cluster" "test" { func (KubernetesClusterResource) addonProfileOpenServiceMeshConfig(data acceptance.TestData, enabled bool) string { return fmt.Sprintf(` provider "azurerm" { - features {} + features { + resource_group { + prevent_deletion_if_contains_resources = false + } + } } resource "azurerm_resource_group" "test" { diff --git a/internal/services/containers/kubernetes_cluster_network_resource_test.go b/internal/services/containers/kubernetes_cluster_network_resource_test.go index 24f773e8c9fb..4c40dfce1809 100644 --- a/internal/services/containers/kubernetes_cluster_network_resource_test.go +++ b/internal/services/containers/kubernetes_cluster_network_resource_test.go @@ -2523,6 +2523,14 @@ resource "azurerm_kubernetes_cluster" "test" { func (KubernetesClusterResource) httpProxyConfigWithTrustedCa(data acceptance.TestData) string { return fmt.Sprintf(` +provider "azurerm" { + features { + resource_group { + prevent_deletion_if_contains_resources = false + } + } +} + resource "azurerm_resource_group" "test" { name = "acctestRG-%d" location = "%s" diff --git a/internal/services/containers/kubernetes_cluster_node_pool_resource.go b/internal/services/containers/kubernetes_cluster_node_pool_resource.go index 506f9e93acdf..45f552304b69 100644 --- a/internal/services/containers/kubernetes_cluster_node_pool_resource.go +++ b/internal/services/containers/kubernetes_cluster_node_pool_resource.go @@ -80,7 +80,21 @@ func resourceKubernetesClusterNodePool() *pluginsdk.Resource { ValidateFunc: validation.StringIsNotEmpty, }, + "host_group_id": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: computeValidate.HostGroupID, + }, + // Optional + "capacity_reservation_group_id": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: computeValidate.CapacityReservationGroupID, + }, + "enable_auto_scaling": { Type: pluginsdk.TypeBool, Optional: true, @@ -461,6 +475,14 @@ func resourceKubernetesClusterNodePoolCreate(d *pluginsdk.ResourceData, meta int profile.VnetSubnetID = utils.String(vnetSubnetID) } + if hostGroupID := d.Get("host_group_id").(string); hostGroupID != "" { + profile.HostGroupID = utils.String(hostGroupID) + } + + if capacityReservationGroupId := d.Get("capacity_reservation_group_id").(string); capacityReservationGroupId != "" { + profile.CapacityReservationGroupID = utils.String(capacityReservationGroupId) + } + maxCount := d.Get("max_count").(int) minCount := d.Get("min_count").(int) @@ -827,6 +849,8 @@ func resourceKubernetesClusterNodePoolRead(d *pluginsdk.ResourceData, meta inter d.Set("vnet_subnet_id", props.VnetSubnetID) d.Set("vm_size", props.VMSize) + d.Set("host_group_id", props.HostGroupID) + d.Set("capacity_reservation_group_id", props.CapacityReservationGroupID) if err := d.Set("upgrade_settings", flattenUpgradeSettings(props.UpgradeSettings)); err != nil { return fmt.Errorf("setting `upgrade_settings`: %+v", err) diff --git a/internal/services/containers/kubernetes_cluster_node_pool_resource_test.go b/internal/services/containers/kubernetes_cluster_node_pool_resource_test.go index 41d854d46fc9..7a92eec905e3 100644 --- a/internal/services/containers/kubernetes_cluster_node_pool_resource_test.go +++ b/internal/services/containers/kubernetes_cluster_node_pool_resource_test.go @@ -97,6 +97,21 @@ func TestAccKubernetesClusterNodePool_availabilityZones(t *testing.T) { }) } +func TestAccKubernetesClusterNodePool_capacityReservationGroup(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kubernetes_cluster_node_pool", "test") + r := KubernetesClusterNodePoolResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.capacityReservationGroup(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccKubernetesClusterNodePool_errorForAvailabilitySet(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_kubernetes_cluster_node_pool", "test") r := KubernetesClusterNodePoolResource{} @@ -722,6 +737,21 @@ func TestAccKubernetesClusterNodePool_osSku(t *testing.T) { }) } +func TestAccKubernetesClusterNodePool_dedicatedHost(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kubernetes_cluster_node_pool", "test") + r := KubernetesClusterNodePoolResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.dedicatedHost(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccKubernetesClusterNodePool_turnOnEnableAutoScalingWithDefaultMaxMinCountSettings(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_kubernetes_cluster_node_pool", "test") r := KubernetesClusterNodePoolResource{} @@ -1118,6 +1148,77 @@ resource "azurerm_kubernetes_cluster_node_pool" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } +func (KubernetesClusterNodePoolResource) capacityReservationGroup(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-aks-%[1]d" + location = "%[2]s" +} + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[1]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + + sku { + name = "Standard_D2s_v3" + capacity = 2 + } +} + +resource "azurerm_user_assigned_identity" "test" { + name = "acctest%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_role_assignment" "test" { + scope = azurerm_capacity_reservation_group.test.id + principal_id = azurerm_user_assigned_identity.test.principal_id + role_definition_name = "Owner" +} + +resource "azurerm_kubernetes_cluster" "test" { + name = "acctestaks%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + dns_prefix = "acctestaks%[1]d" + default_node_pool { + name = "default" + node_count = 1 + vm_size = "Standard_D2s_v3" + capacity_reservation_group_id = azurerm_capacity_reservation.test.capacity_reservation_group_id + } + + identity { + type = "UserAssigned" + identity_ids = [azurerm_user_assigned_identity.test.id] + } + + depends_on = [ + azurerm_capacity_reservation.test, + azurerm_role_assignment.test + ] +} +resource "azurerm_kubernetes_cluster_node_pool" "test" { + name = "internal" + kubernetes_cluster_id = azurerm_kubernetes_cluster.test.id + vm_size = "Standard_D2s_v3" + node_count = 1 + capacity_reservation_group_id = azurerm_capacity_reservation.test.capacity_reservation_group_id +} +`, data.RandomInteger, data.Locations.Primary) +} + func (r KubernetesClusterNodePoolResource) manualScaleConfig(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { @@ -1964,6 +2065,77 @@ resource "azurerm_kubernetes_cluster_node_pool" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) } +func (KubernetesClusterNodePoolResource) dedicatedHost(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-aks-%[1]d" + location = "%[2]s" +} + +resource "azurerm_dedicated_host_group" "test" { + name = "acctestDHG-compute-%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + platform_fault_domain_count = 3 + automatic_placement_enabled = true +} + +resource "azurerm_dedicated_host" "test" { + name = "acctest-DH-%[1]d" + location = azurerm_resource_group.test.location + dedicated_host_group_id = azurerm_dedicated_host_group.test.id + sku_name = "DSv3-Type1" + platform_fault_domain = 0 +} + +resource "azurerm_user_assigned_identity" "test" { + name = "acctest%[2]s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_role_assignment" "test" { + scope = azurerm_resource_group.test.id + principal_id = azurerm_user_assigned_identity.test.principal_id + role_definition_name = "Contributor" +} + +resource "azurerm_kubernetes_cluster" "test" { + name = "acctestaks%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + dns_prefix = "acctestaks%[1]d" + + default_node_pool { + name = "default" + node_count = 1 + vm_size = "Standard_D2s_v3" + } + + identity { + type = "UserAssigned" + identity_ids = [azurerm_user_assigned_identity.test.id] + } + + depends_on = [ + azurerm_role_assignment.test + ] +} + +resource "azurerm_kubernetes_cluster_node_pool" "test" { + name = "internal" + kubernetes_cluster_id = azurerm_kubernetes_cluster.test.id + vm_size = "Standard_DS2_v2" + node_count = 1 + host_group_id = azurerm_dedicated_host_group.test.id +} +`, data.RandomInteger, data.Locations.Primary) +} + func (r KubernetesClusterNodePoolResource) nodePool(data acceptance.TestData, enableAutoScaling bool, minCount, maxCount int) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/containers/kubernetes_cluster_other_resource_test.go b/internal/services/containers/kubernetes_cluster_other_resource_test.go index 62dec9683399..e319eb8d09bb 100644 --- a/internal/services/containers/kubernetes_cluster_other_resource_test.go +++ b/internal/services/containers/kubernetes_cluster_other_resource_test.go @@ -464,6 +464,21 @@ func TestAccKubernetesCluster_basicMaintenanceConfig(t *testing.T) { }) } +func TestAccKubernetesCluster_capacityReservationGroup(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kubernetes_cluster", "test") + r := KubernetesClusterResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.capacityReservationGroup(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccKubernetesCluster_completeMaintenanceConfig(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_kubernetes_cluster", "test") r := KubernetesClusterResource{} @@ -1731,6 +1746,70 @@ resource "azurerm_kubernetes_cluster" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) } +func (KubernetesClusterResource) capacityReservationGroup(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-aks-%[1]d" + location = "%[2]s" +} + +resource "azurerm_capacity_reservation_group" "test" { + name = "acctest-ccrg-%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_capacity_reservation" "test" { + name = "acctest-ccr-%[1]d" + capacity_reservation_group_id = azurerm_capacity_reservation_group.test.id + + sku { + name = "Standard_D2s_v3" + capacity = 2 + } +} + +resource "azurerm_user_assigned_identity" "test" { + name = "acctest%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_role_assignment" "test" { + scope = azurerm_capacity_reservation_group.test.id + principal_id = azurerm_user_assigned_identity.test.principal_id + role_definition_name = "Owner" +} + +resource "azurerm_kubernetes_cluster" "test" { + name = "acctestaks%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + dns_prefix = "acctestaks%[1]d" + default_node_pool { + name = "default" + node_count = 1 + vm_size = "Standard_D2s_v3" + capacity_reservation_group_id = azurerm_capacity_reservation.test.capacity_reservation_group_id + } + + identity { + type = "UserAssigned" + identity_ids = [azurerm_user_assigned_identity.test.id] + } + + depends_on = [ + azurerm_capacity_reservation.test, + azurerm_role_assignment.test + ] +} +`, data.RandomInteger, data.Locations.Primary) +} + func (KubernetesClusterResource) completeMaintenanceConfig(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/containers/kubernetes_cluster_resource.go b/internal/services/containers/kubernetes_cluster_resource.go index f3a66b918d20..9c796f5e9d05 100644 --- a/internal/services/containers/kubernetes_cluster_resource.go +++ b/internal/services/containers/kubernetes_cluster_resource.go @@ -2903,7 +2903,9 @@ func expandKubernetesClusterHttpProxyConfig(input []interface{}) *containerservi httpProxyConfig.HTTPProxy = utils.String(config["http_proxy"].(string)) httpProxyConfig.HTTPSProxy = utils.String(config["https_proxy"].(string)) - httpProxyConfig.TrustedCa = utils.String(config["trusted_ca"].(string)) + if value := config["trusted_ca"].(string); len(value) != 0 { + httpProxyConfig.TrustedCa = utils.String(value) + } noProxyRaw := config["no_proxy"].(*pluginsdk.Set).List() httpProxyConfig.NoProxy = utils.ExpandStringSlice(noProxyRaw) diff --git a/internal/services/containers/kubernetes_cluster_resource_test.go b/internal/services/containers/kubernetes_cluster_resource_test.go index e3abe20eecd2..08c986c1fcef 100644 --- a/internal/services/containers/kubernetes_cluster_resource_test.go +++ b/internal/services/containers/kubernetes_cluster_resource_test.go @@ -38,6 +38,20 @@ func TestAccKubernetesCluster_hostEncryption(t *testing.T) { }) } +func TestAccKubernetesCluster_dedicatedHost(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kubernetes_cluster", "test") + r := KubernetesClusterResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.dedicatedHost(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + }) +} + func TestAccKubernetesCluster_runCommand(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_kubernetes_cluster", "test") r := KubernetesClusterResource{} @@ -140,6 +154,70 @@ resource "azurerm_kubernetes_cluster" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, controlPlaneVersion) } +func (KubernetesClusterResource) dedicatedHost(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-aks-%[1]d" + location = "%[2]s" +} + +resource "azurerm_dedicated_host_group" "test" { + name = "acctestDHG-compute-%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + platform_fault_domain_count = 3 + automatic_placement_enabled = true +} + +resource "azurerm_dedicated_host" "test" { + name = "acctest-DH-%[1]d" + location = azurerm_resource_group.test.location + dedicated_host_group_id = azurerm_dedicated_host_group.test.id + sku_name = "DSv3-Type1" + platform_fault_domain = 0 +} + +resource "azurerm_user_assigned_identity" "test" { + name = "acctest%[2]s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + +resource "azurerm_role_assignment" "test" { + scope = azurerm_resource_group.test.id + principal_id = azurerm_user_assigned_identity.test.principal_id + role_definition_name = "Contributor" +} + +resource "azurerm_kubernetes_cluster" "test" { + name = "acctestaks%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + dns_prefix = "acctestaks%[1]d" + + default_node_pool { + name = "default" + node_count = 1 + vm_size = "Standard_DS2_v2" + host_group_id = azurerm_dedicated_host_group.test.id + } + + identity { + type = "UserAssigned" + identity_ids = [azurerm_user_assigned_identity.test.id] + } + + depends_on = [ + azurerm_role_assignment.test + ] +} + `, data.RandomInteger, data.Locations.Primary) +} + func (KubernetesClusterResource) runCommand(data acceptance.TestData, controlPlaneVersion string, runCommandEnabled bool) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/containers/kubernetes_cluster_upgrade_test.go b/internal/services/containers/kubernetes_cluster_upgrade_test.go index 10d5e451e64e..fbff4a10149b 100644 --- a/internal/services/containers/kubernetes_cluster_upgrade_test.go +++ b/internal/services/containers/kubernetes_cluster_upgrade_test.go @@ -15,14 +15,14 @@ func TestAccKubernetesCluster_upgradeAutoScaleMinCount(t *testing.T) { data.ResourceTest(t, r, []acceptance.TestStep{ { - Config: r.upgradeAutoScaleMinCountConfig(data, olderKubernetesVersion, 3, 8), + Config: r.upgradeAutoScaleMinCountConfig(data, olderKubernetesVersion, 4, 8), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.upgradeAutoScaleMinCountConfig(data, olderKubernetesVersion, 4, 8), + Config: r.upgradeAutoScaleMinCountConfig(data, olderKubernetesVersion, 5, 8), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), diff --git a/internal/services/containers/kubernetes_nodepool.go b/internal/services/containers/kubernetes_nodepool.go index fe8bdf1efef0..eb8a5a576a10 100644 --- a/internal/services/containers/kubernetes_nodepool.go +++ b/internal/services/containers/kubernetes_nodepool.go @@ -54,6 +54,13 @@ func SchemaDefaultNodePool() *pluginsdk.Schema { ValidateFunc: validation.StringIsNotEmpty, }, + "capacity_reservation_group_id": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: computeValidate.CapacityReservationGroupID, + }, + // TODO 4.0: change this from enable_* to *_enabled "enable_auto_scaling": { Type: pluginsdk.TypeBool, @@ -217,6 +224,13 @@ func SchemaDefaultNodePool() *pluginsdk.Schema { ForceNew: true, }, + "host_group_id": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: computeValidate.HostGroupID, + }, + "upgrade_settings": upgradeSettingsSchema(), } @@ -701,6 +715,10 @@ func ExpandDefaultNodePool(d *pluginsdk.ResourceData) (*[]containerservice.Manag profile.VnetSubnetID = utils.String(vnetSubnetID) } + if hostGroupID := raw["host_group_id"].(string); hostGroupID != "" { + profile.HostGroupID = utils.String(hostGroupID) + } + if orchestratorVersion := raw["orchestrator_version"].(string); orchestratorVersion != "" { profile.OrchestratorVersion = utils.String(orchestratorVersion) } @@ -709,6 +727,10 @@ func ExpandDefaultNodePool(d *pluginsdk.ResourceData) (*[]containerservice.Manag profile.ProximityPlacementGroupID = utils.String(proximityPlacementGroupId) } + if capacityReservationGroupId := raw["capacity_reservation_group_id"].(string); capacityReservationGroupId != "" { + profile.CapacityReservationGroupID = utils.String(capacityReservationGroupId) + } + count := raw["node_count"].(int) maxCount := raw["max_count"].(int) minCount := raw["min_count"].(int) @@ -1041,6 +1063,11 @@ func FlattenDefaultNodePool(input *[]containerservice.ManagedClusterAgentPoolPro vnetSubnetId = *agentPool.VnetSubnetID } + hostGroupID := "" + if agentPool.HostGroupID != nil { + hostGroupID = *agentPool.HostGroupID + } + orchestratorVersion := "" if agentPool.OrchestratorVersion != nil { orchestratorVersion = *agentPool.OrchestratorVersion @@ -1055,6 +1082,10 @@ func FlattenDefaultNodePool(input *[]containerservice.ManagedClusterAgentPoolPro if agentPool.VMSize != nil { vmSize = *agentPool.VMSize } + capacityReservationGroupId := "" + if agentPool.CapacityReservationGroupID != nil { + capacityReservationGroupId = *agentPool.CapacityReservationGroupID + } upgradeSettings := flattenUpgradeSettings(agentPool.UpgradeSettings) linuxOSConfig, err := flattenAgentPoolLinuxOSConfig(agentPool.LinuxOSConfig) @@ -1063,35 +1094,37 @@ func FlattenDefaultNodePool(input *[]containerservice.ManagedClusterAgentPoolPro } out := map[string]interface{}{ - "enable_auto_scaling": enableAutoScaling, - "enable_node_public_ip": enableNodePublicIP, - "enable_host_encryption": enableHostEncryption, - "fips_enabled": enableFIPS, - "kubelet_disk_type": string(agentPool.KubeletDiskType), - "max_count": maxCount, - "max_pods": maxPods, - "min_count": minCount, - "name": name, - "node_count": count, - "node_labels": nodeLabels, - "node_public_ip_prefix_id": nodePublicIPPrefixID, - "node_taints": []string{}, - "os_disk_size_gb": osDiskSizeGB, - "os_disk_type": string(osDiskType), - "os_sku": string(agentPool.OsSKU), - "tags": tags.Flatten(agentPool.Tags), - "type": string(agentPool.Type), - "ultra_ssd_enabled": enableUltraSSD, - "vm_size": vmSize, - "pod_subnet_id": podSubnetId, - "orchestrator_version": orchestratorVersion, - "proximity_placement_group_id": proximityPlacementGroupId, - "upgrade_settings": upgradeSettings, - "vnet_subnet_id": vnetSubnetId, - "only_critical_addons_enabled": criticalAddonsEnabled, - "kubelet_config": flattenAgentPoolKubeletConfig(agentPool.KubeletConfig), - "linux_os_config": linuxOSConfig, - "zones": zones.Flatten(agentPool.AvailabilityZones), + "enable_auto_scaling": enableAutoScaling, + "enable_node_public_ip": enableNodePublicIP, + "enable_host_encryption": enableHostEncryption, + "fips_enabled": enableFIPS, + "host_group_id": hostGroupID, + "kubelet_disk_type": string(agentPool.KubeletDiskType), + "max_count": maxCount, + "max_pods": maxPods, + "min_count": minCount, + "name": name, + "node_count": count, + "node_labels": nodeLabels, + "node_public_ip_prefix_id": nodePublicIPPrefixID, + "node_taints": []string{}, + "os_disk_size_gb": osDiskSizeGB, + "os_disk_type": string(osDiskType), + "os_sku": string(agentPool.OsSKU), + "tags": tags.Flatten(agentPool.Tags), + "type": string(agentPool.Type), + "ultra_ssd_enabled": enableUltraSSD, + "vm_size": vmSize, + "pod_subnet_id": podSubnetId, + "orchestrator_version": orchestratorVersion, + "proximity_placement_group_id": proximityPlacementGroupId, + "upgrade_settings": upgradeSettings, + "vnet_subnet_id": vnetSubnetId, + "only_critical_addons_enabled": criticalAddonsEnabled, + "kubelet_config": flattenAgentPoolKubeletConfig(agentPool.KubeletConfig), + "linux_os_config": linuxOSConfig, + "zones": zones.Flatten(agentPool.AvailabilityZones), + "capacity_reservation_group_id": capacityReservationGroupId, } return &[]interface{}{ diff --git a/internal/services/containers/probe.go b/internal/services/containers/probe.go index b9ac2e7a45f7..cddb1e444106 100644 --- a/internal/services/containers/probe.go +++ b/internal/services/containers/probe.go @@ -53,6 +53,14 @@ func SchemaContainerGroupProbe() *pluginsdk.Schema { "Https", }, false), }, + "http_headers": { + Type: pluginsdk.TypeMap, + Optional: true, + ForceNew: true, + Elem: &pluginsdk.Schema{ + Type: pluginsdk.TypeString, + }, + }, }, }, }, diff --git a/internal/services/containers/resourceids.go b/internal/services/containers/resourceids.go index de37bee4a54e..6e9486c55413 100644 --- a/internal/services/containers/resourceids.go +++ b/internal/services/containers/resourceids.go @@ -3,7 +3,6 @@ package containers //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name ContainerRegistryAgentPool -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.ContainerRegistry/registries/registry1/agentPools/agent_pool1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=Cluster -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.ContainerService/managedClusters/cluster1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=NodePool -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.ContainerService/managedClusters/cluster1/agentPools/pool1 -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=ContainerGroup -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.ContainerInstance/containerGroups/containerGroup1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=ContainerRegistryScopeMap -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.ContainerRegistry/registries/registry1/scopeMaps/scopeMap1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=ContainerRegistryTask -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.ContainerRegistry/registries/registry1/tasks/task1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=ContainerRegistryToken -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.ContainerRegistry/registries/registry1/tokens/token1 diff --git a/internal/services/cosmos/cosmosdb_account_resource.go b/internal/services/cosmos/cosmosdb_account_resource.go index 7b610f6cff87..9802b91ade36 100644 --- a/internal/services/cosmos/cosmosdb_account_resource.go +++ b/internal/services/cosmos/cosmosdb_account_resource.go @@ -10,13 +10,12 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" "github.com/Azure/go-autorest/autorest/date" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/cosmos/cosmosdb_cassandra_datacenter_resource.go b/internal/services/cosmos/cosmosdb_cassandra_datacenter_resource.go index f32ecef312e6..e2cc64b701d7 100644 --- a/internal/services/cosmos/cosmosdb_cassandra_datacenter_resource.go +++ b/internal/services/cosmos/cosmosdb_cassandra_datacenter_resource.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "log" - "strconv" "time" "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb" @@ -16,6 +15,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/cosmos/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/cosmos/validate" + keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate" networkValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" @@ -36,10 +36,10 @@ func resourceCassandraDatacenter() *pluginsdk.Resource { }), Timeouts: &pluginsdk.ResourceTimeout{ - Create: pluginsdk.DefaultTimeout(30 * time.Minute), + Create: pluginsdk.DefaultTimeout(60 * time.Minute), Read: pluginsdk.DefaultTimeout(5 * time.Minute), - Update: pluginsdk.DefaultTimeout(30 * time.Minute), - Delete: pluginsdk.DefaultTimeout(30 * time.Minute), + Update: pluginsdk.DefaultTimeout(60 * time.Minute), + Delete: pluginsdk.DefaultTimeout(60 * time.Minute), }, Schema: map[string]*pluginsdk.Schema{ @@ -66,6 +66,31 @@ func resourceCassandraDatacenter() *pluginsdk.Resource { ValidateFunc: networkValidate.SubnetID, }, + "backup_storage_customer_key_uri": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: keyVaultValidate.NestedItemId, + }, + + "base64_encoded_yaml_fragment": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "disk_sku": { + Type: pluginsdk.TypeString, + Optional: true, + Default: "P30", + ValidateFunc: validation.StringIsNotEmpty, + }, + + "managed_disk_customer_key_uri": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: keyVaultValidate.NestedItemId, + }, + "node_count": { Type: pluginsdk.TypeInt, Optional: true, @@ -116,10 +141,23 @@ func resourceCassandraDatacenterCreate(d *pluginsdk.ResourceData, meta interface Sku: utils.String(d.Get("sku_name").(string)), AvailabilityZone: utils.Bool(d.Get("availability_zones_enabled").(bool)), DiskCapacity: utils.Int32(int32(d.Get("disk_count").(int))), + DiskSku: utils.String(d.Get("disk_sku").(string)), DataCenterLocation: utils.String(azure.NormalizeLocation(d.Get("location").(string))), }, } + if v, ok := d.GetOk("backup_storage_customer_key_uri"); ok { + body.Properties.BackupStorageCustomerKeyURI = utils.String(v.(string)) + } + + if v, ok := d.GetOk("base64_encoded_yaml_fragment"); ok { + body.Properties.Base64EncodedCassandraYamlFragment = utils.String(v.(string)) + } + + if v, ok := d.GetOk("managed_disk_customer_key_uri"); ok { + body.Properties.ManagedDiskCustomerKeyURI = utils.String(v.(string)) + } + future, err := client.CreateUpdate(ctx, id.ResourceGroup, id.CassandraClusterName, id.DataCenterName, body) if err != nil { return fmt.Errorf("creating %q: %+v", id, err) @@ -161,8 +199,12 @@ func resourceCassandraDatacenterRead(d *pluginsdk.ResourceData, meta interface{} if res := props; res != nil { d.Set("delegated_management_subnet_id", props.DelegatedSubnetID) d.Set("location", location.NormalizeNilable(props.DataCenterLocation)) + d.Set("backup_storage_customer_key_uri", props.BackupStorageCustomerKeyURI) + d.Set("base64_encoded_yaml_fragment", props.Base64EncodedCassandraYamlFragment) + d.Set("managed_disk_customer_key_uri", props.ManagedDiskCustomerKeyURI) d.Set("node_count", props.NodeCount) d.Set("disk_count", int(*props.DiskCapacity)) + d.Set("disk_sku", props.DiskSku) d.Set("sku_name", props.Sku) d.Set("availability_zones_enabled", props.AvailabilityZone) } @@ -185,9 +227,22 @@ func resourceCassandraDatacenterUpdate(d *pluginsdk.ResourceData, meta interface DelegatedSubnetID: utils.String(d.Get("delegated_management_subnet_id").(string)), NodeCount: utils.Int32(int32(d.Get("node_count").(int))), DataCenterLocation: utils.String(azure.NormalizeLocation(d.Get("location").(string))), + DiskSku: utils.String(d.Get("disk_sku").(string)), }, } + if v, ok := d.GetOk("backup_storage_customer_key_uri"); ok { + body.Properties.BackupStorageCustomerKeyURI = utils.String(v.(string)) + } + + if v, ok := d.GetOk("base64_encoded_yaml_fragment"); ok { + body.Properties.Base64EncodedCassandraYamlFragment = utils.String(v.(string)) + } + + if v, ok := d.GetOk("managed_disk_customer_key_uri"); ok { + body.Properties.ManagedDiskCustomerKeyURI = utils.String(v.(string)) + } + future, err := client.CreateUpdate(ctx, id.ResourceGroup, id.CassandraClusterName, id.DataCenterName, body) if err != nil { return fmt.Errorf("updating %q: %+v", id, err) @@ -197,21 +252,21 @@ func resourceCassandraDatacenterUpdate(d *pluginsdk.ResourceData, meta interface return fmt.Errorf("waiting on update for %q: %+v", id, err) } - // In case the node_count is changed, we need to further poll the node count until the update takes effect. - if d.HasChange("node_count") { - oldNodeCountRaw, _ := d.GetChange("node_count") - oldNodeCount := oldNodeCountRaw.(int) - stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{"-1", strconv.Itoa(oldNodeCount)}, - Target: []string{strconv.Itoa(d.Get("node_count").(int))}, - Refresh: cassandraDatacenterStateRefreshFunc(ctx, client, *id), - MinTimeout: 30 * time.Second, - Timeout: d.Timeout(pluginsdk.TimeoutUpdate), - } + // Issue: https://github.com/Azure/azure-rest-api-specs/issues/19078 + // There is a long running issue on updating this resource. + // The API cannot update the property after WaitForCompletionRef is returned. + // It has to wait a while after that. Then the property can be updated successfully. + stateConf := &pluginsdk.StateChangeConf{ + Delay: 1 * time.Minute, + Pending: []string{string(documentdb.ManagedCassandraProvisioningStateUpdating)}, + Target: []string{string(documentdb.ManagedCassandraProvisioningStateSucceeded)}, + Refresh: cassandraDatacenterStateRefreshFunc(ctx, client, *id), + MinTimeout: 15 * time.Second, + Timeout: d.Timeout(pluginsdk.TimeoutUpdate), + } - if _, err = stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for the updating of node_count in %q to take effect: %+v", id, err) - } + if _, err := stateConf.WaitForStateContext(ctx); err != nil { + return fmt.Errorf("waiting for update of %s: %+v", id, err) } return resourceCassandraDatacenterRead(d, meta) @@ -244,18 +299,14 @@ func resourceCassandraDatacenterDelete(d *pluginsdk.ResourceData, meta interface func cassandraDatacenterStateRefreshFunc(ctx context.Context, client *documentdb.CassandraDataCentersClient, id parse.CassandraDatacenterId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - nodeCount := "-1" - resp, err := client.Get(ctx, id.ResourceGroup, id.CassandraClusterName, id.DataCenterName) + res, err := client.Get(ctx, id.ResourceGroup, id.CassandraClusterName, id.DataCenterName) if err != nil { - return resp, nodeCount, fmt.Errorf("retrieving %q while waiting for node count to update: %+v", id, err) + return nil, "", fmt.Errorf("polling for %s: %+v", id, err) } - if props := resp.Properties; props != nil { - if props.NodeCount != nil { - nodeCount = strconv.Itoa(int(*props.NodeCount)) - } + if res.Properties != nil && res.Properties.ProvisioningState != "" { + return res, string(res.Properties.ProvisioningState), nil } - - return resp, nodeCount, nil + return nil, "", fmt.Errorf("unable to read provisioning state") } } diff --git a/internal/services/cosmos/cosmosdb_cassandra_datacenter_resource_test.go b/internal/services/cosmos/cosmosdb_cassandra_datacenter_resource_test.go index 57d15529d162..7d61290bb067 100644 --- a/internal/services/cosmos/cosmosdb_cassandra_datacenter_resource_test.go +++ b/internal/services/cosmos/cosmosdb_cassandra_datacenter_resource_test.go @@ -36,14 +36,14 @@ func testAccCassandraDatacenter_update(t *testing.T) { data.ResourceSequentialTest(t, r, []acceptance.TestStep{ { - Config: r.basic(data, 3), + Config: r.complete(data, 3), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), { - Config: r.basic(data, 5), + Config: r.update(data, 5), Check: acceptance.ComposeAggregateTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), @@ -66,26 +66,254 @@ func (t CassandraDatacenterResource) Exists(ctx context.Context, clients *client return utils.Bool(resp.ID != nil), nil } -func (CassandraDatacenterResource) basic(data acceptance.TestData, nodeCount int) string { +func (r CassandraDatacenterResource) basic(data acceptance.TestData, nodeCount int) string { + return fmt.Sprintf(` +%s + +resource "azurerm_cosmosdb_cassandra_datacenter" "test" { + name = "acctca-mi-dc-%d" + cassandra_cluster_id = azurerm_cosmosdb_cassandra_cluster.test.id + location = azurerm_cosmosdb_cassandra_cluster.test.location + delegated_management_subnet_id = azurerm_subnet.test.id + node_count = %d + disk_count = 4 + sku_name = "Standard_DS14_v2" + availability_zones_enabled = false +} +`, r.template(data), data.RandomInteger, nodeCount) +} + +func (r CassandraDatacenterResource) complete(data acceptance.TestData, nodeCount int) string { + return fmt.Sprintf(` +%s + +data "azurerm_client_config" "current" {} + +resource "azurerm_key_vault" "test" { + name = "acctestkv-%s" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + tenant_id = data.azurerm_client_config.current.tenant_id + sku_name = "standard" + soft_delete_retention_days = 7 + purge_protection_enabled = true +} + +resource "azurerm_key_vault_access_policy" "current_user" { + key_vault_id = azurerm_key_vault.test.id + + tenant_id = azurerm_key_vault.test.tenant_id + object_id = data.azurerm_client_config.current.object_id + + key_permissions = [ + "Create", + "Delete", + "Get", + "Purge", + "Recover", + "Update", + "WrapKey", + "UnwrapKey" + ] +} + +resource "azurerm_key_vault_access_policy" "system_identity" { + key_vault_id = azurerm_key_vault.test.id + + tenant_id = azurerm_key_vault.test.tenant_id + object_id = azurerm_cosmosdb_cassandra_cluster.test.identity.0.principal_id + + key_permissions = [ + "Create", + "Delete", + "Get", + "Purge", + "Recover", + "Update", + "WrapKey", + "UnwrapKey" + ] +} + +resource "azurerm_key_vault_key" "test" { + name = "acctestkey-%s" + key_vault_id = azurerm_key_vault.test.id + key_type = "RSA" + key_size = 2048 + + key_opts = [ + "decrypt", + "encrypt", + "sign", + "unwrapKey", + "verify", + "wrapKey", + ] + + depends_on = [ + azurerm_key_vault_access_policy.current_user, + azurerm_key_vault_access_policy.system_identity + ] +} + +resource "azurerm_cosmosdb_cassandra_datacenter" "test" { + name = "acctca-mi-dc-%d" + cassandra_cluster_id = azurerm_cosmosdb_cassandra_cluster.test.id + location = azurerm_cosmosdb_cassandra_cluster.test.location + delegated_management_subnet_id = azurerm_subnet.test.id + node_count = %d + disk_count = 4 + sku_name = "Standard_DS14_v2" + availability_zones_enabled = false + disk_sku = "P30" + backup_storage_customer_key_uri = azurerm_key_vault_key.test.id + managed_disk_customer_key_uri = azurerm_key_vault_key.test.id + base64_encoded_yaml_fragment = "Y29tcGFjdGlvbl90aHJvdWdocHV0X21iX3Blcl9zZWM6IDMyCmNvbXBhY3Rpb25fbGFyZ2VfcGFydGl0aW9uX3dhcm5pbmdfdGhyZXNob2xkX21iOiAxMDA=" + + depends_on = [ + azurerm_key_vault_key.test + ] +} +`, r.template(data), data.RandomString, data.RandomString, data.RandomInteger, nodeCount) +} + +func (r CassandraDatacenterResource) update(data acceptance.TestData, nodeCount int) string { + return fmt.Sprintf(` +%s + +data "azurerm_client_config" "current" {} + +resource "azurerm_key_vault" "test" { + name = "acctestkv-%s" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + tenant_id = data.azurerm_client_config.current.tenant_id + sku_name = "standard" + soft_delete_retention_days = 7 + purge_protection_enabled = true +} + +resource "azurerm_key_vault_access_policy" "current_user" { + key_vault_id = azurerm_key_vault.test.id + + tenant_id = azurerm_key_vault.test.tenant_id + object_id = data.azurerm_client_config.current.object_id + + key_permissions = [ + "Create", + "Delete", + "Get", + "Purge", + "Recover", + "Update", + "WrapKey", + "UnwrapKey" + ] +} + +resource "azurerm_key_vault_access_policy" "system_identity" { + key_vault_id = azurerm_key_vault.test.id + + tenant_id = azurerm_key_vault.test.tenant_id + object_id = azurerm_cosmosdb_cassandra_cluster.test.identity.0.principal_id + + key_permissions = [ + "Create", + "Delete", + "Get", + "Purge", + "Recover", + "Update", + "WrapKey", + "UnwrapKey" + ] +} + +resource "azurerm_key_vault_key" "test" { + name = "acctestkey-%s" + key_vault_id = azurerm_key_vault.test.id + key_type = "RSA" + key_size = 2048 + + key_opts = [ + "decrypt", + "encrypt", + "sign", + "unwrapKey", + "verify", + "wrapKey", + ] + + depends_on = [ + azurerm_key_vault_access_policy.current_user, + azurerm_key_vault_access_policy.system_identity + ] +} + +resource "azurerm_key_vault_key" "test2" { + name = "acctestkey2-%s" + key_vault_id = azurerm_key_vault.test.id + key_type = "RSA" + key_size = 2048 + + key_opts = [ + "decrypt", + "encrypt", + "sign", + "unwrapKey", + "verify", + "wrapKey", + ] + + depends_on = [azurerm_key_vault_key.test] +} + +resource "azurerm_cosmosdb_cassandra_datacenter" "test" { + name = "acctca-mi-dc-%d" + cassandra_cluster_id = azurerm_cosmosdb_cassandra_cluster.test.id + location = azurerm_cosmosdb_cassandra_cluster.test.location + delegated_management_subnet_id = azurerm_subnet.test.id + node_count = %d + disk_count = 4 + sku_name = "Standard_DS14_v2" + availability_zones_enabled = false + backup_storage_customer_key_uri = azurerm_key_vault_key.test2.id + managed_disk_customer_key_uri = azurerm_key_vault_key.test2.id + base64_encoded_yaml_fragment = "Z29tcGFjdGlvbl90aHJvdWdocHV0X21iX3Blcl9zZWM6IDMyCmNvbXBhY3Rpb25fbGFyZ2VfcGFydGl0aW9uX3dhcm5pbmdfdGhyZXNob2xkX21iOiAxMDA=" + + depends_on = [ + azurerm_key_vault_key.test, + azurerm_key_vault_key.test2 + ] +} +`, r.template(data), data.RandomString, data.RandomString, data.RandomString, data.RandomInteger, nodeCount) +} + +func (CassandraDatacenterResource) template(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { - features {} + features { + key_vault { + purge_soft_delete_on_destroy = false + purge_soft_deleted_keys_on_destroy = false + } + } } resource "azurerm_resource_group" "test" { - name = "acctestRG-ca-%[1]d" - location = "%[2]s" + name = "acctestRG-ca-%d" + location = "%s" } resource "azurerm_virtual_network" "test" { - name = "acctvn-%[1]d" + name = "acctvn-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name address_space = ["10.0.0.0/16"] } resource "azurerm_subnet" "test" { - name = "acctsub-%[1]d" + name = "acctsub-%d" resource_group_name = azurerm_resource_group.test.name virtual_network_name = azurerm_virtual_network.test.name address_prefixes = ["10.0.1.0/24"] @@ -102,24 +330,17 @@ resource "azurerm_role_assignment" "test" { } resource "azurerm_cosmosdb_cassandra_cluster" "test" { - name = "acctca-mi-cluster-%[1]d" + name = "acctca-mi-cluster-%d" resource_group_name = azurerm_resource_group.test.name location = azurerm_resource_group.test.location delegated_management_subnet_id = azurerm_subnet.test.id default_admin_password = "Password1234" - depends_on = [azurerm_role_assignment.test] -} + identity { + type = "SystemAssigned" + } -resource "azurerm_cosmosdb_cassandra_datacenter" "test" { - name = "acctca-mi-dc-%[1]d" - cassandra_cluster_id = azurerm_cosmosdb_cassandra_cluster.test.id - location = azurerm_cosmosdb_cassandra_cluster.test.location - delegated_management_subnet_id = azurerm_subnet.test.id - node_count = %[3]d - disk_count = 4 - sku_name = "Standard_DS14_v2" - availability_zones_enabled = false + depends_on = [azurerm_role_assignment.test] } -`, data.RandomInteger, data.Locations.Secondary, nodeCount) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger) } diff --git a/internal/services/cosmos/cosmosdb_cassandra_resource_test.go b/internal/services/cosmos/cosmosdb_cassandra_resource_test.go index 68529831ad81..aa2029cd63ef 100644 --- a/internal/services/cosmos/cosmosdb_cassandra_resource_test.go +++ b/internal/services/cosmos/cosmosdb_cassandra_resource_test.go @@ -16,8 +16,8 @@ func TestAccCassandraSequential(t *testing.T) { "requiresImport": testAccCassandraCluster_requiresImport, }, "dataCenter": { - "basic": testAccCassandraDatacenter_basic, - "requiresImport": testAccCassandraDatacenter_update, + "basic": testAccCassandraDatacenter_basic, + "update": testAccCassandraDatacenter_update, }, }) } diff --git a/internal/services/databricks/client/client.go b/internal/services/databricks/client/client.go index dd07f5773012..080f71dd5d04 100644 --- a/internal/services/databricks/client/client.go +++ b/internal/services/databricks/client/client.go @@ -1,8 +1,8 @@ package client import ( + "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/internal/common" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/sdk/2021-04-01-preview/workspaces" ) type Client struct { diff --git a/internal/services/databricks/databricks_customer_managed_key_resource.go b/internal/services/databricks/databricks_customer_managed_key_resource.go index 2aac0e734e2d..5165572d6175 100644 --- a/internal/services/databricks/databricks_customer_managed_key_resource.go +++ b/internal/services/databricks/databricks_customer_managed_key_resource.go @@ -8,12 +8,11 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/sdk/2021-04-01-preview/workspaces" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/validate" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/migration" keyVaultParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" @@ -35,37 +34,32 @@ func resourceDatabricksWorkspaceCustomerManagedKey() *pluginsdk.Resource { }, Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { - _, err := parse.CustomerManagedKeyID(id) + _, err := workspaces.ParseWorkspaceID(id) return err }, func(ctx context.Context, d *pluginsdk.ResourceData, meta interface{}) ([]*pluginsdk.ResourceData, error) { - client := meta.(*clients.Client).DataBricks.WorkspacesClient - // validate that the passed ID is a valid CMK configuration ID - customManagedKey, err := parse.CustomerManagedKeyID(d.Id()) + id, err := workspaces.ParseWorkspaceID(d.Id()) if err != nil { - return []*pluginsdk.ResourceData{d}, fmt.Errorf("parsing Databricks workspace customer managed key ID %q for import: %v", d.Id(), err) - } - - // convert the passed custom Managed Key ID to a valid workspace ID - workspace := workspaces.NewWorkspaceID(customManagedKey.SubscriptionId, customManagedKey.ResourceGroup, customManagedKey.CustomerMangagedKeyName) - - // validate that the workspace exists - if _, err = client.Get(ctx, workspace); err != nil { - return []*pluginsdk.ResourceData{d}, fmt.Errorf("retrieving the Databricks workspace customer managed key configuration(ID: %q) for workspace (ID: %q): %s", customManagedKey.ID(), workspace.ID(), err) + return []*pluginsdk.ResourceData{d}, err } // set the new values for the CMK resource - d.SetId(customManagedKey.ID()) - d.Set("workspace_id", workspace.ID()) + d.SetId(id.ID()) + d.Set("workspace_id", id.ID()) return []*pluginsdk.ResourceData{d}, nil }), + SchemaVersion: 1, + StateUpgraders: pluginsdk.StateUpgrades(map[int]pluginsdk.StateUpgrade{ + 0: migration.CustomerManagedKeyV0ToV1{}, + }), + Schema: map[string]*pluginsdk.Schema{ "workspace_id": { Type: pluginsdk.TypeString, Required: true, - ValidateFunc: validate.WorkspaceID, + ValidateFunc: workspaces.ValidateWorkspaceID, }, // Make this key vault key id and abstract everything from the string... @@ -81,7 +75,6 @@ func resourceDatabricksWorkspaceCustomerManagedKey() *pluginsdk.Resource { func databricksWorkspaceCustomerManagedKeyCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { workspaceClient := meta.(*clients.Client).DataBricks.WorkspacesClient keyVaultsClient := meta.(*clients.Client).KeyVault - subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -124,11 +117,9 @@ func databricksWorkspaceCustomerManagedKeyCreateUpdate(d *pluginsdk.ResourceData return fmt.Errorf("retrieving the Resource ID for the Key Vault at URL %q: %+v", key.KeyVaultBaseUrl, err) } - resourceID := parse.NewCustomerManagedKeyID(subscriptionId, id.ResourceGroupName, id.WorkspaceName) - if d.IsNewResource() { if workspace.Model != nil && workspace.Model.Properties.Parameters != nil && workspace.Model.Properties.Parameters.Encryption != nil { - return tf.ImportAsExistsError("azurerm_databricks_workspace_customer_managed_key", resourceID.ID()) + return tf.ImportAsExistsError("azurerm_databricks_workspace_customer_managed_key", id.ID()) } } @@ -149,13 +140,13 @@ func databricksWorkspaceCustomerManagedKeyCreateUpdate(d *pluginsdk.ResourceData }, } - props := getProps(workspace.Model, params) + props := getProps(*workspace.Model, params) if err = workspaceClient.CreateOrUpdateThenPoll(ctx, *id, props); err != nil { - return fmt.Errorf("creating/updating %s: %+v", resourceID, err) + return fmt.Errorf("creating/updating Customer Managed Key for %s: %+v", *id, err) } - d.SetId(resourceID.ID()) + d.SetId(id.ID()) return databricksWorkspaceCustomerManagedKeyRead(d, meta) } @@ -164,14 +155,12 @@ func databricksWorkspaceCustomerManagedKeyRead(d *pluginsdk.ResourceData, meta i ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.CustomerManagedKeyID(d.Id()) + id, err := workspaces.ParseWorkspaceID(d.Id()) if err != nil { return err } - workspaceId := workspaces.NewWorkspaceID(id.SubscriptionId, id.ResourceGroup, id.CustomerMangagedKeyName) - - resp, err := client.Get(ctx, workspaceId) + resp, err := client.Get(ctx, *id) if err != nil { if response.WasNotFound(resp.HttpResponse) { log.Printf("[DEBUG] %s was not found - removing from state", *id) @@ -207,11 +196,12 @@ func databricksWorkspaceCustomerManagedKeyRead(d *pluginsdk.ResourceData, meta i } if strings.EqualFold(keySource, string(workspaces.KeySourceMicrosoftPointKeyvault)) && (keyName == "" || keyVersion == "" || keyVaultURI == "") { - return fmt.Errorf("%s: `Workspace.WorkspaceProperties.Parameters.Encryption.Value(s)` were nil", *id) + d.SetId("") + return nil } d.SetId(id.ID()) - d.Set("workspace_id", workspaceId.ID()) + d.Set("workspace_id", id.ID()) if keyVaultURI != "" { key, err := keyVaultParse.NewNestedItemID(keyVaultURI, "keys", keyName, keyVersion) @@ -228,25 +218,17 @@ func databricksWorkspaceCustomerManagedKeyDelete(d *pluginsdk.ResourceData, meta ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.CustomerManagedKeyID(d.Id()) + id, err := workspaces.ParseWorkspaceID(d.Id()) if err != nil { return err } - workspaceID := workspaces.NewWorkspaceID(id.SubscriptionId, id.ResourceGroup, id.CustomerMangagedKeyName) - // Not sure if I should also lock the key vault here too - locks.ByName(workspaceID.WorkspaceName, "azurerm_databricks_workspace") - defer locks.UnlockByName(workspaceID.WorkspaceName, "azurerm_databricks_workspace") + locks.ByName(id.WorkspaceName, "azurerm_databricks_workspace") + defer locks.UnlockByName(id.WorkspaceName, "azurerm_databricks_workspace") - workspace, err := client.Get(ctx, workspaceID) + workspace, err := client.Get(ctx, *id) if err != nil { - if response.WasNotFound(workspace.HttpResponse) { - log.Printf("[DEBUG] %s was not found - removing from state", *id) - d.SetId("") - return nil - } - return fmt.Errorf("retrieving %s: %+v", *id, err) } @@ -265,16 +247,16 @@ func databricksWorkspaceCustomerManagedKeyDelete(d *pluginsdk.ResourceData, meta }, } - props := getProps(workspace.Model, params) + props := getProps(*workspace.Model, params) - if err = client.CreateOrUpdateThenPoll(ctx, workspaceID, props); err != nil { - return fmt.Errorf("creating/updating %s: %+v", workspaceID, err) + if err = client.CreateOrUpdateThenPoll(ctx, *id, props); err != nil { + return fmt.Errorf("removing Customer Managed Key from %s: %+v", *id, err) } return nil } -func getProps(workspace *workspaces.Workspace, params *workspaces.WorkspaceCustomParameters) workspaces.Workspace { +func getProps(workspace workspaces.Workspace, params *workspaces.WorkspaceCustomParameters) workspaces.Workspace { props := workspaces.Workspace{ Location: workspace.Location, Sku: workspace.Sku, diff --git a/internal/services/databricks/databricks_customer_managed_key_resource_test.go b/internal/services/databricks/databricks_customer_managed_key_resource_test.go index 817d607297e3..a35375172d87 100644 --- a/internal/services/databricks/databricks_customer_managed_key_resource_test.go +++ b/internal/services/databricks/databricks_customer_managed_key_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/sdk/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/databricks/databricks_workspace_data_source.go b/internal/services/databricks/databricks_workspace_data_source.go index 472478a12e71..0534c1471966 100644 --- a/internal/services/databricks/databricks_workspace_data_source.go +++ b/internal/services/databricks/databricks_workspace_data_source.go @@ -7,8 +7,8 @@ import ( "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/sdk/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" ) diff --git a/internal/services/databricks/databricks_workspace_private_endpoint_connection_data_source.go b/internal/services/databricks/databricks_workspace_private_endpoint_connection_data_source.go index f56c5750a699..7e6dac9bfb76 100644 --- a/internal/services/databricks/databricks_workspace_private_endpoint_connection_data_source.go +++ b/internal/services/databricks/databricks_workspace_private_endpoint_connection_data_source.go @@ -5,9 +5,9 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/sdk/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" ) diff --git a/internal/services/databricks/databricks_workspace_resource.go b/internal/services/databricks/databricks_workspace_resource.go index ea760699eb6b..3a930d0e060a 100644 --- a/internal/services/databricks/databricks_workspace_resource.go +++ b/internal/services/databricks/databricks_workspace_resource.go @@ -11,12 +11,11 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/sdk/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/validate" keyVaultParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate" @@ -44,7 +43,7 @@ func resourceDatabricksWorkspace() *pluginsdk.Resource { }, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.WorkspaceID(id) + _, err := workspaces.ParseWorkspaceID(id) return err }), diff --git a/internal/services/databricks/databricks_workspace_resource_test.go b/internal/services/databricks/databricks_workspace_resource_test.go index d24e11967da4..fe2090403e06 100644 --- a/internal/services/databricks/databricks_workspace_resource_test.go +++ b/internal/services/databricks/databricks_workspace_resource_test.go @@ -6,10 +6,10 @@ import ( "strings" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/sdk/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/databricks/migration/customer_managed_key.go b/internal/services/databricks/migration/customer_managed_key.go new file mode 100644 index 000000000000..dc10bb2bb6ae --- /dev/null +++ b/internal/services/databricks/migration/customer_managed_key.go @@ -0,0 +1,101 @@ +package migration + +import ( + "context" + "fmt" + "log" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" +) + +var _ pluginsdk.StateUpgrade = CustomerManagedKeyV0ToV1{} + +type CustomerManagedKeyV0ToV1 struct { +} + +func (c CustomerManagedKeyV0ToV1) Schema() map[string]*pluginsdk.Schema { + return map[string]*pluginsdk.Schema{ + "workspace_id": { + Type: pluginsdk.TypeString, + Required: true, + }, + + "key_vault_key_id": { + Type: pluginsdk.TypeString, + Required: true, + }, + } +} + +func (c CustomerManagedKeyV0ToV1) UpgradeFunc() pluginsdk.StateUpgraderFunc { + return func(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) { + // previously CustomerManagedKey used a virtual Resource ID - however this had a typo in the final segment `Mangaged` + // whilst we could look to update this to remove the typo - since other Customer Managed Key resources use the + // ID of the Parent resource being changed, we're going to update it to that instead. + + oldIdRaw := rawState["id"].(string) + oldId, err := parseLegacyCustomerManagedKeyId(oldIdRaw) + if err != nil { + return nil, fmt.Errorf("parsing existing Resource ID %q: %+v", oldIdRaw, err) + } + + newId := workspaces.NewWorkspaceID(oldId.SubscriptionId, oldId.ResourceGroup, oldId.CustomerMangagedKeyName) + log.Printf("[DEBUG] Updating the Resource ID from %q to %q", oldIdRaw, newId.ID()) + rawState["id"] = newId.ID() + + return rawState, nil + } +} + +type legacyCustomerManagedKeyId struct { + SubscriptionId string + ResourceGroup string + CustomerMangagedKeyName string +} + +func (id legacyCustomerManagedKeyId) String() string { + segments := []string{ + fmt.Sprintf("Customer Mangaged Key Name %q", id.CustomerMangagedKeyName), + fmt.Sprintf("Resource Group %q", id.ResourceGroup), + } + segmentsStr := strings.Join(segments, " / ") + return fmt.Sprintf("%s: (%s)", "Customer Managed Key", segmentsStr) +} + +func (id legacyCustomerManagedKeyId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Databricks/customerMangagedKey/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.CustomerMangagedKeyName) +} + +func parseLegacyCustomerManagedKeyId(input string) (*legacyCustomerManagedKeyId, error) { + id, err := resourceids.ParseAzureResourceID(input) + if err != nil { + return nil, err + } + + resourceId := legacyCustomerManagedKeyId{ + SubscriptionId: id.SubscriptionID, + ResourceGroup: id.ResourceGroup, + } + + if resourceId.SubscriptionId == "" { + return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + } + + if resourceId.ResourceGroup == "" { + return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") + } + + if resourceId.CustomerMangagedKeyName, err = id.PopSegment("customerMangagedKey"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &resourceId, nil +} diff --git a/internal/services/datafactory/data_factory_linked_service_azure_databricks_resource.go b/internal/services/datafactory/data_factory_linked_service_azure_databricks_resource.go index fa90f551856d..7b8e8c558605 100644 --- a/internal/services/datafactory/data_factory_linked_service_azure_databricks_resource.go +++ b/internal/services/datafactory/data_factory_linked_service_azure_databricks_resource.go @@ -7,9 +7,9 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/datafactory/mgmt/2018-06-01/datafactory" + "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - databricksValidator "github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/datafactory/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/datafactory/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" @@ -56,7 +56,7 @@ func resourceDataFactoryLinkedServiceAzureDatabricks() *pluginsdk.Resource { "msi_work_space_resource_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: databricksValidator.WorkspaceID, + ValidateFunc: workspaces.ValidateWorkspaceID, ExactlyOneOf: []string{"access_token", "msi_work_space_resource_id", "key_vault_password"}, }, diff --git a/internal/services/datafactory/data_factory_managed_private_endpoint_resource.go b/internal/services/datafactory/data_factory_managed_private_endpoint_resource.go index 0f4f969c1a99..62f14b352784 100644 --- a/internal/services/datafactory/data_factory_managed_private_endpoint_resource.go +++ b/internal/services/datafactory/data_factory_managed_private_endpoint_resource.go @@ -69,6 +69,7 @@ func resourceDataFactoryManagedPrivateEndpoint() *pluginsdk.Resource { "fqdns": { Type: pluginsdk.TypeList, Optional: true, + Computed: true, ForceNew: true, Elem: &pluginsdk.Schema{ Type: pluginsdk.TypeString, diff --git a/internal/services/datashare/data_share_account_data_source.go b/internal/services/datashare/data_share_account_data_source.go index 8399045c8e41..737bf54c4bab 100644 --- a/internal/services/datashare/data_share_account_data_source.go +++ b/internal/services/datashare/data_share_account_data_source.go @@ -5,7 +5,6 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/datashare/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/datashare/validate" diff --git a/internal/services/desktopvirtualization/parse/workspace_application_group_association.go b/internal/services/desktopvirtualization/parse/workspace_application_group_association.go index 70315a809e27..a63eb02518ee 100644 --- a/internal/services/desktopvirtualization/parse/workspace_application_group_association.go +++ b/internal/services/desktopvirtualization/parse/workspace_application_group_association.go @@ -6,7 +6,6 @@ import ( "github.com/hashicorp/go-azure-sdk/resource-manager/desktopvirtualization/2021-09-03-preview/applicationgroup" "github.com/hashicorp/go-azure-sdk/resource-manager/desktopvirtualization/2021-09-03-preview/workspace" - "github.com/hashicorp/terraform-provider-azurerm/internal/resourceid" ) diff --git a/internal/services/desktopvirtualization/virtual_desktop_scaling_plan_resource_test.go b/internal/services/desktopvirtualization/virtual_desktop_scaling_plan_resource_test.go index 190ec9c4c744..1c1a84f28a85 100644 --- a/internal/services/desktopvirtualization/virtual_desktop_scaling_plan_resource_test.go +++ b/internal/services/desktopvirtualization/virtual_desktop_scaling_plan_resource_test.go @@ -5,9 +5,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/go-azure-sdk/resource-manager/desktopvirtualization/2021-09-03-preview/scalingplan" - "github.com/google/uuid" + "github.com/hashicorp/go-azure-sdk/resource-manager/desktopvirtualization/2021-09-03-preview/scalingplan" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/devtestlabs/dev_test_lab_schedule_resource.go b/internal/services/devtestlabs/dev_test_lab_schedule_resource.go index afc322ea3251..4d51ed51bc8f 100644 --- a/internal/services/devtestlabs/dev_test_lab_schedule_resource.go +++ b/internal/services/devtestlabs/dev_test_lab_schedule_resource.go @@ -316,7 +316,7 @@ func resourceDevTestLabSchedulesRead(d *pluginsdk.ResourceData, meta interface{} } func resourceDevTestLabSchedulesDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Compute.VMExtensionClient + client := meta.(*clients.Client).DevTestLabs.LabSchedulesClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() @@ -325,12 +325,10 @@ func resourceDevTestLabSchedulesDelete(d *pluginsdk.ResourceData, meta interface return err } - future, err := client.Delete(ctx, id.ResourceGroup, id.LabName, id.ScheduleName) - if err != nil { + if _, err := client.Delete(ctx, id.ResourceGroup, id.LabName, id.ScheduleName); err != nil { return err } - - return future.WaitForCompletionRef(ctx, client.Client) + return nil } func expandDevTestScheduleRecurrenceDaily(recurrence interface{}) *dtl.DayDetails { diff --git a/internal/services/eventgrid/parse/event_subscription.go b/internal/services/eventgrid/parse/event_subscription.go index 0325cda6adb3..1efceb2c9787 100644 --- a/internal/services/eventgrid/parse/event_subscription.go +++ b/internal/services/eventgrid/parse/event_subscription.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" - "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" ) diff --git a/internal/services/eventhub/client/client.go b/internal/services/eventhub/client/client.go index 5c16fc8980bc..cb49f8333294 100644 --- a/internal/services/eventhub/client/client.go +++ b/internal/services/eventhub/client/client.go @@ -1,16 +1,16 @@ package client import ( + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/common" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationruleseventhubs" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationrulesnamespaces" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/checknameavailabilitydisasterrecoveryconfigs" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/consumergroups" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/disasterrecoveryconfigs" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/eventhubs" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2018-01-01-preview/eventhubsclusters" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2018-01-01-preview/networkrulesets" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2021-01-01-preview/namespaces" ) type Client struct { diff --git a/internal/services/eventhub/eventhub_authorization_rule_data_source.go b/internal/services/eventhub/eventhub_authorization_rule_data_source.go index 3dd7658bba36..64e12bbccc89 100644 --- a/internal/services/eventhub/eventhub_authorization_rule_data_source.go +++ b/internal/services/eventhub/eventhub_authorization_rule_data_source.go @@ -6,9 +6,9 @@ import ( "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationruleseventhubs" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" diff --git a/internal/services/eventhub/eventhub_authorization_rule_resource.go b/internal/services/eventhub/eventhub_authorization_rule_resource.go index 153d501b5715..70bda16dbdb7 100644 --- a/internal/services/eventhub/eventhub_authorization_rule_resource.go +++ b/internal/services/eventhub/eventhub_authorization_rule_resource.go @@ -6,12 +6,13 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationruleseventhubs" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/eventhubs" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/migration" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -29,6 +30,11 @@ func resourceEventHubAuthorizationRule() *pluginsdk.Resource { return err }), + SchemaVersion: 1, + StateUpgraders: pluginsdk.StateUpgrades(map[int]pluginsdk.StateUpgrade{ + 0: migration.EventHubAuthorizationRuleV0ToV1{}, + }), + Timeouts: &pluginsdk.ResourceTimeout{ Create: pluginsdk.DefaultTimeout(30 * time.Minute), Read: pluginsdk.DefaultTimeout(5 * time.Minute), diff --git a/internal/services/eventhub/eventhub_authorization_rule_resource_test.go b/internal/services/eventhub/eventhub_authorization_rule_resource_test.go index 31849bbaad99..1691d5debce6 100644 --- a/internal/services/eventhub/eventhub_authorization_rule_resource_test.go +++ b/internal/services/eventhub/eventhub_authorization_rule_resource_test.go @@ -6,10 +6,10 @@ import ( "strconv" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/eventhub/eventhub_cluster_data_source.go b/internal/services/eventhub/eventhub_cluster_data_source.go index d6fc175959f8..77a820e43a73 100644 --- a/internal/services/eventhub/eventhub_cluster_data_source.go +++ b/internal/services/eventhub/eventhub_cluster_data_source.go @@ -7,8 +7,8 @@ import ( "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2018-01-01-preview/eventhubsclusters" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" ) diff --git a/internal/services/eventhub/eventhub_cluster_resource.go b/internal/services/eventhub/eventhub_cluster_resource.go index 013a2878ddc0..7f0c66aae8b7 100644 --- a/internal/services/eventhub/eventhub_cluster_resource.go +++ b/internal/services/eventhub/eventhub_cluster_resource.go @@ -11,10 +11,10 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2018-01-01-preview/eventhubsclusters" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" diff --git a/internal/services/eventhub/eventhub_cluster_resource_test.go b/internal/services/eventhub/eventhub_cluster_resource_test.go index 28e681ef3ea9..b2ea26b1b249 100644 --- a/internal/services/eventhub/eventhub_cluster_resource_test.go +++ b/internal/services/eventhub/eventhub_cluster_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2018-01-01-preview/eventhubsclusters" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/eventhub/eventhub_consumer_group_data_source.go b/internal/services/eventhub/eventhub_consumer_group_data_source.go index 80f6e20e0a06..36cd7000e2b6 100644 --- a/internal/services/eventhub/eventhub_consumer_group_data_source.go +++ b/internal/services/eventhub/eventhub_consumer_group_data_source.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/consumergroups" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" diff --git a/internal/services/eventhub/eventhub_consumer_group_resource.go b/internal/services/eventhub/eventhub_consumer_group_resource.go index 15cac3c41e08..dca39f7408cc 100644 --- a/internal/services/eventhub/eventhub_consumer_group_resource.go +++ b/internal/services/eventhub/eventhub_consumer_group_resource.go @@ -6,10 +6,10 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/consumergroups" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" diff --git a/internal/services/eventhub/eventhub_consumer_group_resource_test.go b/internal/services/eventhub/eventhub_consumer_group_resource_test.go index 7ff0ec61ed6b..bbf4729347fe 100644 --- a/internal/services/eventhub/eventhub_consumer_group_resource_test.go +++ b/internal/services/eventhub/eventhub_consumer_group_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/consumergroups" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/eventhub/eventhub_data_source.go b/internal/services/eventhub/eventhub_data_source.go index ff9265240532..61929f149044 100644 --- a/internal/services/eventhub/eventhub_data_source.go +++ b/internal/services/eventhub/eventhub_data_source.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" ) diff --git a/internal/services/eventhub/eventhub_namespace_authorization_rule_data_source.go b/internal/services/eventhub/eventhub_namespace_authorization_rule_data_source.go index c5b9cb3ceff4..7ce5dc97a623 100644 --- a/internal/services/eventhub/eventhub_namespace_authorization_rule_data_source.go +++ b/internal/services/eventhub/eventhub_namespace_authorization_rule_data_source.go @@ -6,8 +6,8 @@ import ( "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationrulesnamespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" diff --git a/internal/services/eventhub/eventhub_namespace_authorization_rule_resource.go b/internal/services/eventhub/eventhub_namespace_authorization_rule_resource.go index e79bebcd087a..e5c7daacaff2 100644 --- a/internal/services/eventhub/eventhub_namespace_authorization_rule_resource.go +++ b/internal/services/eventhub/eventhub_namespace_authorization_rule_resource.go @@ -6,12 +6,12 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationrulesnamespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" diff --git a/internal/services/eventhub/eventhub_namespace_authorization_rule_resource_test.go b/internal/services/eventhub/eventhub_namespace_authorization_rule_resource_test.go index d5ff7d081d08..f9e5de6331b7 100644 --- a/internal/services/eventhub/eventhub_namespace_authorization_rule_resource_test.go +++ b/internal/services/eventhub/eventhub_namespace_authorization_rule_resource_test.go @@ -6,10 +6,10 @@ import ( "strconv" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationrulesnamespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/eventhub/eventhub_namespace_customer_managed_key_resource.go b/internal/services/eventhub/eventhub_namespace_customer_managed_key_resource.go index ed2bed13af23..57f22221db0f 100644 --- a/internal/services/eventhub/eventhub_namespace_customer_managed_key_resource.go +++ b/internal/services/eventhub/eventhub_namespace_customer_managed_key_resource.go @@ -7,10 +7,10 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2021-01-01-preview/namespaces" keyVaultParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" diff --git a/internal/services/eventhub/eventhub_namespace_customer_managed_key_resource_test.go b/internal/services/eventhub/eventhub_namespace_customer_managed_key_resource_test.go index 2ab1b7a9157c..cdf986900a3e 100644 --- a/internal/services/eventhub/eventhub_namespace_customer_managed_key_resource_test.go +++ b/internal/services/eventhub/eventhub_namespace_customer_managed_key_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/eventhub/eventhub_namespace_data_source.go b/internal/services/eventhub/eventhub_namespace_data_source.go index 1a8c4a70d28b..b4691fe125ba 100644 --- a/internal/services/eventhub/eventhub_namespace_data_source.go +++ b/internal/services/eventhub/eventhub_namespace_data_source.go @@ -9,9 +9,9 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationrulesnamespaces" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" ) diff --git a/internal/services/eventhub/eventhub_namespace_disaster_recovery_config_resource.go b/internal/services/eventhub/eventhub_namespace_disaster_recovery_config_resource.go index e3d6f586c3dc..436db25284c0 100644 --- a/internal/services/eventhub/eventhub_namespace_disaster_recovery_config_resource.go +++ b/internal/services/eventhub/eventhub_namespace_disaster_recovery_config_resource.go @@ -8,12 +8,12 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/checknameavailabilitydisasterrecoveryconfigs" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/disasterrecoveryconfigs" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" diff --git a/internal/services/eventhub/eventhub_namespace_disaster_recovery_config_resource_test.go b/internal/services/eventhub/eventhub_namespace_disaster_recovery_config_resource_test.go index 1214c0dbaf0f..49cd724c4c22 100644 --- a/internal/services/eventhub/eventhub_namespace_disaster_recovery_config_resource_test.go +++ b/internal/services/eventhub/eventhub_namespace_disaster_recovery_config_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/disasterrecoveryconfigs" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/eventhub/eventhub_namespace_resource.go b/internal/services/eventhub/eventhub_namespace_resource.go index bdfceb21df97..fdc9ba6d3926 100644 --- a/internal/services/eventhub/eventhub_namespace_resource.go +++ b/internal/services/eventhub/eventhub_namespace_resource.go @@ -14,14 +14,13 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - legacyIdentity "github.com/hashicorp/terraform-provider-azurerm/internal/identity" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationrulesnamespaces" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2018-01-01-preview/eventhubsclusters" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2018-01-01-preview/networkrulesets" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" @@ -104,7 +103,7 @@ func resourceEventHubNamespace() *pluginsdk.Resource { ValidateFunc: eventhubsclusters.ValidateClusterID, }, - "identity": commonschema.SystemAssignedIdentityOptional(), + "identity": commonschema.SystemOrUserAssignedIdentityOptional(), "maximum_throughput_units": { Type: pluginsdk.TypeInt, @@ -274,7 +273,7 @@ func resourceEventHubNamespaceCreate(d *pluginsdk.ResourceData, meta interface{} autoInflateEnabled := d.Get("auto_inflate_enabled").(bool) zoneRedundant := d.Get("zone_redundant").(bool) - identity, err := expandEventHubIdentity(d.Get("identity").([]interface{})) + identity, err := identity.ExpandSystemAndUserAssignedMap(d.Get("identity").([]interface{})) if err != nil { return fmt.Errorf("expanding `identity`: %+v", err) } @@ -354,7 +353,7 @@ func resourceEventHubNamespaceUpdate(d *pluginsdk.ResourceData, meta interface{} autoInflateEnabled := d.Get("auto_inflate_enabled").(bool) zoneRedundant := d.Get("zone_redundant").(bool) - identity, err := expandEventHubIdentity(d.Get("identity").([]interface{})) + identity, err := identity.ExpandSystemAndUserAssignedMap(d.Get("identity").([]interface{})) if err != nil { return fmt.Errorf("expanding `identity`: %+v", err) } @@ -459,7 +458,12 @@ func resourceEventHubNamespaceRead(d *pluginsdk.ResourceData, meta interface{}) d.Set("capacity", sku.Capacity) } - if err := d.Set("identity", flattenEventHubIdentity(model.Identity)); err != nil { + identity, err := identity.FlattenSystemAndUserAssignedMap(model.Identity) + if err != nil { + return fmt.Errorf("setting `identity`: %+v", err) + } + + if err := d.Set("identity", identity); err != nil { return fmt.Errorf("setting `identity`: %+v", err) } @@ -621,7 +625,7 @@ func expandEventHubNamespaceNetworkRuleset(input []interface{}) *networkrulesets return &ruleset } -func flattenEventHubNamespaceNetworkRuleset(ruleset networkrulesets.NamespacesGetNetworkRuleSetResponse) []interface{} { +func flattenEventHubNamespaceNetworkRuleset(ruleset networkrulesets.NamespacesGetNetworkRuleSetOperationResponse) []interface{} { if ruleset.Model == nil || ruleset.Model.Properties == nil { return nil } @@ -674,33 +678,6 @@ func flattenEventHubNamespaceNetworkRuleset(ruleset networkrulesets.NamespacesGe }} } -func expandEventHubIdentity(input []interface{}) (*legacyIdentity.SystemUserAssignedIdentityMap, error) { - expanded, err := identity.ExpandSystemAssigned(input) - if err != nil { - return nil, err - } - - result := legacyIdentity.SystemUserAssignedIdentityMap{ - Type: legacyIdentity.Type(string(expanded.Type)), - PrincipalId: &expanded.PrincipalId, - TenantId: &expanded.TenantId, - } - return &result, nil -} - -func flattenEventHubIdentity(input *legacyIdentity.SystemUserAssignedIdentityMap) []interface{} { - if input == nil { - return []interface{}{} - } - - legacyConfig := input.ToExpandedConfig() - return identity.FlattenSystemAssigned(&identity.SystemAssigned{ - Type: identity.Type(string(legacyConfig.Type)), - PrincipalId: legacyConfig.PrincipalId, - TenantId: legacyConfig.TenantId, - }) -} - // The resource id of subnet_id that's being returned by API is always lower case & // the default caseDiff suppress func is not working in TypeSet func resourceVnetRuleHash(v interface{}) int { diff --git a/internal/services/eventhub/eventhub_namespace_resource_test.go b/internal/services/eventhub/eventhub_namespace_resource_test.go index e559654a6a2e..7793f6235337 100644 --- a/internal/services/eventhub/eventhub_namespace_resource_test.go +++ b/internal/services/eventhub/eventhub_namespace_resource_test.go @@ -6,10 +6,10 @@ import ( "regexp" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/eventhub/eventhub_resource.go b/internal/services/eventhub/eventhub_resource.go index bf3b15017319..536be3754628 100644 --- a/internal/services/eventhub/eventhub_resource.go +++ b/internal/services/eventhub/eventhub_resource.go @@ -5,13 +5,12 @@ import ( "log" "time" - "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" - "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/eventhubs" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2021-01-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" diff --git a/internal/services/eventhub/eventhub_resource_test.go b/internal/services/eventhub/eventhub_resource_test.go index 7042d29e8b39..579c92c652ae 100644 --- a/internal/services/eventhub/eventhub_resource_test.go +++ b/internal/services/eventhub/eventhub_resource_test.go @@ -6,10 +6,10 @@ import ( "strconv" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" diff --git a/internal/services/eventhub/migration/consumer_group.go b/internal/services/eventhub/migration/consumer_group.go index 8112b2ee5c1d..08a09b63ff98 100644 --- a/internal/services/eventhub/migration/consumer_group.go +++ b/internal/services/eventhub/migration/consumer_group.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/consumergroups" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) diff --git a/internal/services/eventhub/migration/eventhub_authorization_rule.go b/internal/services/eventhub/migration/eventhub_authorization_rule.go new file mode 100644 index 000000000000..94868d53184f --- /dev/null +++ b/internal/services/eventhub/migration/eventhub_authorization_rule.go @@ -0,0 +1,60 @@ +package migration + +import ( + "context" + "log" + + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" +) + +var _ pluginsdk.StateUpgrade = EventHubAuthorizationRuleV0ToV1{} + +type EventHubAuthorizationRuleV0ToV1 struct{} + +func (EventHubAuthorizationRuleV0ToV1) Schema() map[string]*pluginsdk.Schema { + s := map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + }, + + "namespace_name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + }, + + "eventhub_name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + }, + } + return s +} + +func (EventHubAuthorizationRuleV0ToV1) UpgradeFunc() pluginsdk.StateUpgraderFunc { + return func(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) { + + oldID := rawState["id"].(string) + + newID, err := eventhubs.ParseEventhubAuthorizationRuleIDInsensitively(oldID) + if err != nil { + return nil, err + } + + log.Printf("[DEBUG] Updating ID from %q to %q", oldID, newID) + + rawState["id"] = newID.ID() + + return rawState, nil + } +} diff --git a/internal/services/firewall/firewall_policy_resource.go b/internal/services/firewall/firewall_policy_resource.go index 3371a139224b..e9086275bc69 100644 --- a/internal/services/firewall/firewall_policy_resource.go +++ b/internal/services/firewall/firewall_policy_resource.go @@ -258,7 +258,7 @@ func expandFirewallPolicyDNSSetting(input []interface{}) *network.DNSSettings { raw := input[0].(map[string]interface{}) output := &network.DNSSettings{ - Servers: utils.ExpandStringSlice(raw["servers"].(*pluginsdk.Set).List()), + Servers: utils.ExpandStringSlice(raw["servers"].([]interface{})), EnableProxy: utils.Bool(raw["proxy_enabled"].(bool)), } @@ -635,7 +635,7 @@ func resourceFirewallPolicySchema() map[string]*pluginsdk.Schema { Elem: &pluginsdk.Resource{ Schema: map[string]*pluginsdk.Schema{ "servers": { - Type: pluginsdk.TypeSet, + Type: pluginsdk.TypeList, Optional: true, Elem: &pluginsdk.Schema{ Type: pluginsdk.TypeString, diff --git a/internal/services/firewall/firewall_policy_resource_test.go b/internal/services/firewall/firewall_policy_resource_test.go index e28ce0df6b24..77610b0cec81 100644 --- a/internal/services/firewall/firewall_policy_resource_test.go +++ b/internal/services/firewall/firewall_policy_resource_test.go @@ -54,6 +54,10 @@ func TestAccFirewallPolicy_complete(t *testing.T) { Config: r.complete(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), + check.That(data.ResourceName).Key("dns.0.servers.#").HasValue("3"), + check.That(data.ResourceName).Key("dns.0.servers.0").HasValue("1.1.1.1"), + check.That(data.ResourceName).Key("dns.0.servers.1").HasValue("3.3.3.3"), + check.That(data.ResourceName).Key("dns.0.servers.2").HasValue("2.2.2.2"), ), }, data.ImportStep(), @@ -248,7 +252,7 @@ resource "azurerm_firewall_policy" "test" { fqdns = ["foo.com", "bar.com"] } dns { - servers = ["1.1.1.1", "2.2.2.2"] + servers = ["1.1.1.1", "3.3.3.3", "2.2.2.2"] proxy_enabled = true } tags = { @@ -415,10 +419,9 @@ resource "azurerm_user_assigned_identity" "test" { } resource "azurerm_key_vault_access_policy" "test" { - key_vault_id = azurerm_key_vault.test.id - application_id = azurerm_user_assigned_identity.test.client_id - tenant_id = data.azurerm_client_config.current.tenant_id - object_id = azurerm_user_assigned_identity.test.principal_id + key_vault_id = azurerm_key_vault.test.id + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = azurerm_user_assigned_identity.test.principal_id key_permissions = [ "Backup", @@ -499,26 +502,10 @@ resource "azurerm_key_vault_certificate" "test" { certificate { contents = filebase64("testdata/certificate.pfx") + password = "somepassword" } - certificate_policy { - issuer_parameters { - name = "Self" - } - - key_properties { - exportable = true - key_size = 2048 - key_type = "RSA" - reuse_key = false - } - - secret_properties { - content_type = "application/x-pkcs12" - } - } - - depends_on = [azurerm_key_vault_access_policy.test2] + depends_on = [azurerm_key_vault_access_policy.test, azurerm_key_vault_access_policy.test2] } `, data.RandomInteger, "westeurope", data.RandomInteger, data.RandomInteger) } diff --git a/internal/services/firewall/firewall_resource.go b/internal/services/firewall/firewall_resource.go index 6624a11d54c0..e65975c52606 100644 --- a/internal/services/firewall/firewall_resource.go +++ b/internal/services/firewall/firewall_resource.go @@ -6,14 +6,11 @@ import ( "strings" "time" + "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - "github.com/hashicorp/go-azure-helpers/resourcemanager/zones" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/firewall/testdata/HOWTO.md b/internal/services/firewall/testdata/HOWTO.md index 0ec5e949e0f9..54a58a4b85c8 100644 --- a/internal/services/firewall/testdata/HOWTO.md +++ b/internal/services/firewall/testdata/HOWTO.md @@ -1,11 +1,13 @@ # How Certificates were generated ## How Key and Certificate was generated + ```bash -openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem +openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem -config $(pwd)/openssl.cnf -extensions rootCA_ext -subj "/DC=org/DC=OpenSSL/DC=users/CN=John Doe" -passin pass:somepassword ``` ## How PFX was generated from above Key and Certificate + ```bash -openssl pkcs12 -export -out certificate.pfx -inkey key.pem -in cert.pem -``` \ No newline at end of file +openssl pkcs12 -export -out certificate.pfx -inkey key.pem -in cert.pem -passout pass:somepassword +``` diff --git a/internal/services/firewall/testdata/cert.pem b/internal/services/firewall/testdata/cert.pem index a0334a6afa4d..0947082fdecf 100644 --- a/internal/services/firewall/testdata/cert.pem +++ b/internal/services/firewall/testdata/cert.pem @@ -1,22 +1,22 @@ -----BEGIN CERTIFICATE----- -MIIDkjCCAnoCCQDY1A4aUvTZ0TANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMC -Q0gxCzAJBgNVBAgMAlpIMQswCQYDVQQHDAJaSDESMBAGA1UECgwJVGVycmFmb3Jt -MQ4wDAYDVQQLDAVBenVyZTEYMBYGA1UEAwwPd3d3LmNvbnRvc28uY29tMSMwIQYJ -KoZIhvcNAQkBFhR3aGF0ZXZlckBjb250b3NvLmNvbTAeFw0yMTA0MjIxOTU4MTBa -Fw0zMTA0MjAxOTU4MTBaMIGKMQswCQYDVQQGEwJDSDELMAkGA1UECAwCWkgxCzAJ -BgNVBAcMAlpIMRIwEAYDVQQKDAlUZXJyYWZvcm0xDjAMBgNVBAsMBUF6dXJlMRgw -FgYDVQQDDA93d3cuY29udG9zby5jb20xIzAhBgkqhkiG9w0BCQEWFHdoYXRldmVy -QGNvbnRvc28uY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5rx3 -fTN0UUV1ktetzM2AEIJ4ZKQlibrLtVORPX2LQp2Vl/n74DPD2Re/ZgO2NtjhjItY -O65ZSqOgGz3R8ED4r12AokLCFmqhBnnr4IybeaQos7prjLKwSIyj5NbVMGuzNO6P -55W1zTMfV+CstbCtXtRPa7zizXjYbT3dfpw8FgJLh9sVWaiCO34Nu9PWF9NRIlzI -e/Ek3ss/JnNqskH+xnxgxq68slaZa4qojBjiLl/IdIs4A9DtyJnFd99xuh8nShMg -4ykccPr9/+YBaz8/Ef7/zmXj3g9DLTrIa7JV6s80V5oVINaF7KXu9jmjD+a03SsR -/8eKX6K+xDBtqxpz8wIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAOGe2knCVxje06 -ihfhzprg7lTM7GCgiXqa4fdCVwq0hJAYpMg29F7Df3OE/zVD/mzdRWZe2yVTY47f -YFEfDKMmkGepgqICs0wTfhBSham8vkk2yDcoT01Lar+Im3GToP3JSM5YFbqxam0R -/AVskE5aHQ+tIGUwcuwWhjjKQuWua59tI0USjgGaK3cZ5tyFOQPcE3ZFzndWM3Rz -ojNHH5UJOT7zt4RebBzGRpcNdrbkOtVkRVZIwH0wJfm44zR+L36UhpXUd8XGKvua -KFlqJhw/8UtYzXXX5bwHb/JTkOLUbs8gobG23lFhxXG5QhqtwqYnHXRw9Jhclv8p -weEgmhnj +MIIDljCCAn6gAwIBAgIJAJy4q/m3yCkUMA0GCSqGSIb3DQEBDQUAMFgxEzARBgoJ +kiaJk/IsZAEZFgNvcmcxFzAVBgoJkiaJk/IsZAEZFgdPcGVuU1NMMRUwEwYKCZIm +iZPyLGQBGRYFdXNlcnMxETAPBgNVBAMMCEpvaG4gRG9lMB4XDTIyMDYyOTA2MTcw +NloXDTMyMDYyNjA2MTcwNlowWDETMBEGCgmSJomT8ixkARkWA29yZzEXMBUGCgmS +JomT8ixkARkWB09wZW5TU0wxFTATBgoJkiaJk/IsZAEZFgV1c2VyczERMA8GA1UE +AwwISm9obiBEb2UwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDFwb1B +jG4omFnZEuyUDH6uAPxCAqr+OKWEfM+2w/XJcrDuD+w08WwLAxbq6kSTG5LVtbMX +M9BvdoMNLlixrf2h2LcWvwgjIP/9Uj7XGa2P32Q7WVlRp62OjCu/c/kG6bM+NeCM +yV39nz7bn1uZdfeUvmWV44dDdpBdZw4jfHrIlr8WW33p8VHot+TZlecyfzj8rs2B +csReuGYHIjpN0AWLKrxbyyxd5yKaBrQLrxsHVaU1fpFZxTn2YLXlGmfeQ4EaZj1S +VriJ+zFRo5CkN6ZO0CqUcGO/BstgcqSFt3+LyliYI8zRSGv6kY8E4cRzDINWMe0R +PIqknStANcRhWIj7AgMBAAGjYzBhMB0GA1UdDgQWBBSRapPb7bWCxb2IPNseoSVX +9eL8kTAfBgNVHSMEGDAWgBSRapPb7bWCxb2IPNseoSVX9eL8kTAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQ0FAAOCAQEAaRcwHlsB +v2iBNM0jEbCbGLIuNIpE0NxsxpLhxWjl9Ds2u3ULqvASVvBJuDASjZofq9wNrAm5 +YZnjQ5ehbsUvL1XgIDcnG38prZMP8s8CrBakJUZp/FX227Xo+ApBtKZkkYv2AfBf +DLTtRL4PsIilshPAc4WyKYlSH93ih4vpu/WUWbQLjdLWgsCoKxsy5ZWwmPUmlitV +N5VhOAF//bO/HlxWO2pfc1GZZ2iG5dByi82yZLtjYjdVBHM3iXV5mTCG6AkZBRci +nM+TLi6OigDfpVAbxc1Rt4m/klGN+3uYc5UwVYF5tKtBG786RmL319hRI8NY5HzU +Ot7NFKpEZ4k6Xg== -----END CERTIFICATE----- diff --git a/internal/services/firewall/testdata/certificate.pfx b/internal/services/firewall/testdata/certificate.pfx index cbf0f300daebf9066003876079b8c26512e8bc7d..dc63660ac033f05281663f6c647a01b8a2c3b6c6 100644 GIT binary patch delta 2458 zcmV;L31#-x6WtR)FoFr$0s#Xsf(f4n2`Yw2hW8Bt2LYgh36KPW35+m;35YO)1V07| zDuzgg_YDCD2B3ljFff7yECK-lFoFankw6`PuuPQO+mNXg0s;sCfPw?~JN8oGTTm5! z{#LLKQL-f8v91yu@`VfM82K@y5$7J9R)ka|A!M-rl3VCgbigxZG^t<77VC{rkx4N0|FMRJWVMu`DwR?c8a|P0f}4Gf089KkAx+_I0PB>8Kp8DnCKy` zWl4;_O1+oSuT##7P~4GRiADB*TSrjsGsS1IEAX^633_e6`IAbg*nLI`RA*<}afvRd z^>$uopICnZrF*eCDwM>hq6Ufe??6|Uv@=~j)+fuQ_?fTV*zj^!EC;Ea^M_~)WQ{Cim63ZXvPx^Zl*q#zLfi5QACfvRGp|lvj zx$CqfnaZN4XB^v-34b-Njhy^2PpD$6X26O(p5n62-G|ALr^l0jok?)eA}gZQOdZ<% z-xCP`b97Cx)xt6A(-d}i4y5F}^z^DBFWspKSv-P`Cau}C%q^X#@6+C|_p}*=!83!( z$QZ?=(Xn#*m2Yx$LR?QrgL%Ohi^!yQ_Q(Y*Rhi9?ZEYK@HTpflRuBbDgo35!MnGjY zTA%w?D(p^-viWEbSDKk%A7pep0xr$U8?Y zQCW*{fG9`mBGLr7VHMS?6b-Z4Atx3RlizmtBC4b+?6>E&QUNA*H@Xd$w=Q-ru8Q<0 zE;DL3l6)NzW;yt=FiX6keIO2NwQyXbB468Ys;z_^m~q_Xwp;SwSRk$Pl61+zR9 zc9Dk&e-gE8(1Dodc0bUFI&}V4Z%MDPnp}SNwZ73YcR6Ckv=SEvgKRN)C3+e@s<6u5{N+Jl z=^K%!Hxj(bmVc*!r!<#w%#`+kN8AceNqli(e=|EPRgUZnxXIyNt$)a^C*cI|$iSVW zwQP(|=juIFoy<&&avJ36|7mP~fnMuEbSExH!Wf*CuLLku1P(Z0fE5V4OsfF=n&tZ- zI+asEcrG>a?5lNMl9`|Z96eGWYR1^7jyMVtdOq-B6Bv&ChPr4y$EiGnP7S#8Oa7~V ze*xmOXLC;!d2K&R*7FJ^PvF8HVgdms4CUI;hDI)XvB~3v4A=DASAb-O)SW zy<}aZeCwrpij9;Nin3`472NmHmkF6OsWlS;g z5U^pvm}+2BJC|~Zg@Of>XHY;Vcv}Y4UFkb95V6>oIU;1_vt;XO{jk(_Agdx|il$jd zH3s+AUDB{5q~bL`g?gbus}(MaW-=NnAMd+*2KDlc86ko1dVCG~$LQ*^U|#Lyf6YGL z@86wj1G>9{Ycf$WBb$2xZG#pTC-UKw{Q{THr9kyZW}aOkQnI!lli?NSlq zrOdQ%$6srSR2l_tPCb1;PVePmQTKjMfbk~;L@FfAt2;J|?@xcNq;7!Te{U6G|7^Y4 z{*Fn5lZDBC@X+P4kDon%F@ott9{s$=g?=i$d2X>FP5&}-3Ag;T)>Xex2pXMIO+< z^sAK99E^7%{N)T%lCr8~e-BinOC(1JnN8$z{VE9m#kbs%ch&dDPZfCtG7nq_26}8p zZBbB}>OPtLvDJSMAA892jyU~9jp`h85ne-44iKlI3af>jFGcfAFkyFK&Kn;6UYZ z^AN54T`4Z;(I7;zxE9e8XPZktY)Vzuz@vcGeAKpB{&Iy|$zZTl9Hkp=I_xLd-Fe3&DDuzgg_YDCF6)_eB z6f}HFAE~D!OLSdFJQoPMZJYzISoSb6Fd;Ar1_dh)0|FWa00b1I5!fpMRLR_0uTI&6 Y=L%$`=3%k~2z%L^jvqVX*8&0v0DhU5&j0`b delta 2450 zcmV;D32pY>6V($yFoFru0s#Xsf(e%f2`Yw2hW8Bt2LYgh35W!O34}0$34kzy1UCi= zDuzgg_YDCD2B3ljC@_KqBmw~dFoFafkw6`PYOSCKJCoaS0s;sCfPw??q|YyJ{Jpy% zXO6(}9{h+IhBvC|jDXSe`J`nbPF~zpdk-HQW%!uf=*NQCKr)}}PzS70l|B4z>lD_o znmiujB6Lw*Vo4hRWmC6~Mx}#p`KzGhq))d({FeIL+JH#*uF*xKBbM%Zizxu5v5&cb zy6k!DhPDS5Wt(0UA;Jg?v65avlM&ve-}t71K=?Cw%t2G4qwOYw)9aV>CqYD5y05wp zee^Ej@#y9U5F3Uz&g1Zb!L_Ot;C*#OwzYFP=)CL1RiiN1&^zg09C4kMGaT}!hk}Nr z-Jhb01^h+FEdpCSzhP=(&>JID{)mr%aNE_k+%d5&w;ti*p2xje|Gqz3kHfgPD(8;9 zGNID^z`S6n*dM0)7BvTEo{>6cS2xW;)d)Tuv=mlW!<}Ivq84&QZ#Y8)MhrtnQNaCP z#G^4+3E!qN{cc5>0$ZJyE5v-BoO~q+%+@%Unj(uL$OjZ9h-Gal9dsp&rLSFo2u5Eh z;TY0UOPTWXhrY5O@NLN}aBcS_7ZP!7p-^by5(F**po!K7wwt0a!X5%4Owb0Rv8kSl!!VnWWRi zw62*pxQJy#t`~*+_GLO0w5}w7QrqO)6jZtn1n<#e>f_kzfSomP&(^O0QM+@2e@0|M z@MfR=HkS~8iv5G@s!yT?N>)ki?9M~lI_zF)Y0dRvqrY;fUsB4jl*fO~EqEv~ zK*-IY%p0jq8-WB!zmE6~X~AM1Jcu_^J9aWSVmeXZ*+;BvG!f;u?0}blA=pK9;`V%g za#rSlA?&qI!KZ?Qv1tPq_SD};4az&okC3!>@xsZ9@Z17D^@a*AeB(lNE!r0w11_{$ zbOb)T^mo!Yn%CXwXO?JBhT*CX!LV|cl-@advNw6yTCBgZnt;v{zx|Ie#<0bj6()*h zR3de0nfAp9_iBEPmh0R3^jr)phq`e=%$O$cG-)a@y)- zrPZ$)?b!jAG4g0GR=+X4rFImfAXCIzrZ#>t*cfbB`@_$^UA zOK!?|nTr$PT$Vx~Zn4#Q|s_ z5Qq=541%0dp_TjxVkPUeiLa8+d4s=9dIa+t_kd~aWIGJue71I0mR%$(e_x*%qxZpQ zN_{wo#wV|MzU6zch2yfKZJM5)i;{XmG(UH6)Oe8AkC~esgDZb^#i516d)P`#e}=HX z!`mmHElsJtS-n**FHg*YFXPV~zP#g8n?52RX| znanv+d&f3*!-xmwo15bS;$3K3V!rA@GP@?GsTFc(4IVc!yfR7d-=rNL*nOpf=wsDB zR6$ot`5{4HTOMI#Sq!7Vh&2HvE2#ndrHBHBHE zT{QCwzjHBC&_#;*da<-Ej2L>3N79uDrDH><)8K?Z3km4u%vfX+koBg!e@+aW7M)ZM zXhh(_WH;mQR8G73KMqdI2V*5cTzq?PqTIn zbgE<;p+KOC|7Ygzeb3Nu%URxhd-jqwXUzDruzHp9{n7p zP{kPd@xR{o%E1jl_OlgUm(x2~gx43xC9bchk)Lr>E7g8>>LYmLfB(AmRJL>!^SN{V zsi)ECs+{VW=5K+)eqtPrxLH{Lygmsvf5^LaE6S&VpwTKRlJ$XN2u70BNT0ytFQ;AR zRHxRs?L+%3qR@TUlB44P<&8e)9~@36O=79BGt06A`DPHV znkI_MZNnX&9f8hob-udTcaZmnr+jEC>~BY+dIZgc5)ut7`=)`p2a-;V?mbGs%$5cGxl>CP^9#G^i>ftnHa797Sqo9S~j-=_+^`H5|op37c)tZ2B9?=jt(4|M+CAma~=bNuP zUCMimkL=eHe`y^rRhkLv*kci{qCjzgM4GU7@Q)7U5cfsGmFjPl$i&iX1dXj1b`jV) z5Q=B&=-fP=u=MJ-HMTNTsEdx41?#EvHZe!Z_T=@igyk13#1FLPq;8;gDFD$-U`O`) zft4FqkS45xa~T;_Ic6ZxF^ zWV0+aDl=gRlJkx6s97eu$bJX*Xz6R0npE#jSa7V%z{jQrEg^gxO*?${YqkI1UShmh zNEr%_4Ovf$I~g~PO1sifj?x)kV{mkaTb?l`Fe3&DDuzgg_YDCF6)_eB6p76_S}qAv zwy^&xJfKi?{}%8j!nQCmFd;Ar1_dh)0|FWa00b1w`5Ru}8}{ZlTKdt+IRs|agZ+~P Q2*9SIrn~R4NCE-~01ukKy#N3J diff --git a/internal/services/firewall/testdata/key.pem b/internal/services/firewall/testdata/key.pem index 87761f711640..19beac2bbd06 100644 --- a/internal/services/firewall/testdata/key.pem +++ b/internal/services/firewall/testdata/key.pem @@ -1,28 +1,28 @@ -----BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDmvHd9M3RRRXWS -163MzYAQgnhkpCWJusu1U5E9fYtCnZWX+fvgM8PZF79mA7Y22OGMi1g7rllKo6Ab -PdHwQPivXYCiQsIWaqEGeevgjJt5pCizumuMsrBIjKPk1tUwa7M07o/nlbXNMx9X -4Ky1sK1e1E9rvOLNeNhtPd1+nDwWAkuH2xVZqII7fg2709YX01EiXMh78STeyz8m -c2qyQf7GfGDGrryyVplriqiMGOIuX8h0izgD0O3ImcV333G6HydKEyDjKRxw+v3/ -5gFrPz8R/v/OZePeD0MtOshrslXqzzRXmhUg1oXspe72OaMP5rTdKxH/x4pfor7E -MG2rGnPzAgMBAAECggEAAXJvIWbgNN5FpX0axu0G/5OB48evwJReUK3MfGE8LVfF -p2VW8goBEWx3s9EUJHXpvDLng8BNKQ2rpGAX3/TYWmkwtFPM2c0jY2ICW68mDnY8 -Fxx1LjW0q0/Oe1HpllsmjY9tcZtbv4SxjqCHFMCd5blZIijWF0nJua2opPGf4tdv -yvN/D9HYPdRlynj6SjUij0rR2PFN134LLaKhRrAsaeKHqSk+Pngxt6HStRLPSnN+ -dqk+6rA0fJ97YXeiNRjYfRbJEMOedJFW5wavddIXkNzI/3iwrDc5P0A+9X+SbIGm -6BlKNy6EbFtEsbsbdcefZaVuaRXEVNsiRXBoUHjkYQKBgQD7yZWZDPr0JWtL+Mav -dewbQUd8xVMzAc9r2mjRCNJi5qanQRDNIDhkYkNVrpBnsKpCe8cDRb3SaawTqYEv -ASCPGOU92ooQ1AMKMwETaCsrSDAEwpS6NdCSuYZbu6yGqWc8/v4Oi8ZAv10I1TJP -2WaG2PkvfOpsvXs8ixQWZ4f5QwKBgQDqmLgV86pnDFUEfW8W8f0n6PG0gPSofcF7 -DKDEcRj3ZmkBWDUKiICBInrPgQaxw5rLA4lL1GwRgxMQg51fit52mQcsMK56/aQx -3BmSIoA3Uf+mzHp+bSL+o1vYmoOtklUF09DGIf+y4XyQy9GjojSzxCVkXqBwFldj -9+jL0NXXkQKBgECyo8YYF8P0eYWj/ynG20yFkaD181L//BRyosxTv/u52MjRZ0fO -J69jsHmryV9bfeRnedPVb9lJXfYPcCpr17ntY7ppFWENmVpdkMEz2yPcALq4ZQ8U -FOwez+9yYfqYPPbnbtC+CctJYNaMMcliy32K8zzIlFQsvCXqdtbq832RAoGAAtPw -dCNJzJAzfihc7HPiT1bZgwmC6X0Klgci8PtEB8duQJvll8jpc6UMwe+WOxJWjVfv -kcBvxQ5Fbo+HmB0+bUOO+JNlpwnjrs4uaLqNvRz57fLNDzUVlOg3NTc3myIGcFmL -TLggMvHQ5JXwYv6TkA8vPDR/zpoWV5gncD2GNmECgYEA8e9f30xeVtce5eUebRkB -bNCxi1sApTIPq8CXRN5JzX5plFj7K1HUlgqQsIxpdWJhi8G7DMj8C4/K7V+PjCTo -dU1ulbuFWwrIuSS3W6S1gh+eBhODfU80iO6SvSbGLiq11iRrQL/xMsCLgOExZE5d -BXgz1uzIrvJt5jmZh6bPSYc= +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDFwb1BjG4omFnZ +EuyUDH6uAPxCAqr+OKWEfM+2w/XJcrDuD+w08WwLAxbq6kSTG5LVtbMXM9BvdoMN +Llixrf2h2LcWvwgjIP/9Uj7XGa2P32Q7WVlRp62OjCu/c/kG6bM+NeCMyV39nz7b +n1uZdfeUvmWV44dDdpBdZw4jfHrIlr8WW33p8VHot+TZlecyfzj8rs2BcsReuGYH +IjpN0AWLKrxbyyxd5yKaBrQLrxsHVaU1fpFZxTn2YLXlGmfeQ4EaZj1SVriJ+zFR +o5CkN6ZO0CqUcGO/BstgcqSFt3+LyliYI8zRSGv6kY8E4cRzDINWMe0RPIqknStA +NcRhWIj7AgMBAAECggEAY/dY3U7IzNqe6J2pW/mo+/rhidjhaVtnSD7znVcX4zqH +9/+yjtzPmg14w02jVp3krwWHv53gqsfE3Z/lFAR5JxxvCR+OVHu1C/BMdd20H/t0 +JpA3F5Dkqh9vafuNEhKHGlaP6XtNeQzL8Kdw3XWFrvpETe3TjaXcumqC+itNwiGW +Xp7sRmCRxXQh9xEpM29sH7AddgewxuiAfQ9xcbKD8SXjfH67ECE7+RPnoipTo2We +io3r26S99x25GwP0fa1+JvMFXl7AzCSwiRLm9i3zHfB2oG17MfYh6MiQyPXRoj3R +/huvYPQDsJB/T11emg9AdRJTYN7Afu0y3iH9z59hSQKBgQDo/UGSFO29V1a+MtIe +vg+fBNE3cZR2CAEBEDTT6ea46F9ECTjkPTa4palD0XFB8lwz8bvLviJEXVtU14YD +nppw2RklMctefE9JpYr6fyVoe+bAejbD+Lcc1pQEzkv7Xui2MFGGSzeOp11+cXnY +vNiofA0ZSsgif5J9N+FWwjlOLQKBgQDZSbBN6ctJClgvGocLOPAoSEZUWuRpgOfZ +gxozCHlDVbM9ZAKqDsZX5qhXjbCT5qObeGFxSFS1E0cy+g1YHJ/oasXJGqHIdILj +/PWmmn1DZWsPVHMyKJPicaX8UTSV6L7j7SzSLufllMLMRk/9RdEcTuP/tiYiKwpf +T692+35UxwKBgQCHYKB5ATAilF0SpvTwZ/8rpuDqFlTtQDlVJNWNTJuDVYIFRlaI +SAlDwP5ZKZlleC2bARrdh9zhXF11LsXv1HhombzCn+xLOm/Xmxjl9HsH+vZZYKnx +tNKxLv1SzYvYw4z0T58PKSVe/mCU19q01QYO4AW8bHddlELJ/24vuysRAQKBgQCt +VLn+PQz70/Oqh5fIXQA+sgDgU603eCv6+DkTEqRhEWEtDLWPYL/Z6NbLGO0N3oMO +h0X77v4bgChgwtWYPyVUarAiD0uVM1QieGyhHUXlWGbB0NUf4vytO4l0MHcpSoPU +ICOL+vzjx/pop4IxgNshoNEB8BSVVw4sH83RtSb+iwKBgFqL6xMGRZqNT8bhqNMT +v2mCAX2GriUO4OPNOnKizlX86rxxyKz3z2vCX2ay4f4AeRXpoNwR6FYvwhbu+x6t +LQEmiIqM8olOJ1Kg++3KQeTkNh6mzQ4OIPOpHcJrW/C48MwipfZTMLp1q5iUoIjL +7FpPTt4uuvDOcVQoNDN9AXLA -----END PRIVATE KEY----- diff --git a/internal/services/firewall/testdata/openssl.cnf b/internal/services/firewall/testdata/openssl.cnf new file mode 100644 index 000000000000..0c9850096e6e --- /dev/null +++ b/internal/services/firewall/testdata/openssl.cnf @@ -0,0 +1,20 @@ +[ req ] +default_bits = 4096 +distinguished_name = req_distinguished_name +string_mask = utf8only +default_md = sha512 + +[ req_distinguished_name ] +countryName = Country Name (2 letter code) +stateOrProvinceName = State or Province Name +localityName = Locality Name +0.organizationName = Organization Name +organizationalUnitName = Organizational Unit Name +commonName = Common Name +emailAddress = Email Address + +[ rootCA_ext ] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +basicConstraints = critical, CA:true +keyUsage = critical, digitalSignature, cRLSign, keyCertSign diff --git a/internal/services/fluidrelay/client/client.go b/internal/services/fluidrelay/client/client.go new file mode 100644 index 000000000000..1e50ecfde852 --- /dev/null +++ b/internal/services/fluidrelay/client/client.go @@ -0,0 +1,19 @@ +package client + +import ( + servers "github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers" + "github.com/hashicorp/terraform-provider-azurerm/internal/common" +) + +type Client struct { + ServerClient *servers.FluidRelayServersClient +} + +func NewClient(o *common.ClientOptions) *Client { + serverClient := servers.NewFluidRelayServersClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&serverClient.Client, o.ResourceManagerAuthorizer) + + return &Client{ + ServerClient: &serverClient, + } +} diff --git a/internal/services/fluidrelay/fluid_relay_servers_resource.go b/internal/services/fluidrelay/fluid_relay_servers_resource.go new file mode 100644 index 000000000000..a413906a7bff --- /dev/null +++ b/internal/services/fluidrelay/fluid_relay_servers_resource.go @@ -0,0 +1,271 @@ +package fluidrelay + +import ( + "context" + "fmt" + "time" + + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers" + "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/fluidrelay/validate" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type ServerModel struct { + Name string `tfschema:"name"` + ResourceGroup string `tfschema:"resource_group_name"` + Location string `tfschema:"location"` + StorageSKU string `tfschema:"storage_sku"` + FrsTenantId string `tfschema:"frs_tenant_id"` + OrdererEndpoints []string `tfschema:"orderer_endpoints"` + StorageEndpoints []string `tfschema:"storage_endpoints"` + Tags map[string]string `tfschema:"tags"` + Identity []identity.ModelSystemAssignedUserAssigned `tfschema:"identity"` +} + +func (s *ServerModel) flattenIdentity(input *identity.SystemAndUserAssignedMap) error { + if input == nil { + return nil + } + config := identity.SystemAndUserAssignedMap{ + Type: input.Type, + PrincipalId: input.PrincipalId, + TenantId: input.TenantId, + IdentityIds: make(map[string]identity.UserAssignedIdentityDetails), + } + for k, v := range input.IdentityIds { + config.IdentityIds[k] = identity.UserAssignedIdentityDetails{ + ClientId: v.ClientId, + PrincipalId: v.PrincipalId, + } + } + model, err := identity.FlattenSystemAndUserAssignedMapToModel(&config) + if err != nil { + return err + } + s.Identity = *model + return nil +} + +type Server struct{} + +var _ sdk.ResourceWithUpdate = (*Server)(nil) + +func (s Server) Arguments() map[string]*pluginsdk.Schema { + return map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.FluidRelayServerName, + }, + "resource_group_name": commonschema.ResourceGroupName(), + "location": commonschema.Location(), + "tags": commonschema.Tags(), + "identity": commonschema.SystemAssignedUserAssignedIdentityOptional(), + "storage_sku": { + // todo remove computed when https://github.com/Azure/azure-rest-api-specs/issues/19700 is fixed + Type: pluginsdk.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice(fluidrelayservers.PossibleValuesForStorageSKU(), false), + }, + } +} + +func (s Server) Attributes() map[string]*pluginsdk.Schema { + return map[string]*pluginsdk.Schema{ + "frs_tenant_id": { + Type: pluginsdk.TypeString, + Computed: true, + }, + "orderer_endpoints": { + Type: pluginsdk.TypeList, + Computed: true, + Elem: &pluginsdk.Schema{ + Type: pluginsdk.TypeString, + }, + }, + "storage_endpoints": { + Type: pluginsdk.TypeList, + Computed: true, + Elem: &pluginsdk.Schema{ + Type: pluginsdk.TypeString, + }, + }, + } +} + +func (s Server) ModelObject() interface{} { + return &ServerModel{} +} + +func (s Server) ResourceType() string { + return "azurerm_fluid_relay_server" +} + +func (s Server) Create() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 30 * time.Minute, + Func: func(ctx context.Context, meta sdk.ResourceMetaData) (err error) { + client := meta.Client.FluidRelay.ServerClient + + var model ServerModel + if err = meta.Decode(&model); err != nil { + return err + } + + subscriptionID := meta.Client.Account.SubscriptionId + id := fluidrelayservers.NewFluidRelayServerID(subscriptionID, model.ResourceGroup, model.Name) + + existing, err := client.Get(ctx, id) + if !response.WasNotFound(existing.HttpResponse) { + if err != nil { + return fmt.Errorf("checking for presence of existing %s: %+v", id, err) + } + + return meta.ResourceRequiresImport(s.ResourceType(), id) + } + + serverReq := fluidrelayservers.FluidRelayServer{ + Location: azure.NormalizeLocation(model.Location), + Name: utils.String(model.Name), + } + if model.Tags != nil { + serverReq.Tags = &model.Tags + } + serverReq.Properties = &fluidrelayservers.FluidRelayServerProperties{} + serverReq.Identity, err = identity.ExpandSystemAndUserAssignedMapFromModel(model.Identity) + if err != nil { + return fmt.Errorf("expanding user identities: %+v", err) + } + + if model.StorageSKU != "" { + serverReq.Properties.Storagesku = (*fluidrelayservers.StorageSKU)(&model.StorageSKU) + } + _, err = client.CreateOrUpdate(ctx, id, serverReq) + if err != nil { + return fmt.Errorf("creating %v err: %+v", id, err) + } + meta.SetID(id) + + return nil + }, + } +} + +func (s Server) Update() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 10 * time.Minute, + Func: func(ctx context.Context, meta sdk.ResourceMetaData) (err error) { + client := meta.Client.FluidRelay.ServerClient + id, err := fluidrelayservers.ParseFluidRelayServerID(meta.ResourceData.Id()) + if err != nil { + return err + } + + var model ServerModel + if err = meta.Decode(&model); err != nil { + return fmt.Errorf("decoding err: %+v", err) + } + + var upd fluidrelayservers.FluidRelayServerUpdate + if meta.ResourceData.HasChange("tags") { + upd.Tags = &model.Tags + } + if meta.ResourceData.HasChange("identity") { + upd.Identity, err = identity.ExpandSystemAndUserAssignedMapFromModel(model.Identity) + if err != nil { + return fmt.Errorf("expanding user identities: %+v", err) + } + } + if _, err = client.Update(ctx, *id, upd); err != nil { + return fmt.Errorf("updating %s: %v", id, err) + } + + return nil + }, + } +} + +func (s Server) Read() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 5 * time.Minute, + Func: func(ctx context.Context, meta sdk.ResourceMetaData) error { + client := meta.Client.FluidRelay.ServerClient + + id, err := fluidrelayservers.ParseFluidRelayServerID(meta.ResourceData.Id()) + if err != nil { + return err + } + + server, err := client.Get(ctx, *id) + if err != nil { + return fmt.Errorf("retrieving %s: %v", id, err) + } + + model := server.Model + + output := &ServerModel{ + Name: id.FluidRelayServerName, + ResourceGroup: id.ResourceGroup, + Location: location.Normalize(model.Location), + } + if err = output.flattenIdentity(model.Identity); err != nil { + return fmt.Errorf("flattening `identity`: %v", err) + } + if server.Model.Tags != nil { + output.Tags = *server.Model.Tags + } + if prop := model.Properties; prop != nil { + if prop.FrsTenantId != nil { + output.FrsTenantId = *prop.FrsTenantId + } + if points := prop.FluidRelayEndpoints; points != nil { + if points.OrdererEndpoints != nil { + output.OrdererEndpoints = *points.OrdererEndpoints + } + if points.StorageEndpoints != nil { + output.StorageEndpoints = *points.StorageEndpoints + } + } + } + if val, ok := meta.ResourceData.GetOk("storage_sku"); ok { + output.StorageSKU = val.(string) + } + return meta.Encode(output) + }, + } +} + +func (s Server) Delete() sdk.ResourceFunc { + return sdk.ResourceFunc{ + Timeout: 10 * time.Minute, + Func: func(ctx context.Context, meta sdk.ResourceMetaData) error { + client := meta.Client.FluidRelay.ServerClient + + id, err := fluidrelayservers.ParseFluidRelayServerID(meta.ResourceData.Id()) + if err != nil { + return err + } + + meta.Logger.Infof("deleting %s", id) + if _, err := client.Delete(ctx, *id); err != nil { + return fmt.Errorf("delete %s: %v", id, err) + } + return nil + }, + } +} + +func (s Server) IDValidationFunc() pluginsdk.SchemaValidateFunc { + return fluidrelayservers.ValidateFluidRelayServerID +} diff --git a/internal/services/fluidrelay/fluid_relay_servers_resource_test.go b/internal/services/fluidrelay/fluid_relay_servers_resource_test.go new file mode 100644 index 000000000000..0e8f2dfd8a98 --- /dev/null +++ b/internal/services/fluidrelay/fluid_relay_servers_resource_test.go @@ -0,0 +1,301 @@ +package fluidrelay_test + +import ( + "context" + "fmt" + "testing" + + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/fluidrelay" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type FluidRelayResource struct{} + +func (f FluidRelayResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { + id, err := fluidrelayservers.ParseFluidRelayServerID(state.ID) + if err != nil { + return nil, err + } + + resp, err := client.FluidRelay.ServerClient.Get(ctx, *id) + if err != nil { + if response.WasNotFound(resp.HttpResponse) { + return utils.Bool(false), nil + } + return nil, fmt.Errorf("retrieving %s: %v", id, err) + } + if response.WasNotFound(resp.HttpResponse) { + return utils.Bool(false), nil + } + return utils.Bool(true), nil +} + +var s = fluidrelay.Server{} + +func TestAccFluidRelay_basic(t *testing.T) { + data := acceptance.BuildTestData(t, s.ResourceType(), "test") + f := FluidRelayResource{} + + data.ResourceTest(t, f, []acceptance.TestStep{ + { + Config: f.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + check.That(data.ResourceName).Key("frs_tenant_id").IsUUID(), + check.That(data.ResourceName).Key("orderer_endpoints.0").Exists(), + ), + }, + data.ImportStep(), + }) +} + +func TestAccFluidRelay_storageBasic(t *testing.T) { + data := acceptance.BuildTestData(t, s.ResourceType(), "test") + f := FluidRelayResource{} + + data.ResourceTest(t, f, []acceptance.TestStep{ + { + Config: f.storageBasic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + check.That(data.ResourceName).Key("frs_tenant_id").IsUUID(), + check.That(data.ResourceName).Key("orderer_endpoints.0").Exists(), + ), + }, + data.ImportStep("storage_sku"), + }) +} + +func TestAccFluidRelay_ami(t *testing.T) { + data := acceptance.BuildTestData(t, s.ResourceType(), "test") + f := FluidRelayResource{} + + data.ResourceTest(t, f, []acceptance.TestStep{ + { + Config: f.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + ), + }, + data.ImportStep(), + { + Config: f.userAssigned(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + ), + }, + data.ImportStep(), + { + Config: f.systemAssigned(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + ), + }, + data.ImportStep(), + { + Config: f.systemAndUserAssigned(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + ), + }, + data.ImportStep(), + }) +} + +func TestAccFluidRelayServer_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, s.ResourceType(), "test") + var f FluidRelayResource + + data.ResourceTest(t, f, []acceptance.TestStep{ + { + Config: f.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + ), + }, + data.RequiresImportErrorStep(f.requiresImport), + }) +} + +func TestAccFluidRelayServer_update(t *testing.T) { + data := acceptance.BuildTestData(t, s.ResourceType(), "test") + var f FluidRelayResource + + data.ResourceTest(t, f, []acceptance.TestStep{ + { + Config: f.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + ), + }, + data.ImportStep(), + { + Config: f.update(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + ), + }, + data.ImportStep(), + { + Config: f.basic(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(f), + ), + }, + }) +} + +func (f FluidRelayResource) template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-fluidrelay-%[1]d" + location = "%[2]s" +} +`, data.RandomInteger, data.Locations.Primary) +} + +func (f FluidRelayResource) templateWithIdentity(data acceptance.TestData) string { + return fmt.Sprintf(` + +%[1]s + +resource "azurerm_user_assigned_identity" "test" { + name = "acctestRG-userAssignedIdentity-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} +`, f.template(data), data.RandomInteger) +} + +func (f FluidRelayResource) basic(data acceptance.TestData) string { + return fmt.Sprintf(` + +%[1]s + +resource "azurerm_fluid_relay_server" "test" { + name = "acctestRG-fuildRelayServer-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = "%[3]s" + tags = { + foo = "bar" + } +} +`, f.template(data), data.RandomInteger, data.Locations.Primary) +} + +// basic storage sku only work with east asia and south-ease-asia +func (f FluidRelayResource) storageBasic(data acceptance.TestData) string { + return fmt.Sprintf(` + + +%[1]s + +resource "azurerm_fluid_relay_server" "test" { + name = "acctestRG-fuildRelayServer-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = "SouthEastAsia" + storage_sku = "basic" + tags = { + foo = "bar" + } +} +`, f.template(data), data.RandomInteger) +} + +func (f FluidRelayResource) userAssigned(data acceptance.TestData) string { + return fmt.Sprintf(` + + +%[1]s + +resource "azurerm_fluid_relay_server" "test" { + name = "acctestRG-fuildRelayServer-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = "%[3]s" + identity { + type = "UserAssigned" + identity_ids = [azurerm_user_assigned_identity.test.id] + } +} +`, f.templateWithIdentity(data), data.RandomInteger, data.Locations.Primary) +} + +func (f FluidRelayResource) systemAssigned(data acceptance.TestData) string { + return fmt.Sprintf(` + + +%[1]s + +resource "azurerm_fluid_relay_server" "test" { + name = "acctestRG-fuildRelayServer-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = "%[3]s" + identity { + type = "SystemAssigned" + } + tags = { + foo = "bar" + } +} +`, f.templateWithIdentity(data), data.RandomInteger, data.Locations.Primary) +} + +func (f FluidRelayResource) systemAndUserAssigned(data acceptance.TestData) string { + return fmt.Sprintf(` + + +%[1]s + +resource "azurerm_fluid_relay_server" "test" { + name = "acctestRG-fuildRelayServer-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = "%[3]s" + identity { + type = "SystemAssigned, UserAssigned" + identity_ids = [azurerm_user_assigned_identity.test.id] + } + tags = { + foo = "bar" + } +} +`, f.templateWithIdentity(data), data.RandomInteger, data.Locations.Primary) +} + +func (f FluidRelayResource) requiresImport(data acceptance.TestData) string { + return fmt.Sprintf(` + +%s + +resource "azurerm_fluid_relay_server" "import" { + name = azurerm_fluid_relay_server.test.name + resource_group_name = azurerm_fluid_relay_server.test.resource_group_name + location = azurerm_fluid_relay_server.test.location +} +`, f.basic(data)) +} + +func (f FluidRelayResource) update(data acceptance.TestData) string { + return fmt.Sprintf(` + +%[1]s + +resource "azurerm_fluid_relay_server" "test" { + name = "acctestRG-fuildRelayServer-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = "%[3]s" + tags = { + foo = "bar2" + } +} +`, f.template(data), data.RandomInteger, data.Locations.Primary) +} diff --git a/internal/services/fluidrelay/parse/fluid_relay.go b/internal/services/fluidrelay/parse/fluid_relay.go new file mode 100644 index 000000000000..1a256fc789e5 --- /dev/null +++ b/internal/services/fluidrelay/parse/fluid_relay.go @@ -0,0 +1,69 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +type FluidRelayId struct { + SubscriptionId string + ResourceGroup string + FluidRelayServerName string +} + +func NewFluidRelayID(subscriptionId, resourceGroup, fluidRelayServerName string) FluidRelayId { + return FluidRelayId{ + SubscriptionId: subscriptionId, + ResourceGroup: resourceGroup, + FluidRelayServerName: fluidRelayServerName, + } +} + +func (id FluidRelayId) String() string { + segments := []string{ + fmt.Sprintf("Fluid Relay Server Name %q", id.FluidRelayServerName), + fmt.Sprintf("Resource Group %q", id.ResourceGroup), + } + segmentsStr := strings.Join(segments, " / ") + return fmt.Sprintf("%s: (%s)", "Fluid Relay", segmentsStr) +} + +func (id FluidRelayId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.FluidRelay/fluidRelayServers/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.FluidRelayServerName) +} + +// FluidRelayID parses a FluidRelay ID into an FluidRelayId struct +func FluidRelayID(input string) (*FluidRelayId, error) { + id, err := resourceids.ParseAzureResourceID(input) + if err != nil { + return nil, err + } + + resourceId := FluidRelayId{ + SubscriptionId: id.SubscriptionID, + ResourceGroup: id.ResourceGroup, + } + + if resourceId.SubscriptionId == "" { + return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + } + + if resourceId.ResourceGroup == "" { + return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") + } + + if resourceId.FluidRelayServerName, err = id.PopSegment("fluidRelayServers"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &resourceId, nil +} diff --git a/internal/services/fluidrelay/parse/fluid_relay_servers.go b/internal/services/fluidrelay/parse/fluid_relay_servers.go new file mode 100644 index 000000000000..05a91ba4b37a --- /dev/null +++ b/internal/services/fluidrelay/parse/fluid_relay_servers.go @@ -0,0 +1,69 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +type FluidRelayServersId struct { + SubscriptionId string + ResourceGroup string + FluidRelayServerName string +} + +func NewFluidRelayServersID(subscriptionId, resourceGroup, fluidRelayServerName string) FluidRelayServersId { + return FluidRelayServersId{ + SubscriptionId: subscriptionId, + ResourceGroup: resourceGroup, + FluidRelayServerName: fluidRelayServerName, + } +} + +func (id FluidRelayServersId) String() string { + segments := []string{ + fmt.Sprintf("Fluid Relay Server Name %q", id.FluidRelayServerName), + fmt.Sprintf("Resource Group %q", id.ResourceGroup), + } + segmentsStr := strings.Join(segments, " / ") + return fmt.Sprintf("%s: (%s)", "Fluid Relay Servers", segmentsStr) +} + +func (id FluidRelayServersId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.FluidRelay/fluidRelayServers/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.FluidRelayServerName) +} + +// FluidRelayServersID parses a FluidRelayServers ID into an FluidRelayServersId struct +func FluidRelayServersID(input string) (*FluidRelayServersId, error) { + id, err := resourceids.ParseAzureResourceID(input) + if err != nil { + return nil, err + } + + resourceId := FluidRelayServersId{ + SubscriptionId: id.SubscriptionID, + ResourceGroup: id.ResourceGroup, + } + + if resourceId.SubscriptionId == "" { + return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + } + + if resourceId.ResourceGroup == "" { + return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") + } + + if resourceId.FluidRelayServerName, err = id.PopSegment("fluidRelayServers"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &resourceId, nil +} diff --git a/internal/services/fluidrelay/parse/fluid_relay_servers_test.go b/internal/services/fluidrelay/parse/fluid_relay_servers_test.go new file mode 100644 index 000000000000..eed09cfe0595 --- /dev/null +++ b/internal/services/fluidrelay/parse/fluid_relay_servers_test.go @@ -0,0 +1,112 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "testing" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.Id = FluidRelayServersId{} + +func TestFluidRelayServersIDFormatter(t *testing.T) { + actual := NewFluidRelayServersID("00000000-0000-0000-0000-000000000000", "rg1", "server1").ID() + expected := "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.FluidRelay/fluidRelayServers/server1" + if actual != expected { + t.Fatalf("Expected %q but got %q", expected, actual) + } +} + +func TestFluidRelayServersID(t *testing.T) { + testData := []struct { + Input string + Error bool + Expected *FluidRelayServersId + }{ + + { + // empty + Input: "", + Error: true, + }, + + { + // missing SubscriptionId + Input: "/", + Error: true, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Error: true, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/", + Error: true, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Error: true, + }, + + { + // missing FluidRelayServerName + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.FluidRelay/", + Error: true, + }, + + { + // missing value for FluidRelayServerName + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.FluidRelay/fluidRelayServers/", + Error: true, + }, + + { + // valid + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.FluidRelay/fluidRelayServers/server1", + Expected: &FluidRelayServersId{ + SubscriptionId: "00000000-0000-0000-0000-000000000000", + ResourceGroup: "rg1", + FluidRelayServerName: "server1", + }, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/00000000-0000-0000-0000-000000000000/RESOURCEGROUPS/RG1/PROVIDERS/MICROSOFT.FLUIDRELAY/FLUIDRELAYSERVERS/SERVER1", + Error: true, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Input) + + actual, err := FluidRelayServersID(v.Input) + if err != nil { + if v.Error { + continue + } + + t.Fatalf("Expect a value but got an error: %s", err) + } + if v.Error { + t.Fatal("Expect an error but didn't get one") + } + + if actual.SubscriptionId != v.Expected.SubscriptionId { + t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) + } + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) + } + if actual.FluidRelayServerName != v.Expected.FluidRelayServerName { + t.Fatalf("Expected %q but got %q for FluidRelayServerName", v.Expected.FluidRelayServerName, actual.FluidRelayServerName) + } + } +} diff --git a/internal/services/fluidrelay/parse/fluid_relay_test.go b/internal/services/fluidrelay/parse/fluid_relay_test.go new file mode 100644 index 000000000000..d9713ad2a35d --- /dev/null +++ b/internal/services/fluidrelay/parse/fluid_relay_test.go @@ -0,0 +1,112 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "testing" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.Id = FluidRelayId{} + +func TestFluidRelayIDFormatter(t *testing.T) { + actual := NewFluidRelayID("67a9759d-d099-4aa8-8675-e6cfd669c3f4", "myrg", "myFluid").ID() + expected := "/subscriptions/67a9759d-d099-4aa8-8675-e6cfd669c3f4/resourceGroups/myrg/providers/Microsoft.FluidRelay/fluidRelayServers/myFluid" + if actual != expected { + t.Fatalf("Expected %q but got %q", expected, actual) + } +} + +func TestFluidRelayID(t *testing.T) { + testData := []struct { + Input string + Error bool + Expected *FluidRelayId + }{ + + { + // empty + Input: "", + Error: true, + }, + + { + // missing SubscriptionId + Input: "/", + Error: true, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Error: true, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/67a9759d-d099-4aa8-8675-e6cfd669c3f4/", + Error: true, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/67a9759d-d099-4aa8-8675-e6cfd669c3f4/resourceGroups/", + Error: true, + }, + + { + // missing FluidRelayServerName + Input: "/subscriptions/67a9759d-d099-4aa8-8675-e6cfd669c3f4/resourceGroups/myrg/providers/Microsoft.FluidRelay/", + Error: true, + }, + + { + // missing value for FluidRelayServerName + Input: "/subscriptions/67a9759d-d099-4aa8-8675-e6cfd669c3f4/resourceGroups/myrg/providers/Microsoft.FluidRelay/fluidRelayServers/", + Error: true, + }, + + { + // valid + Input: "/subscriptions/67a9759d-d099-4aa8-8675-e6cfd669c3f4/resourceGroups/myrg/providers/Microsoft.FluidRelay/fluidRelayServers/myFluid", + Expected: &FluidRelayId{ + SubscriptionId: "67a9759d-d099-4aa8-8675-e6cfd669c3f4", + ResourceGroup: "myrg", + FluidRelayServerName: "myFluid", + }, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/67A9759D-D099-4AA8-8675-E6CFD669C3F4/RESOURCEGROUPS/MYRG/PROVIDERS/MICROSOFT.FLUIDRELAY/FLUIDRELAYSERVERS/MYFLUID", + Error: true, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Input) + + actual, err := FluidRelayID(v.Input) + if err != nil { + if v.Error { + continue + } + + t.Fatalf("Expect a value but got an error: %s", err) + } + if v.Error { + t.Fatal("Expect an error but didn't get one") + } + + if actual.SubscriptionId != v.Expected.SubscriptionId { + t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) + } + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) + } + if actual.FluidRelayServerName != v.Expected.FluidRelayServerName { + t.Fatalf("Expected %q but got %q for FluidRelayServerName", v.Expected.FluidRelayServerName, actual.FluidRelayServerName) + } + } +} diff --git a/internal/services/fluidrelay/registration.go b/internal/services/fluidrelay/registration.go new file mode 100644 index 000000000000..1dc2cd1f83d7 --- /dev/null +++ b/internal/services/fluidrelay/registration.go @@ -0,0 +1,29 @@ +package fluidrelay + +import "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" + +type Registration struct{} + +func (r Registration) Name() string { + return "Fluid Relay" +} + +func (r Registration) DataSources() []sdk.DataSource { + return []sdk.DataSource{} +} + +func (r Registration) Resources() []sdk.Resource { + return []sdk.Resource{ + Server{}, + } +} + +func (r Registration) WebsiteCategories() []string { + return []string{ + "Fluid Relay", + } +} + +var ( + _ sdk.TypedServiceRegistration = (*Registration)(nil) +) diff --git a/internal/services/fluidrelay/resourceids.go b/internal/services/fluidrelay/resourceids.go new file mode 100644 index 000000000000..84a7525948ab --- /dev/null +++ b/internal/services/fluidrelay/resourceids.go @@ -0,0 +1,4 @@ +package fluidrelay + +// Fluid Relay IDs +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=FluidRelayServers -id=/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.FluidRelay/fluidRelayServers/server1 diff --git a/internal/services/fluidrelay/validate/fluid_relay_servers_id.go b/internal/services/fluidrelay/validate/fluid_relay_servers_id.go new file mode 100644 index 000000000000..d4aedcc5f49a --- /dev/null +++ b/internal/services/fluidrelay/validate/fluid_relay_servers_id.go @@ -0,0 +1,23 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + + "github.com/hashicorp/terraform-provider-azurerm/internal/services/fluidrelay/parse" +) + +func FluidRelayServersID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := parse.FluidRelayServersID(v); err != nil { + errors = append(errors, err) + } + + return +} diff --git a/internal/services/fluidrelay/validate/fluid_relay_servers_id_test.go b/internal/services/fluidrelay/validate/fluid_relay_servers_id_test.go new file mode 100644 index 000000000000..f0de817b98a8 --- /dev/null +++ b/internal/services/fluidrelay/validate/fluid_relay_servers_id_test.go @@ -0,0 +1,76 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import "testing" + +func TestFluidRelayServersID(t *testing.T) { + cases := []struct { + Input string + Valid bool + }{ + + { + // empty + Input: "", + Valid: false, + }, + + { + // missing SubscriptionId + Input: "/", + Valid: false, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Valid: false, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/", + Valid: false, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Valid: false, + }, + + { + // missing FluidRelayServerName + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.FluidRelay/", + Valid: false, + }, + + { + // missing value for FluidRelayServerName + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.FluidRelay/fluidRelayServers/", + Valid: false, + }, + + { + // valid + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.FluidRelay/fluidRelayServers/server1", + Valid: true, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/00000000-0000-0000-0000-000000000000/RESOURCEGROUPS/RG1/PROVIDERS/MICROSOFT.FLUIDRELAY/FLUIDRELAYSERVERS/SERVER1", + Valid: false, + }, + } + for _, tc := range cases { + t.Logf("[DEBUG] Testing Value %s", tc.Input) + _, errors := FluidRelayServersID(tc.Input, "test") + valid := len(errors) == 0 + + if tc.Valid != valid { + t.Fatalf("Expected %t but got %t", tc.Valid, valid) + } + } +} diff --git a/internal/services/fluidrelay/validate/server_name.go b/internal/services/fluidrelay/validate/server_name.go new file mode 100644 index 000000000000..10aebff9c1a6 --- /dev/null +++ b/internal/services/fluidrelay/validate/server_name.go @@ -0,0 +1,21 @@ +package validate + +import ( + "fmt" + "regexp" +) + +var serverNameReg = regexp.MustCompile(`^[-0-9a-zA-Z]{1,50}$`) + +func FluidRelayServerName(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + // Name should contain only alphanumeric characters and hyphens, up to 50 characters long. + if !serverNameReg.MatchString(v) { + errors = append(errors, fmt.Errorf("Name should contain only alphanumeric characters and hyphens, up to 50 characters long.")) + } + return +} diff --git a/internal/services/fluidrelay/validate/server_name_test.go b/internal/services/fluidrelay/validate/server_name_test.go new file mode 100644 index 000000000000..a849f0b6c6c1 --- /dev/null +++ b/internal/services/fluidrelay/validate/server_name_test.go @@ -0,0 +1,63 @@ +package validate + +import ( + "strconv" + "testing" +) + +func TestFluidRelayServerName(t *testing.T) { + type args struct { + Input string + Valid bool + } + tests := []args{ + { + Input: "", + Valid: false, + }, + { + Input: "Ahc_dfs", + Valid: false, + }, + { + Input: "fds##$%#", + Valid: false, + }, + { + Input: "SUlwnodfs", + Valid: true, + }, + { + Input: "09810-", + Valid: true, + }, + { + Input: "-u432948230", + Valid: true, + }, + { + Input: "jkfdsj_de", + Valid: false, + }, + { + Input: "njkjoinjknkjnakjvdsjaneoihroiwjioionb6789233jn", + Valid: true, + }, + { + Input: "njk joinjknkjnakjvdsjaneoihroiwjioionb6789233jn", + Valid: false, + }, + { + Input: "njk1234567890sdfghjklcvbnmkjhgfcvbnjoinjknkjnakjvdsjaneoihroiwjioionb6789233jn", + Valid: false, + }, + } + for idx, tt := range tests { + t.Run(strconv.FormatInt(int64(idx), 10), func(t *testing.T) { + _, gotErrors := FluidRelayServerName(tt.Input, "test") + if (len(gotErrors) == 0) != tt.Valid { + t.Fatalf("server name validate `%s` expect %#v but got %#v", tt.Input, tt.Valid, gotErrors) + } + }) + } +} diff --git a/internal/services/hdinsight/hdinsight_kafka_cluster_resource.go b/internal/services/hdinsight/hdinsight_kafka_cluster_resource.go index b7c8bb358edf..5d2e867f0980 100644 --- a/internal/services/hdinsight/hdinsight_kafka_cluster_resource.go +++ b/internal/services/hdinsight/hdinsight_kafka_cluster_resource.go @@ -84,6 +84,8 @@ func resourceHDInsightKafkaCluster() *pluginsdk.Resource { "metastores": SchemaHDInsightsExternalMetastores(), + "network": SchemaHDInsightsNetwork(), + "component_version": { Type: pluginsdk.TypeList, Required: true, @@ -212,6 +214,9 @@ func resourceHDInsightKafkaClusterCreate(d *pluginsdk.ResourceData, meta interfa return fmt.Errorf("failure expanding `storage_account`: %s", err) } + networkPropertiesRaw := d.Get("network").([]interface{}) + networkProperties := ExpandHDInsightsNetwork(networkPropertiesRaw) + kafkaRoles := hdInsightRoleDefinition{ HeadNodeDef: hdInsightKafkaClusterHeadNodeDefinition, WorkerNodeDef: hdInsightKafkaClusterWorkerNodeDefinition, @@ -244,6 +249,7 @@ func resourceHDInsightKafkaClusterCreate(d *pluginsdk.ResourceData, meta interfa OsType: hdinsight.OSTypeLinux, ClusterVersion: utils.String(clusterVersion), MinSupportedTLSVersion: utils.String(tls), + NetworkProperties: networkProperties, ClusterDefinition: &hdinsight.ClusterDefinition{ Kind: utils.String("Kafka"), ComponentVersion: componentVersions, @@ -401,6 +407,12 @@ func resourceHDInsightKafkaClusterRead(d *pluginsdk.ResourceData, meta interface d.Set("encryption_in_transit_enabled", props.EncryptionInTransitProperties.IsEncryptionInTransitEnabled) } + if props.NetworkProperties != nil { + if err := d.Set("network", FlattenHDInsightsNetwork(props.NetworkProperties)); err != nil { + return fmt.Errorf("flatten `network`: %+v", err) + } + } + monitor, err := extensionsClient.GetMonitoringStatus(ctx, resourceGroup, name) if err != nil { return fmt.Errorf("failed reading monitor configuration for HDInsight Hadoop Cluster %q (Resource Group %q): %+v", name, resourceGroup, err) diff --git a/internal/services/hdinsight/hdinsight_kafka_cluster_resource_test.go b/internal/services/hdinsight/hdinsight_kafka_cluster_resource_test.go index 7943d178fe9f..ce732de4c606 100644 --- a/internal/services/hdinsight/hdinsight_kafka_cluster_resource_test.go +++ b/internal/services/hdinsight/hdinsight_kafka_cluster_resource_test.go @@ -863,11 +863,16 @@ resource "azurerm_hdinsight_kafka_cluster" "test" { } storage_account { + storage_resource_id = azurerm_storage_account.test.id storage_container_id = azurerm_storage_container.test.id storage_account_key = azurerm_storage_account.test.primary_access_key is_default = true } + network { + connection_direction = "Outbound" + } + roles { head_node { vm_size = "Standard_D3_V2" diff --git a/internal/services/keyvault/key_vault_access_policy_resource.go b/internal/services/keyvault/key_vault_access_policy_resource.go index 41d4f29a62c0..5353bc9bfb4c 100644 --- a/internal/services/keyvault/key_vault_access_policy_resource.go +++ b/internal/services/keyvault/key_vault_access_policy_resource.go @@ -7,14 +7,13 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" - "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2021-10-01/keyvault" "github.com/gofrs/uuid" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" diff --git a/internal/services/keyvault/key_vault_access_policy_resource_test.go b/internal/services/keyvault/key_vault_access_policy_resource_test.go index 20d4bd02c760..0921bcfea2eb 100644 --- a/internal/services/keyvault/key_vault_access_policy_resource_test.go +++ b/internal/services/keyvault/key_vault_access_policy_resource_test.go @@ -6,12 +6,11 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/keyvault/key_vault_certificate_resource.go b/internal/services/keyvault/key_vault_certificate_resource.go index 9bd94e2ebead..469340004f32 100644 --- a/internal/services/keyvault/key_vault_certificate_resource.go +++ b/internal/services/keyvault/key_vault_certificate_resource.go @@ -461,8 +461,14 @@ func resourceKeyVaultCertificateCreate(d *pluginsdk.ResourceData, meta interface CertificatePolicy: policy, Tags: tags.Expand(t), } - if _, err := client.ImportCertificate(ctx, *keyVaultBaseUrl, name, importParameters); err != nil { - return err + if resp, err := client.ImportCertificate(ctx, *keyVaultBaseUrl, name, importParameters); err != nil { + if meta.(*clients.Client).Features.KeyVault.RecoverSoftDeletedCerts && utils.ResponseWasConflict(resp.Response) { + if err = recoverDeletedCertificate(ctx, d, meta, *keyVaultBaseUrl, name); err != nil { + return err + } + } else { + return err + } } } else { // Generate new @@ -472,27 +478,9 @@ func resourceKeyVaultCertificateCreate(d *pluginsdk.ResourceData, meta interface } if resp, err := client.CreateCertificate(ctx, *keyVaultBaseUrl, name, parameters); err != nil { if meta.(*clients.Client).Features.KeyVault.RecoverSoftDeletedCerts && utils.ResponseWasConflict(resp.Response) { - recoveredCertificate, err := client.RecoverDeletedCertificate(ctx, *keyVaultBaseUrl, name) - if err != nil { + if err = recoverDeletedCertificate(ctx, d, meta, *keyVaultBaseUrl, name); err != nil { return err } - log.Printf("[DEBUG] Recovering Secret %q with ID: %q", name, *recoveredCertificate.ID) - if certificate := recoveredCertificate.ID; certificate != nil { - stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{"pending"}, - Target: []string{"available"}, - Refresh: keyVaultChildItemRefreshFunc(*certificate), - Delay: 30 * time.Second, - PollInterval: 10 * time.Second, - ContinuousTargetOccurence: 10, - Timeout: d.Timeout(pluginsdk.TimeoutCreate), - } - - if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for Key Vault Secret %q to become available: %s", name, err) - } - log.Printf("[DEBUG] Secret %q recovered with ID: %q", name, *recoveredCertificate.ID) - } } else { return err } @@ -529,6 +517,32 @@ func resourceKeyVaultCertificateCreate(d *pluginsdk.ResourceData, meta interface return resourceKeyVaultCertificateRead(d, meta) } +func recoverDeletedCertificate(ctx context.Context, d *pluginsdk.ResourceData, meta interface{}, keyVaultBaseUrl string, name string) error { + client := meta.(*clients.Client).KeyVault.ManagementClient + recoveredCertificate, err := client.RecoverDeletedCertificate(ctx, keyVaultBaseUrl, name) + if err != nil { + return err + } + log.Printf("[DEBUG] Recovering Secret %q with ID: %q", name, *recoveredCertificate.ID) + if certificate := recoveredCertificate.ID; certificate != nil { + stateConf := &pluginsdk.StateChangeConf{ + Pending: []string{"pending"}, + Target: []string{"available"}, + Refresh: keyVaultChildItemRefreshFunc(*certificate), + Delay: 30 * time.Second, + PollInterval: 10 * time.Second, + ContinuousTargetOccurence: 10, + Timeout: d.Timeout(pluginsdk.TimeoutCreate), + } + + if _, err := stateConf.WaitForStateContext(ctx); err != nil { + return fmt.Errorf("waiting for Key Vault Secret %q to become available: %s", name, err) + } + log.Printf("[DEBUG] Secret %q recovered with ID: %q", name, *recoveredCertificate.ID) + } + return nil +} + func resourceKeyVaultCertificateUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).KeyVault.ManagementClient ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) diff --git a/internal/services/kusto/client/client.go b/internal/services/kusto/client/client.go index a1a8ff832d06..6e2badb7a925 100644 --- a/internal/services/kusto/client/client.go +++ b/internal/services/kusto/client/client.go @@ -1,7 +1,7 @@ package client import ( - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/terraform-provider-azurerm/internal/common" ) diff --git a/internal/services/kusto/identity.go b/internal/services/kusto/identity.go index dd530e9d3cf2..f74767d9ae54 100644 --- a/internal/services/kusto/identity.go +++ b/internal/services/kusto/identity.go @@ -1,7 +1,7 @@ package kusto import ( - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/kusto/kusto_attached_database_configuration_resource.go b/internal/services/kusto/kusto_attached_database_configuration_resource.go index 0ec64135dae0..d618c399eb08 100644 --- a/internal/services/kusto/kusto_attached_database_configuration_resource.go +++ b/internal/services/kusto/kusto_attached_database_configuration_resource.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" diff --git a/internal/services/kusto/kusto_cluster_customer_managed_key_resource.go b/internal/services/kusto/kusto_cluster_customer_managed_key_resource.go index 727839d261ae..0216be47c5ce 100644 --- a/internal/services/kusto/kusto_cluster_customer_managed_key_resource.go +++ b/internal/services/kusto/kusto_cluster_customer_managed_key_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/kusto/kusto_cluster_principal_assignment_resource.go b/internal/services/kusto/kusto_cluster_principal_assignment_resource.go index 44fe3123387c..4695c420ce50 100644 --- a/internal/services/kusto/kusto_cluster_principal_assignment_resource.go +++ b/internal/services/kusto/kusto_cluster_principal_assignment_resource.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/kusto/kusto_cluster_resource.go b/internal/services/kusto/kusto_cluster_resource.go index 83830c6c4e33..cba2a51166ae 100644 --- a/internal/services/kusto/kusto_cluster_resource.go +++ b/internal/services/kusto/kusto_cluster_resource.go @@ -6,18 +6,16 @@ import ( "strings" "time" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-helpers/resourcemanager/zones" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-provider-azurerm/internal/features" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" - "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/features" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" "github.com/hashicorp/terraform-provider-azurerm/internal/services/kusto/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/kusto/validate" @@ -197,6 +195,16 @@ func resourceKustoCluster() *pluginsdk.Resource { Computed: true, }, + "public_ip_type": { + Type: pluginsdk.TypeString, + Optional: true, + Default: string(kusto.PublicIPTypeIPv4), + ValidateFunc: validation.StringInSlice([]string{ + string(kusto.PublicIPTypeIPv4), + string(kusto.PublicIPTypeDualStack), + }, false), + }, + "public_network_access_enabled": { Type: pluginsdk.TypeBool, Optional: true, @@ -315,6 +323,7 @@ func resourceKustoClusterCreateUpdate(d *pluginsdk.ResourceData, meta interface{ EnablePurge: utils.Bool(d.Get("purge_enabled").(bool)), EngineType: engine, PublicNetworkAccess: publicNetworkAccess, + PublicIPType: kusto.PublicIPType(d.Get("public_ip_type").(string)), TrustedExternalTenants: expandTrustedExternalTenants(d.Get("trusted_external_tenants").([]interface{})), } @@ -451,6 +460,7 @@ func resourceKustoClusterRead(d *pluginsdk.ResourceData, meta interface{}) error d.Set("uri", props.URI) d.Set("data_ingestion_uri", props.DataIngestionURI) d.Set("engine", props.EngineType) + d.Set("public_ip_type", props.PublicIPType) } return tags.FlattenAndSet(d, resp.Tags) diff --git a/internal/services/kusto/kusto_cluster_resource_test.go b/internal/services/kusto/kusto_cluster_resource_test.go index 3e6e7f9d07be..f42cde28238c 100644 --- a/internal/services/kusto/kusto_cluster_resource_test.go +++ b/internal/services/kusto/kusto_cluster_resource_test.go @@ -57,6 +57,7 @@ func TestAccKustoCluster_update(t *testing.T) { check.That(data.ResourceName).Key("disk_encryption_enabled").HasValue("false"), check.That(data.ResourceName).Key("streaming_ingestion_enabled").HasValue("false"), check.That(data.ResourceName).Key("purge_enabled").HasValue("false"), + check.That(data.ResourceName).Key("public_ip_type").HasValue("IPv4"), ), }, data.ImportStep(), @@ -67,6 +68,7 @@ func TestAccKustoCluster_update(t *testing.T) { check.That(data.ResourceName).Key("disk_encryption_enabled").HasValue("true"), check.That(data.ResourceName).Key("streaming_ingestion_enabled").HasValue("true"), check.That(data.ResourceName).Key("purge_enabled").HasValue("true"), + check.That(data.ResourceName).Key("public_ip_type").HasValue("DualStack"), ), }, data.ImportStep(), @@ -77,6 +79,7 @@ func TestAccKustoCluster_update(t *testing.T) { check.That(data.ResourceName).Key("disk_encryption_enabled").HasValue("false"), check.That(data.ResourceName).Key("streaming_ingestion_enabled").HasValue("false"), check.That(data.ResourceName).Key("purge_enabled").HasValue("false"), + check.That(data.ResourceName).Key("public_ip_type").HasValue("IPv4"), ), }, data.ImportStep(), @@ -400,9 +403,10 @@ resource "azurerm_kusto_cluster" "test" { location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name public_network_access_enabled = false + public_ip_type = "DualStack" sku { - name = "Dev(No SLA)_Standard_D11_v2" - capacity = 1 + name = "Standard_D13_v2" + capacity = 2 } } `, data.RandomInteger, data.Locations.Primary, data.RandomString) @@ -588,6 +592,7 @@ resource "azurerm_kusto_cluster" "test" { disk_encryption_enabled = true streaming_ingestion_enabled = true purge_enabled = true + public_ip_type = "DualStack" sku { name = "Dev(No SLA)_Standard_D11_v2" @@ -856,7 +861,7 @@ resource "azurerm_network_security_group" "test" { resource "azurerm_network_security_rule" "test_allow_management_inbound" { name = "AllowAzureDataExplorerManagement" - priority = 106 + priority = 1000 direction = "Inbound" access = "Allow" protocol = "Tcp" diff --git a/internal/services/kusto/kusto_data_connection_import.go b/internal/services/kusto/kusto_data_connection_import.go index 146f3c816f80..c6f87a87302b 100644 --- a/internal/services/kusto/kusto_data_connection_import.go +++ b/internal/services/kusto/kusto_data_connection_import.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/kusto/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" diff --git a/internal/services/kusto/kusto_database_principal_assignment_resource.go b/internal/services/kusto/kusto_database_principal_assignment_resource.go index 26aeaafea3a7..1d137e03b597 100644 --- a/internal/services/kusto/kusto_database_principal_assignment_resource.go +++ b/internal/services/kusto/kusto_database_principal_assignment_resource.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/kusto/kusto_database_resource.go b/internal/services/kusto/kusto_database_resource.go index 3f59d7d2bdb1..60eb46be401a 100644 --- a/internal/services/kusto/kusto_database_resource.go +++ b/internal/services/kusto/kusto_database_resource.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" diff --git a/internal/services/kusto/kusto_database_script_resource.go b/internal/services/kusto/kusto_database_script_resource.go index fb373feda8bd..dfa4e822a96c 100644 --- a/internal/services/kusto/kusto_database_script_resource.go +++ b/internal/services/kusto/kusto_database_script_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -51,28 +51,42 @@ func resourceKustoDatabaseScript() *pluginsdk.Resource { ValidateFunc: validate.DatabaseID, }, - "url": { + "continue_on_errors_enabled": { + Type: pluginsdk.TypeBool, + Optional: true, + Default: false, + }, + + "force_an_update_when_value_changed": { Type: pluginsdk.TypeString, - Required: true, + Optional: true, + Computed: true, ValidateFunc: validation.StringIsNotEmpty, }, - "sas_token": { + "url": { Type: pluginsdk.TypeString, - Required: true, + Optional: true, + ExactlyOneOf: []string{"url", "script_content"}, + RequiredWith: []string{"sas_token"}, ValidateFunc: validation.StringIsNotEmpty, }, - "continue_on_errors_enabled": { - Type: pluginsdk.TypeBool, - Optional: true, - Default: false, + "sas_token": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + RequiredWith: []string{"url"}, + Sensitive: true, + ValidateFunc: validation.StringIsNotEmpty, }, - "force_an_update_when_value_changed": { + "script_content": { Type: pluginsdk.TypeString, + ExactlyOneOf: []string{"url", "script_content"}, Optional: true, - Computed: true, + ForceNew: true, + Sensitive: true, ValidateFunc: validation.StringIsNotEmpty, }, }, @@ -109,12 +123,23 @@ func resourceKustoDatabaseScriptCreateUpdate(d *pluginsdk.ResourceData, meta int parameters := kusto.Script{ ScriptProperties: &kusto.ScriptProperties{ - ContinueOnErrors: utils.Bool(d.Get("continue_on_errors_enabled").(bool)), - ForceUpdateTag: utils.String(forceUpdateTag), - ScriptURL: utils.String(d.Get("url").(string)), - ScriptURLSasToken: utils.String(d.Get("sas_token").(string)), + ContinueOnErrors: utils.Bool(d.Get("continue_on_errors_enabled").(bool)), + ForceUpdateTag: utils.String(forceUpdateTag), }, } + + if scriptURL, ok := d.GetOk("url"); ok { + parameters.ScriptURL = utils.String(scriptURL.(string)) + } + + if scriptURLSasToken, ok := d.GetOk("sas_token"); ok { + parameters.ScriptURLSasToken = utils.String(scriptURLSasToken.(string)) + } + + if scriptContent, ok := d.GetOk("script_content"); ok { + parameters.ScriptContent = utils.String(scriptContent.(string)) + } + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.ClusterName, id.DatabaseName, id.Name, parameters) if err != nil { return fmt.Errorf("creating %q: %+v", id, err) diff --git a/internal/services/kusto/kusto_database_script_resource_test.go b/internal/services/kusto/kusto_database_script_resource_test.go index 0574bd77d476..723be94a96e1 100644 --- a/internal/services/kusto/kusto_database_script_resource_test.go +++ b/internal/services/kusto/kusto_database_script_resource_test.go @@ -25,7 +25,7 @@ func TestAccKustoScript_basic(t *testing.T) { check.That(data.ResourceName).ExistsInAzure(r), ), }, - data.ImportStep("sas_token"), + data.ImportStep("sas_token", "script_content"), }) } @@ -53,7 +53,7 @@ func TestAccKustoScript_complete(t *testing.T) { check.That(data.ResourceName).ExistsInAzure(r), ), }, - data.ImportStep("sas_token"), + data.ImportStep("sas_token", "script_content"), }) } @@ -67,21 +67,21 @@ func TestAccKustoScript_update(t *testing.T) { check.That(data.ResourceName).ExistsInAzure(r), ), }, - data.ImportStep("sas_token"), + data.ImportStep("sas_token", "script_content"), { Config: r.complete(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, - data.ImportStep("sas_token"), + data.ImportStep("sas_token", "script_content"), { Config: r.basic(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, - data.ImportStep("sas_token"), + data.ImportStep("sas_token", "script_content"), }) } @@ -98,7 +98,21 @@ func TestAccKustoScript_multiple(t *testing.T) { check.That(fmt.Sprintf("%s%d", data.ResourceName, 4)).ExistsInAzure(r), ), }, - data.ImportStep("sas_token"), + data.ImportStep("sas_token", "script_content"), + }) +} + +func TestAccKustoScript_scriptContent(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kusto_script", "test") + r := KustoScriptResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.scriptContent(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("sas_token", "script_content"), }) } @@ -288,3 +302,17 @@ resource "azurerm_kusto_script" "test4" { `, template, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } + +func (r KustoScriptResource) scriptContent(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s +resource "azurerm_kusto_script" "test" { + name = "acctest-ks-%d" + database_id = azurerm_kusto_database.test.id + continue_on_errors_enabled = true + force_an_update_when_value_changed = "first" + script_content = ".create table MyTable (Level:string, Timestamp:datetime, UserId:string, TraceId:string, Message:string, ProcessId:int32)" +} +`, template, data.RandomInteger) +} diff --git a/internal/services/kusto/kusto_eventgrid_data_connection_resource.go b/internal/services/kusto/kusto_eventgrid_data_connection_resource.go index 14e32ba5d23b..68f81b59b898 100644 --- a/internal/services/kusto/kusto_eventgrid_data_connection_resource.go +++ b/internal/services/kusto/kusto_eventgrid_data_connection_resource.go @@ -5,12 +5,13 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/eventhubs" eventhubValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/kusto/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/kusto/validate" @@ -137,6 +138,33 @@ func resourceKustoEventGridDataConnection() *pluginsdk.Resource { string(kusto.EventGridDataFormatW3CLOGFILE), }, false), }, + + "database_routing_type": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + Default: string(kusto.DatabaseRoutingSingle), + ValidateFunc: validation.StringInSlice([]string{ + string(kusto.DatabaseRoutingSingle), + string(kusto.DatabaseRoutingMulti), + }, false), + }, + + "eventgrid_resource_id": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: azure.ValidateResourceID, + }, + + "managed_identity_resource_id": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validate.ClusterID, + commonids.ValidateUserAssignedIdentityID, + ), + }, }, } } @@ -186,6 +214,18 @@ func resourceKustoEventGridDataConnectionCreateUpdate(d *pluginsdk.ResourceData, dataConnection.EventGridConnectionProperties.DataFormat = kusto.EventGridDataFormat(df.(string)) } + if databaseRouting, ok := d.GetOk("database_routing_type"); ok { + dataConnection.DatabaseRouting = kusto.DatabaseRouting(databaseRouting.(string)) + } + + if eventGridRID, ok := d.GetOk("eventgrid_resource_id"); ok { + dataConnection.EventGridConnectionProperties.EventGridResourceID = utils.String(eventGridRID.(string)) + } + + if managedIdentityRID, ok := d.GetOk("managed_identity_resource_id"); ok { + dataConnection.EventGridConnectionProperties.ManagedIdentityResourceID = utils.String(managedIdentityRID.(string)) + } + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.ClusterName, id.DatabaseName, id.Name, dataConnection) if err != nil { return fmt.Errorf("creating %s: %+v", id, err) @@ -235,6 +275,9 @@ func resourceKustoEventGridDataConnectionRead(d *pluginsdk.ResourceData, meta in d.Set("table_name", props.TableName) d.Set("mapping_rule_name", props.MappingRuleName) d.Set("data_format", props.DataFormat) + d.Set("database_routing_type", props.DatabaseRouting) + d.Set("eventgrid_resource_id", props.EventGridResourceID) + d.Set("managed_identity_resource_id", props.ManagedIdentityResourceID) } } diff --git a/internal/services/kusto/kusto_eventgrid_data_connection_resource_test.go b/internal/services/kusto/kusto_eventgrid_data_connection_resource_test.go index 916f69c82eae..6593d320a898 100644 --- a/internal/services/kusto/kusto_eventgrid_data_connection_resource_test.go +++ b/internal/services/kusto/kusto_eventgrid_data_connection_resource_test.go @@ -54,6 +54,7 @@ func TestAccKustoEventGridDataConnection_complete(t *testing.T) { Config: r.complete(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), + check.That(data.ResourceName).Key("database_routing_type").HasValue("Multi"), ), }, data.ImportStep(), @@ -75,6 +76,36 @@ func TestAccKustoEventGridDataConnection_mappingRule(t *testing.T) { }) } +func TestAccKustoEventGridDataConnection_userAssignedIdentity(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kusto_eventgrid_data_connection", "test") + r := KustoEventGridDataConnectionResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.userAssignedIdentity(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccKustoEventGridDataConnection_systemAssignedIdentity(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kusto_eventgrid_data_connection", "test") + r := KustoEventGridDataConnectionResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.systemAssignedIdentity(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccKustoEventGridDataConnection_update(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_kusto_eventgrid_data_connection", "test") r := KustoEventGridDataConnectionResource{} @@ -176,6 +207,9 @@ resource "azurerm_kusto_eventgrid_data_connection" "test" { blob_storage_event_type = "Microsoft.Storage.BlobRenamed" skip_first_record = true + database_routing_type = "Multi" + eventgrid_resource_id = azurerm_eventgrid_event_subscription.test.id + depends_on = [azurerm_eventgrid_event_subscription.test] } `, r.template(data), data.RandomInteger) @@ -206,6 +240,42 @@ resource "azurerm_kusto_eventgrid_data_connection" "test" { `, r.template(data), data.RandomInteger) } +func (r KustoEventGridDataConnectionResource) userAssignedIdentity(data acceptance.TestData) string { + return fmt.Sprintf(` +%s +resource "azurerm_kusto_eventgrid_data_connection" "test" { + name = "acctestkrgdc-%d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + cluster_name = azurerm_kusto_cluster.test.name + database_name = azurerm_kusto_database.test.name + storage_account_id = azurerm_storage_account.test.id + eventhub_id = azurerm_eventhub.test.id + eventhub_consumer_group_name = azurerm_eventhub_consumer_group.test.name + managed_identity_resource_id = azurerm_user_assigned_identity.test.id + depends_on = [azurerm_eventgrid_event_subscription.test] +} +`, r.template(data), data.RandomInteger) +} + +func (r KustoEventGridDataConnectionResource) systemAssignedIdentity(data acceptance.TestData) string { + return fmt.Sprintf(` +%s +resource "azurerm_kusto_eventgrid_data_connection" "test" { + name = "acctestkrgdc-%d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + cluster_name = azurerm_kusto_cluster.test.name + database_name = azurerm_kusto_database.test.name + storage_account_id = azurerm_storage_account.test.id + eventhub_id = azurerm_eventhub.test.id + eventhub_consumer_group_name = azurerm_eventhub_consumer_group.test.name + managed_identity_resource_id = azurerm_kusto_cluster.test.id + depends_on = [azurerm_eventgrid_event_subscription.test] +} +`, r.template(data), data.RandomInteger) +} + func (KustoEventGridDataConnectionResource) template(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { @@ -217,6 +287,12 @@ resource "azurerm_resource_group" "test" { location = "%s" } +resource "azurerm_user_assigned_identity" "test" { + name = "acctest%s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location +} + resource "azurerm_kusto_cluster" "test" { name = "acctestkc%s" location = azurerm_resource_group.test.location @@ -225,6 +301,11 @@ resource "azurerm_kusto_cluster" "test" { name = "Dev(No SLA)_Standard_D11_v2" capacity = 1 } + + identity { + type = "SystemAssigned, UserAssigned" + identity_ids = [azurerm_user_assigned_identity.test.id] + } } resource "azurerm_kusto_database" "test" { @@ -276,5 +357,5 @@ resource "azurerm_eventgrid_event_subscription" "test" { max_delivery_attempts = 10 } } -`, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomInteger, data.RandomString, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomString, data.RandomInteger, data.RandomString, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } diff --git a/internal/services/kusto/kusto_eventhub_data_connection_resource.go b/internal/services/kusto/kusto_eventhub_data_connection_resource.go index 3ae1d6c41203..dd30aabed5ad 100644 --- a/internal/services/kusto/kusto_eventhub_data_connection_resource.go +++ b/internal/services/kusto/kusto_eventhub_data_connection_resource.go @@ -5,12 +5,12 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/eventhubs" eventhubValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/kusto/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/kusto/validate" @@ -141,6 +141,17 @@ func resourceKustoEventHubDataConnection() *pluginsdk.Resource { string(kusto.EventHubDataFormatTXT), }, false), }, + + "database_routing_type": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + Default: string(kusto.DatabaseRoutingSingle), + ValidateFunc: validation.StringInSlice([]string{ + string(kusto.DatabaseRoutingSingle), + string(kusto.DatabaseRoutingMulti), + }, false), + }, }, } } @@ -180,6 +191,10 @@ func resourceKustoEventHubDataConnectionCreateUpdate(d *pluginsdk.ResourceData, EventHubConnectionProperties: eventHubDataConnectionProperties, } + if databaseRouting, ok := d.GetOk("database_routing_type"); ok { + dataConnection1.DatabaseRouting = kusto.DatabaseRouting(databaseRouting.(string)) + } + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.ClusterName, id.DatabaseName, id.Name, dataConnection1) if err != nil { return fmt.Errorf("creating or updating %s: %+v", id, err) @@ -229,6 +244,7 @@ func resourceKustoEventHubDataConnectionRead(d *pluginsdk.ResourceData, meta int d.Set("table_name", props.TableName) d.Set("mapping_rule_name", props.MappingRuleName) d.Set("data_format", props.DataFormat) + d.Set("database_routing_type", props.DatabaseRouting) d.Set("compression", props.Compression) d.Set("event_system_properties", props.EventSystemProperties) d.Set("identity_id", props.ManagedIdentityResourceID) diff --git a/internal/services/kusto/kusto_eventhub_data_connection_resource_test.go b/internal/services/kusto/kusto_eventhub_data_connection_resource_test.go index cda3c9518187..e35cace00520 100644 --- a/internal/services/kusto/kusto_eventhub_data_connection_resource_test.go +++ b/internal/services/kusto/kusto_eventhub_data_connection_resource_test.go @@ -105,6 +105,22 @@ func TestAccKustoEventHubDataConnection_userAssignedIdentity(t *testing.T) { }) } +func TestAccKustoEventHubDataConnection_databaseRoutingType(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_kusto_eventhub_data_connection", "test") + r := KustoEventHubDataConnectionResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.databaseRoutingType(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + check.That(data.ResourceName).Key("database_routing_type").HasValue("Multi"), + ), + }, + data.ImportStep(), + }) +} + func (KustoEventHubDataConnectionResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { id, err := parse.DataConnectionID(state.ID) if err != nil { @@ -257,6 +273,24 @@ resource "azurerm_kusto_eventhub_data_connection" "test" { `, r.template(data), data.RandomInteger) } +func (r KustoEventHubDataConnectionResource) databaseRoutingType(data acceptance.TestData) string { + return fmt.Sprintf(` +%s +resource "azurerm_kusto_eventhub_data_connection" "test" { + name = "acctestkedc-%d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + cluster_name = azurerm_kusto_cluster.test.name + database_name = azurerm_kusto_database.test.name + eventhub_id = azurerm_eventhub.test.id + consumer_group = azurerm_eventhub_consumer_group.test.name + mapping_rule_name = "Json_Mapping" + data_format = "MULTIJSON" + database_routing_type = "Multi" +} +`, r.template(data), data.RandomInteger) +} + func (KustoEventHubDataConnectionResource) template(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/kusto/kusto_iothub_data_connection_resource.go b/internal/services/kusto/kusto_iothub_data_connection_resource.go index 218365f7fb41..8a70245a3085 100644 --- a/internal/services/kusto/kusto_iothub_data_connection_resource.go +++ b/internal/services/kusto/kusto_iothub_data_connection_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" + "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" @@ -121,6 +121,17 @@ func resourceKustoIotHubDataConnection() *pluginsdk.Resource { }, false), }, + "database_routing_type": { + Type: pluginsdk.TypeString, + Optional: true, + ForceNew: true, + Default: string(kusto.DatabaseRoutingSingle), + ValidateFunc: validation.StringInSlice([]string{ + string(kusto.DatabaseRoutingSingle), + string(kusto.DatabaseRoutingMulti), + }, false), + }, + "event_system_properties": { Type: pluginsdk.TypeSet, Optional: true, @@ -173,6 +184,10 @@ func resourceKustoIotHubDataConnectionCreate(d *pluginsdk.ResourceData, meta int IotHubConnectionProperties: iotHubDataConnectionProperties, } + if databaseRouting, ok := d.GetOk("database_routing_type"); ok { + dataConnection.DatabaseRouting = kusto.DatabaseRouting(databaseRouting.(string)) + } + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.ClusterName, id.DatabaseName, id.Name, dataConnection) if err != nil { return fmt.Errorf("creating or updating %s: %+v", id, err) @@ -218,6 +233,7 @@ func resourceKustoIotHubDataConnectionRead(d *pluginsdk.ResourceData, meta inter d.Set("table_name", props.TableName) d.Set("mapping_rule_name", props.MappingRuleName) d.Set("data_format", props.DataFormat) + d.Set("database_routing_type", props.DatabaseRouting) d.Set("shared_access_policy_name", props.SharedAccessPolicyName) d.Set("event_system_properties", utils.FlattenStringSlice(props.EventSystemProperties)) } diff --git a/internal/services/kusto/kusto_iothub_data_connection_resource_test.go b/internal/services/kusto/kusto_iothub_data_connection_resource_test.go index cb022f3c9a2b..0a72cef65ead 100644 --- a/internal/services/kusto/kusto_iothub_data_connection_resource_test.go +++ b/internal/services/kusto/kusto_iothub_data_connection_resource_test.go @@ -39,6 +39,7 @@ func TestAccKustoIotHubDataConnection_complete(t *testing.T) { Config: r.complete(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), + check.That(data.ResourceName).Key("database_routing_type").HasValue("Multi"), ), }, data.ImportStep(), @@ -99,6 +100,7 @@ resource "azurerm_kusto_iothub_data_connection" "test" { event_system_properties = ["message-id", "sequence-number", "to"] mapping_rule_name = "Json_Mapping" data_format = "MULTIJSON" + database_routing_type = "Multi" } `, r.template(data), data.RandomInteger) } diff --git a/internal/services/lighthouse/client/client.go b/internal/services/lighthouse/client/client.go index fe776a43577e..e977d4d0fa76 100644 --- a/internal/services/lighthouse/client/client.go +++ b/internal/services/lighthouse/client/client.go @@ -1,24 +1,25 @@ package client import ( - "github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices" + "github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments" + "github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions" "github.com/hashicorp/terraform-provider-azurerm/internal/common" ) type Client struct { - DefinitionsClient *managedservices.RegistrationDefinitionsClient - AssignmentsClient *managedservices.RegistrationAssignmentsClient + AssignmentsClient *registrationassignments.RegistrationAssignmentsClient + DefinitionsClient *registrationdefinitions.RegistrationDefinitionsClient } func NewClient(o *common.ClientOptions) *Client { - DefinitionsClient := managedservices.NewRegistrationDefinitionsClientWithBaseURI(o.ResourceManagerEndpoint) - o.ConfigureClient(&DefinitionsClient.Client, o.ResourceManagerAuthorizer) + assignmentsClient := registrationassignments.NewRegistrationAssignmentsClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&assignmentsClient.Client, o.ResourceManagerAuthorizer) - AssignmentsClient := managedservices.NewRegistrationAssignmentsClientWithBaseURI(o.ResourceManagerEndpoint) - o.ConfigureClient(&AssignmentsClient.Client, o.ResourceManagerAuthorizer) + definitionsClient := registrationdefinitions.NewRegistrationDefinitionsClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&definitionsClient.Client, o.ResourceManagerAuthorizer) return &Client{ - DefinitionsClient: &DefinitionsClient, - AssignmentsClient: &AssignmentsClient, + DefinitionsClient: &definitionsClient, + AssignmentsClient: &assignmentsClient, } } diff --git a/internal/services/lighthouse/lighthouse_assignment_resource.go b/internal/services/lighthouse/lighthouse_assignment_resource.go index 43bd5cac5069..5ae5f27b77ff 100644 --- a/internal/services/lighthouse/lighthouse_assignment_resource.go +++ b/internal/services/lighthouse/lighthouse_assignment_resource.go @@ -6,12 +6,12 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" + "github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments" + "github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/lighthouse/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/lighthouse/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -25,7 +25,7 @@ func resourceLighthouseAssignment() *pluginsdk.Resource { Delete: resourceLighthouseAssignmentDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.LighthouseAssignmentID(id) + _, err := registrationassignments.ParseScopedRegistrationAssignmentID(id) return err }), @@ -48,7 +48,7 @@ func resourceLighthouseAssignment() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.LighthouseDefinitionID, + ValidateFunc: registrationdefinitions.ValidateScopedRegistrationDefinitionID, }, "scope": { @@ -76,27 +76,26 @@ func resourceLighthouseAssignmentCreate(d *pluginsdk.ResourceData, meta interfac lighthouseAssignmentName = uuid } - id := parse.NewLighthouseAssignmentID(d.Get("scope").(string), lighthouseAssignmentName) - existing, err := client.Get(ctx, id.Scope, id.Name, utils.Bool(false)) + id := registrationassignments.NewScopedRegistrationAssignmentID(d.Get("scope").(string), lighthouseAssignmentName) + options := registrationassignments.GetOperationOptions{ + ExpandRegistrationDefinition: utils.Bool(false), + } + existing, err := client.Get(ctx, id, options) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - parameters := managedservices.RegistrationAssignment{ - Properties: &managedservices.RegistrationAssignmentProperties{ - RegistrationDefinitionID: utils.String(d.Get("lighthouse_definition_id").(string)), + parameters := registrationassignments.RegistrationAssignment{ + Properties: ®istrationassignments.RegistrationAssignmentProperties{ + RegistrationDefinitionId: d.Get("lighthouse_definition_id").(string), }, } - future, err := client.CreateOrUpdate(ctx, id.Scope, id.Name, parameters) - if err != nil { + if err := client.CreateOrUpdateThenPoll(ctx, id, parameters); err != nil { return fmt.Errorf("creating %s: %+v", id, err) } - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation/update of %q: %+v", id, err) - } d.SetId(id.ID()) return resourceLighthouseAssignmentRead(d, meta) @@ -107,14 +106,17 @@ func resourceLighthouseAssignmentRead(d *pluginsdk.ResourceData, meta interface{ ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.LighthouseAssignmentID(d.Id()) + id, err := registrationassignments.ParseScopedRegistrationAssignmentID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.Scope, id.Name, utils.Bool(false)) + options := registrationassignments.GetOperationOptions{ + ExpandRegistrationDefinition: utils.Bool(false), + } + resp, err := client.Get(ctx, *id, options) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[WARN] %s was not found - removing from state", *id) d.SetId("") return nil @@ -123,11 +125,13 @@ func resourceLighthouseAssignmentRead(d *pluginsdk.ResourceData, meta interface{ return fmt.Errorf("retrieving %s: %+v", *id, err) } - d.Set("name", id.Name) + d.Set("name", id.RegistrationAssignmentId) d.Set("scope", id.Scope) - if props := resp.Properties; props != nil { - d.Set("lighthouse_definition_id", props.RegistrationDefinitionID) + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + d.Set("lighthouse_definition_id", props.RegistrationDefinitionId) + } } return nil @@ -138,45 +142,43 @@ func resourceLighthouseAssignmentDelete(d *pluginsdk.ResourceData, meta interfac ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.LighthouseAssignmentID(d.Id()) + id, err := registrationassignments.ParseScopedRegistrationAssignmentID(d.Id()) if err != nil { return err } - future, err := client.Delete(ctx, id.Scope, id.Name) - if err != nil { - return fmt.Errorf("deleting Lighthouse Assignment %q at Scope %q: %+v", id.Name, id.Scope, err) - } - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for deletion of %q: %+v", id, err) + if err := client.DeleteThenPoll(ctx, *id); err != nil { + return fmt.Errorf("deleting %s: %+v", *id, err) } stateConf := &pluginsdk.StateChangeConf{ Pending: []string{"Deleting"}, Target: []string{"Deleted"}, - Refresh: lighthouseAssignmentDeleteRefreshFunc(ctx, client, id.Scope, id.Name), + Refresh: lighthouseAssignmentDeleteRefreshFunc(ctx, client, *id), MinTimeout: 15 * time.Second, Timeout: d.Timeout(pluginsdk.TimeoutDelete), } if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for Lighthouse Assignment %q (Scope %q) to be deleted: %s", id.Name, id.Scope, err) + return err } return nil } -func lighthouseAssignmentDeleteRefreshFunc(ctx context.Context, client *managedservices.RegistrationAssignmentsClient, scope string, lighthouseAssignmentName string) pluginsdk.StateRefreshFunc { +func lighthouseAssignmentDeleteRefreshFunc(ctx context.Context, client *registrationassignments.RegistrationAssignmentsClient, id registrationassignments.ScopedRegistrationAssignmentId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - expandLighthouseDefinition := true - res, err := client.Get(ctx, scope, lighthouseAssignmentName, &expandLighthouseDefinition) + options := registrationassignments.GetOperationOptions{ + ExpandRegistrationDefinition: utils.Bool(true), + } + resp, err := client.Get(ctx, id, options) if err != nil { - if utils.ResponseWasNotFound(res.Response) { - return res, "Deleted", nil + if response.WasNotFound(resp.HttpResponse) { + return resp, "Deleted", nil } - return nil, "Error", fmt.Errorf("issuing read request in lighthouseAssignmentDeleteRefreshFunc to Lighthouse Assignment %q (Scope %q): %s", lighthouseAssignmentName, scope, err) + return nil, "Error", fmt.Errorf("polling to check the deletion of %s: %+v", id, err) } - return res, "Deleting", nil + return resp, "Deleting", nil } } diff --git a/internal/services/lighthouse/lighthouse_assignment_resource_test.go b/internal/services/lighthouse/lighthouse_assignment_resource_test.go index b7949209c564..b67c572c4048 100644 --- a/internal/services/lighthouse/lighthouse_assignment_resource_test.go +++ b/internal/services/lighthouse/lighthouse_assignment_resource_test.go @@ -7,10 +7,10 @@ import ( "testing" "github.com/google/uuid" + "github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/lighthouse/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -90,17 +90,20 @@ func TestAccLighthouseAssignment_emptyID(t *testing.T) { } func (LighthouseAssignmentResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.LighthouseAssignmentID(state.ID) + id, err := registrationassignments.ParseScopedRegistrationAssignmentID(state.ID) if err != nil { return nil, err } - resp, err := clients.Lighthouse.AssignmentsClient.Get(ctx, id.Scope, id.Name, utils.Bool(false)) + options := registrationassignments.GetOperationOptions{ + ExpandRegistrationDefinition: utils.Bool(false), + } + resp, err := clients.Lighthouse.AssignmentsClient.Get(ctx, *id, options) if err != nil { - return nil, fmt.Errorf("retrieving Lighthouse Assignment %q (Scope: %q) does not exist", id.Name, id.Scope) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.Properties != nil), nil + return utils.Bool(resp.Model != nil), nil } func (LighthouseAssignmentResource) basic(id string, secondTenantID string, principalID string, data acceptance.TestData) string { diff --git a/internal/services/lighthouse/lighthouse_definition_resource.go b/internal/services/lighthouse/lighthouse_definition_resource.go index 3cd3488d382e..30f9762016f3 100644 --- a/internal/services/lighthouse/lighthouse_definition_resource.go +++ b/internal/services/lighthouse/lighthouse_definition_resource.go @@ -5,13 +5,12 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices" - frsUUID "github.com/gofrs/uuid" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" + "github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions" "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/lighthouse/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -26,7 +25,7 @@ func resourceLighthouseDefinition() *pluginsdk.Resource { Delete: resourceLighthouseDefinitionDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.LighthouseDefinitionID(id) + _, err := registrationdefinitions.ParseScopedRegistrationDefinitionID(id) return err }), @@ -159,41 +158,34 @@ func resourceLighthouseDefinitionCreateUpdate(d *pluginsdk.ResourceData, meta in lighthouseDefinitionID = uuid } - id := parse.NewLighthouseDefinitionID(d.Get("scope").(string), lighthouseDefinitionID) + id := registrationdefinitions.NewScopedRegistrationDefinitionID(d.Get("scope").(string), lighthouseDefinitionID) if d.IsNewResource() { - existing, err := client.Get(ctx, id.Scope, id.LighthouseDefinitionID) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_lighthouse_definition", id.ID()) } } - authorizations, err := expandLighthouseDefinitionAuthorization(d.Get("authorization").(*pluginsdk.Set).List()) - if err != nil { - return err - } - parameters := managedservices.RegistrationDefinition{ + authorizations := expandLighthouseDefinitionAuthorization(d.Get("authorization").(*pluginsdk.Set).List()) + parameters := registrationdefinitions.RegistrationDefinition{ Plan: expandLighthouseDefinitionPlan(d.Get("plan").([]interface{})), - Properties: &managedservices.RegistrationDefinitionProperties{ + Properties: ®istrationdefinitions.RegistrationDefinitionProperties{ Description: utils.String(d.Get("description").(string)), Authorizations: authorizations, RegistrationDefinitionName: utils.String(d.Get("name").(string)), - ManagedByTenantID: utils.String(d.Get("managing_tenant_id").(string)), + ManagedByTenantId: d.Get("managing_tenant_id").(string), }, } // NOTE: this API call uses DefinitionId then Scope - check in the future - future, err := client.CreateOrUpdate(ctx, id.LighthouseDefinitionID, id.Scope, parameters) - if err != nil { + if err := client.CreateOrUpdateThenPoll(ctx, id, parameters); err != nil { return fmt.Errorf("creating/updating %s: %+v", id, err) } - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation/update of %q: %+v", id, err) - } d.SetId(id.ID()) return resourceLighthouseDefinitionRead(d, meta) @@ -204,14 +196,14 @@ func resourceLighthouseDefinitionRead(d *pluginsdk.ResourceData, meta interface{ ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.LighthouseDefinitionID(d.Id()) + id, err := registrationdefinitions.ParseScopedRegistrationDefinitionID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.Scope, id.LighthouseDefinitionID) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[WARN] %s was not found - removing from state", *id) d.SetId("") return nil @@ -220,20 +212,22 @@ func resourceLighthouseDefinitionRead(d *pluginsdk.ResourceData, meta interface{ return fmt.Errorf("retrieving %s: %+v", *id, err) } - d.Set("lighthouse_definition_id", id.LighthouseDefinitionID) + d.Set("lighthouse_definition_id", id.RegistrationDefinitionId) d.Set("scope", id.Scope) - if err := d.Set("plan", flattenLighthouseDefinitionPlan(resp.Plan)); err != nil { - return fmt.Errorf("setting `plan`: %+v", err) - } + if model := resp.Model; model != nil { + if err := d.Set("plan", flattenLighthouseDefinitionPlan(model.Plan)); err != nil { + return fmt.Errorf("setting `plan`: %+v", err) + } - if props := resp.Properties; props != nil { - if err := d.Set("authorization", flattenLighthouseDefinitionAuthorization(props.Authorizations)); err != nil { - return fmt.Errorf("setting `authorization`: %+v", err) + if props := model.Properties; props != nil { + if err := d.Set("authorization", flattenLighthouseDefinitionAuthorization(props.Authorizations)); err != nil { + return fmt.Errorf("setting `authorization`: %+v", err) + } + d.Set("description", props.Description) + d.Set("name", props.RegistrationDefinitionName) + d.Set("managing_tenant_id", props.ManagedByTenantId) } - d.Set("description", props.Description) - d.Set("name", props.RegistrationDefinitionName) - d.Set("managing_tenant_id", props.ManagedByTenantID) } return nil @@ -244,129 +238,78 @@ func resourceLighthouseDefinitionDelete(d *pluginsdk.ResourceData, meta interfac ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.LighthouseDefinitionID(d.Id()) + id, err := registrationdefinitions.ParseScopedRegistrationDefinitionID(d.Id()) if err != nil { return err } - if _, err = client.Delete(ctx, id.LighthouseDefinitionID, id.Scope); err != nil { + if _, err = client.Delete(ctx, *id); err != nil { return fmt.Errorf("deleting %s: %+v", *id, err) } return nil } -func flattenLighthouseDefinitionAuthorization(input *[]managedservices.Authorization) []interface{} { +func flattenLighthouseDefinitionAuthorization(input []registrationdefinitions.Authorization) []interface{} { results := make([]interface{}, 0) - if input == nil { - return results - } - - for _, item := range *input { - principalID := "" - if item.PrincipalID != nil { - principalID = *item.PrincipalID - } - - roleDefinitionID := "" - if item.RoleDefinitionID != nil { - roleDefinitionID = *item.RoleDefinitionID - } - + for _, item := range input { principalIDDisplayName := "" - if item.PrincipalIDDisplayName != nil { - principalIDDisplayName = *item.PrincipalIDDisplayName + if item.PrincipalIdDisplayName != nil { + principalIDDisplayName = *item.PrincipalIdDisplayName } results = append(results, map[string]interface{}{ - "role_definition_id": roleDefinitionID, - "principal_id": principalID, + "role_definition_id": item.RoleDefinitionId, + "principal_id": item.PrincipalId, "principal_display_name": principalIDDisplayName, - "delegated_role_definition_ids": flattenLighthouseDefinitionAuthorizationDelegatedRoleDefinitionIds(item.DelegatedRoleDefinitionIds), + "delegated_role_definition_ids": utils.FlattenStringSlice(item.DelegatedRoleDefinitionIds), }) } return results } -func flattenLighthouseDefinitionAuthorizationDelegatedRoleDefinitionIds(input *[]frsUUID.UUID) []interface{} { - if input == nil { - return []interface{}{} - } - result := make([]interface{}, 0) - for _, item := range *input { - result = append(result, item.String()) - } - return result -} - -func expandLighthouseDefinitionAuthorization(input []interface{}) (*[]managedservices.Authorization, error) { - results := make([]managedservices.Authorization, 0) +func expandLighthouseDefinitionAuthorization(input []interface{}) []registrationdefinitions.Authorization { + results := make([]registrationdefinitions.Authorization, 0) for _, item := range input { v := item.(map[string]interface{}) - delegatedRoleDefinitionIds, err := expandLighthouseDefinitionAuthorizationDelegatedRoleDefinitionIds(v["delegated_role_definition_ids"].(*pluginsdk.Set).List()) - if err != nil { - return nil, err - } - result := managedservices.Authorization{ - RoleDefinitionID: utils.String(v["role_definition_id"].(string)), - PrincipalID: utils.String(v["principal_id"].(string)), - PrincipalIDDisplayName: utils.String(v["principal_display_name"].(string)), + delegatedRoleDefinitionIds := utils.ExpandStringSlice(v["delegated_role_definition_ids"].(*pluginsdk.Set).List()) + result := registrationdefinitions.Authorization{ + RoleDefinitionId: v["role_definition_id"].(string), + PrincipalId: v["principal_id"].(string), + PrincipalIdDisplayName: utils.String(v["principal_display_name"].(string)), DelegatedRoleDefinitionIds: delegatedRoleDefinitionIds, } results = append(results, result) } - return &results, nil -} - -func expandLighthouseDefinitionAuthorizationDelegatedRoleDefinitionIds(input []interface{}) (*[]frsUUID.UUID, error) { - result := make([]frsUUID.UUID, 0) - for _, item := range input { - id, err := frsUUID.FromString(item.(string)) - if err != nil { - return nil, fmt.Errorf("parsing %q as a UUID: %+v", item, err) - } - result = append(result, id) - } - return &result, nil + return results } -func expandLighthouseDefinitionPlan(input []interface{}) *managedservices.Plan { +func expandLighthouseDefinitionPlan(input []interface{}) *registrationdefinitions.Plan { if len(input) == 0 || input[0] == nil { return nil } + raw := input[0].(map[string]interface{}) - return &managedservices.Plan{ - Name: utils.String(raw["name"].(string)), - Publisher: utils.String(raw["publisher"].(string)), - Product: utils.String(raw["product"].(string)), - Version: utils.String(raw["version"].(string)), + return ®istrationdefinitions.Plan{ + Name: raw["name"].(string), + Publisher: raw["publisher"].(string), + Product: raw["product"].(string), + Version: raw["version"].(string), } } -func flattenLighthouseDefinitionPlan(input *managedservices.Plan) []interface{} { +func flattenLighthouseDefinitionPlan(input *registrationdefinitions.Plan) []interface{} { if input == nil { return []interface{}{} } - var name, publisher, product, version string - if input.Name != nil { - name = *input.Name - } - if input.Publisher != nil { - publisher = *input.Publisher - } - if input.Product != nil { - product = *input.Product - } - if input.Version != nil { - version = *input.Version - } + return []interface{}{ map[string]interface{}{ - "name": name, - "publisher": publisher, - "product": product, - "version": version, + "name": input.Name, + "publisher": input.Publisher, + "product": input.Product, + "version": input.Version, }, } } diff --git a/internal/services/lighthouse/lighthouse_definition_resource_test.go b/internal/services/lighthouse/lighthouse_definition_resource_test.go index 88c5dac36989..ffd104b54a4a 100644 --- a/internal/services/lighthouse/lighthouse_definition_resource_test.go +++ b/internal/services/lighthouse/lighthouse_definition_resource_test.go @@ -7,10 +7,10 @@ import ( "testing" "github.com/google/uuid" + "github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/lighthouse/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -194,17 +194,17 @@ func TestAccLighthouseDefinition_plan(t *testing.T) { } func (LighthouseDefinitionResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.LighthouseDefinitionID(state.ID) + id, err := registrationdefinitions.ParseScopedRegistrationDefinitionID(state.ID) if err != nil { return nil, err } - resp, err := clients.Lighthouse.DefinitionsClient.Get(ctx, id.Scope, id.LighthouseDefinitionID) + resp, err := clients.Lighthouse.DefinitionsClient.Get(ctx, *id) if err != nil { - return nil, fmt.Errorf("retrieving Lighthouse Definition %q (Scope: %q) does not exist", id.LighthouseDefinitionID, id.Scope) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.Properties != nil), nil + return utils.Bool(resp.Model != nil), nil } func (LighthouseDefinitionResource) basic(id string, secondTenantID string, principalID string, data acceptance.TestData) string { diff --git a/internal/services/loadbalancer/backend_address_pool_address_resource.go b/internal/services/loadbalancer/backend_address_pool_address_resource.go index e7f947cffa99..2ca06709a182 100644 --- a/internal/services/loadbalancer/backend_address_pool_address_resource.go +++ b/internal/services/loadbalancer/backend_address_pool_address_resource.go @@ -24,10 +24,40 @@ var ( type BackendAddressPoolAddressResource struct{} type BackendAddressPoolAddressModel struct { - Name string `tfschema:"name"` - BackendAddressPoolId string `tfschema:"backend_address_pool_id"` - VirtualNetworkId string `tfschema:"virtual_network_id"` - IPAddress string `tfschema:"ip_address"` + Name string `tfschema:"name"` + BackendAddressPoolId string `tfschema:"backend_address_pool_id"` + VirtualNetworkId string `tfschema:"virtual_network_id"` + IPAddress string `tfschema:"ip_address"` + PortMapping []inboundNATRulePortMapping `tfschema:"inbound_nat_rule_port_mapping"` +} + +type inboundNATRulePortMapping struct { + Name string `tfschema:"inbound_nat_rule_name"` + FrontendPort int32 `tfschema:"frontend_port"` + BackendPort int32 `tfschema:"backend_port"` +} + +func portMapping() *pluginsdk.Schema { + return &pluginsdk.Schema{ + Type: pluginsdk.TypeList, + Computed: true, + Elem: &pluginsdk.Resource{ + Schema: map[string]*pluginsdk.Schema{ + "inbound_nat_rule_name": { + Type: pluginsdk.TypeString, + Computed: true, + }, + "frontend_port": { + Type: pluginsdk.TypeInt, + Computed: true, + }, + "backend_port": { + Type: pluginsdk.TypeInt, + Computed: true, + }, + }, + }, + } } func (r BackendAddressPoolAddressResource) Arguments() map[string]*pluginsdk.Schema { @@ -61,7 +91,9 @@ func (r BackendAddressPoolAddressResource) Arguments() map[string]*pluginsdk.Sch } func (r BackendAddressPoolAddressResource) Attributes() map[string]*pluginsdk.Schema { - return map[string]*pluginsdk.Schema{} + return map[string]*pluginsdk.Schema{ + "inbound_nat_rule_port_mapping": portMapping(), + } } func (r BackendAddressPoolAddressResource) ModelObject() interface{} { @@ -206,6 +238,25 @@ func (r BackendAddressPoolAddressResource) Read() sdk.ResourceFunc { } } + var inboundNATRulePortMappingList []inboundNATRulePortMapping + if rules := backendAddress.LoadBalancerBackendAddressPropertiesFormat.InboundNatRulesPortMapping; rules != nil { + for _, rule := range *rules { + rulePortMapping := inboundNATRulePortMapping{} + + if rule.InboundNatRuleName != nil { + rulePortMapping.Name = *rule.InboundNatRuleName + } + if rule.FrontendPort != nil { + rulePortMapping.FrontendPort = *rule.FrontendPort + } + + if rule.BackendPort != nil { + rulePortMapping.BackendPort = *rule.BackendPort + } + inboundNATRulePortMappingList = append(inboundNATRulePortMappingList, rulePortMapping) + } + model.PortMapping = inboundNATRulePortMappingList + } return metadata.Encode(&model) }, Timeout: 5 * time.Minute, @@ -216,6 +267,7 @@ func (r BackendAddressPoolAddressResource) Delete() sdk.ResourceFunc { return sdk.ResourceFunc{ Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { client := metadata.Client.LoadBalancers.LoadBalancerBackendAddressPoolsClient + lbClient := metadata.Client.LoadBalancers.LoadBalancersClient id, err := parse.BackendAddressPoolAddressID(metadata.ResourceData.Id()) if err != nil { return err @@ -232,6 +284,20 @@ func (r BackendAddressPoolAddressResource) Delete() sdk.ResourceFunc { return fmt.Errorf("retrieving %s: `properties` was nil", *id) } + timeout, _ := ctx.Deadline() + lbStatus := &pluginsdk.StateChangeConf{ + Pending: []string{string(network.ProvisioningStateUpdating)}, + Target: []string{string(network.ProvisioningStateSucceeded)}, + MinTimeout: 5 * time.Second, + Refresh: loadbalacnerProvisioningStatusRefreshFunc(ctx, lbClient, *id), + ContinuousTargetOccurence: 10, + Timeout: time.Until(timeout), + } + + if _, err := lbStatus.WaitForStateContext(ctx); err != nil { + return fmt.Errorf("waiting for parent resource loadbalancer status to be ready error: %+v", err) + } + addresses := make([]network.LoadBalancerBackendAddress, 0) if pool.BackendAddressPoolPropertiesFormat.LoadBalancerBackendAddresses != nil { addresses = *pool.BackendAddressPoolPropertiesFormat.LoadBalancerBackendAddresses @@ -271,6 +337,7 @@ func (r BackendAddressPoolAddressResource) Update() sdk.ResourceFunc { return sdk.ResourceFunc{ Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { client := metadata.Client.LoadBalancers.LoadBalancerBackendAddressPoolsClient + lbClient := metadata.Client.LoadBalancers.LoadBalancersClient id, err := parse.BackendAddressPoolAddressID(metadata.ResourceData.Id()) if err != nil { return err @@ -322,6 +389,20 @@ func (r BackendAddressPoolAddressResource) Update() sdk.ResourceFunc { } pool.BackendAddressPoolPropertiesFormat.LoadBalancerBackendAddresses = &addresses + timeout, _ := ctx.Deadline() + lbStatus := &pluginsdk.StateChangeConf{ + Pending: []string{string(network.ProvisioningStateUpdating)}, + Target: []string{string(network.ProvisioningStateSucceeded)}, + MinTimeout: 5 * time.Minute, + Refresh: loadbalacnerProvisioningStatusRefreshFunc(ctx, lbClient, *id), + ContinuousTargetOccurence: 10, + Timeout: time.Until(timeout), + } + + if _, err := lbStatus.WaitForStateContext(ctx); err != nil { + return fmt.Errorf("waiting for parent resource loadbalancer status to be ready error: %+v", err) + } + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.LoadBalancerName, id.BackendAddressPoolName, pool) if err != nil { return fmt.Errorf("updating %s: %+v", *id, err) @@ -334,3 +415,13 @@ func (r BackendAddressPoolAddressResource) Update() sdk.ResourceFunc { Timeout: 30 * time.Minute, } } + +func loadbalacnerProvisioningStatusRefreshFunc(ctx context.Context, client *network.LoadBalancersClient, id parse.BackendAddressPoolAddressId) pluginsdk.StateRefreshFunc { + return func() (interface{}, string, error) { + lbClient, err := client.Get(ctx, id.ResourceGroup, id.LoadBalancerName, "") + if err != nil { + return nil, "", fmt.Errorf("retrieving load balancer error: %+v", err) + } + return lbClient, string(lbClient.ProvisioningState), nil + } +} diff --git a/internal/services/loadbalancer/backend_address_pool_data_source.go b/internal/services/loadbalancer/backend_address_pool_data_source.go index 3e9c744e86ac..0b19f540b8ea 100644 --- a/internal/services/loadbalancer/backend_address_pool_data_source.go +++ b/internal/services/loadbalancer/backend_address_pool_data_source.go @@ -53,6 +53,27 @@ func dataSourceArmLoadBalancerBackendAddressPool() *pluginsdk.Resource { Type: pluginsdk.TypeString, Computed: true, }, + + "inbound_nat_rule_port_mapping": { + Type: pluginsdk.TypeList, + Computed: true, + Elem: &pluginsdk.Resource{ + Schema: map[string]*pluginsdk.Schema{ + "inbound_nat_rule_name": { + Type: pluginsdk.TypeString, + Computed: true, + }, + "frontend_port": { + Type: pluginsdk.TypeInt, + Computed: true, + }, + "backend_port": { + Type: pluginsdk.TypeInt, + Computed: true, + }, + }, + }, + }, }, }, }, @@ -85,6 +106,14 @@ func dataSourceArmLoadBalancerBackendAddressPool() *pluginsdk.Resource { Type: pluginsdk.TypeString, }, }, + + "inbound_nat_rules": { + Type: pluginsdk.TypeList, + Computed: true, + Elem: &pluginsdk.Schema{ + Type: pluginsdk.TypeString, + }, + }, }, } } @@ -155,6 +184,19 @@ func dataSourceArmLoadBalancerBackendAddressPoolRead(d *pluginsdk.ResourceData, if err := d.Set("outbound_rules", outboundRules); err != nil { return fmt.Errorf("setting `outbound_rules`: %v", err) } + + var inboundNATRules []string + if rules := props.InboundNatRules; rules != nil { + for _, rule := range *rules { + if rule.ID == nil { + continue + } + inboundNATRules = append(inboundNATRules, *rule.ID) + } + } + if err := d.Set("inbound_nat_rules", inboundNATRules); err != nil { + return fmt.Errorf("setting `inbound_nat_rules`: %v", err) + } } return nil @@ -177,6 +219,7 @@ func flattenArmLoadBalancerBackendAddresses(input *[]network.LoadBalancerBackend ipAddress string vnetId string ) + var inboundNATRulePortMappingList []interface{} if prop := e.LoadBalancerBackendAddressPropertiesFormat; prop != nil { if prop.IPAddress != nil { ipAddress = *prop.IPAddress @@ -184,12 +227,31 @@ func flattenArmLoadBalancerBackendAddresses(input *[]network.LoadBalancerBackend if prop.VirtualNetwork != nil && prop.VirtualNetwork.ID != nil { vnetId = *prop.VirtualNetwork.ID } + if prop.InboundNatRulesPortMapping != nil { + rules := prop.InboundNatRulesPortMapping + for _, rule := range *rules { + rulePortMapping := make(map[string]interface{}) + + if rule.InboundNatRuleName != nil { + rulePortMapping["inbound_nat_rule_name"] = *rule.InboundNatRuleName + } + if rule.FrontendPort != nil { + rulePortMapping["frontendPort"] = *rule.FrontendPort + } + + if rule.BackendPort != nil { + rulePortMapping["backendPort"] = *rule.BackendPort + } + inboundNATRulePortMappingList = append(inboundNATRulePortMappingList, rulePortMapping) + } + } } v := map[string]interface{}{ - "name": name, - "virtual_network_id": vnetId, - "ip_address": ipAddress, + "name": name, + "virtual_network_id": vnetId, + "ip_address": ipAddress, + "inbound_nat_rule_port_mapping": inboundNATRulePortMappingList, } output = append(output, v) } diff --git a/internal/services/loadbalancer/backend_address_pool_resource.go b/internal/services/loadbalancer/backend_address_pool_resource.go index 53efb9f50460..c6e4407c4134 100644 --- a/internal/services/loadbalancer/backend_address_pool_resource.go +++ b/internal/services/loadbalancer/backend_address_pool_resource.go @@ -109,6 +109,14 @@ func resourceArmLoadBalancerBackendAddressPool() *pluginsdk.Resource { }, }, + "inbound_nat_rules": { + Type: pluginsdk.TypeList, + Computed: true, + Elem: &pluginsdk.Schema{ + Type: pluginsdk.TypeString, + }, + }, + "load_balancing_rules": { Type: pluginsdk.TypeList, Computed: true, @@ -312,6 +320,19 @@ func resourceArmLoadBalancerBackendAddressPoolRead(d *pluginsdk.ResourceData, me if err := d.Set("outbound_rules", outboundRules); err != nil { return fmt.Errorf("setting `outbound_rules`: %v", err) } + + var inboundNATRules []string + if rules := props.InboundNatRules; rules != nil { + for _, rule := range *rules { + if rule.ID == nil { + continue + } + inboundNATRules = append(inboundNATRules, *rule.ID) + } + } + if err := d.Set("inbound_nat_rules", inboundNATRules); err != nil { + return fmt.Errorf("setting `inbound_nat_rules`: %v", err) + } } return nil diff --git a/internal/services/loadbalancer/loadbalancer_nat_rule_resource_test.go b/internal/services/loadbalancer/loadbalancer_nat_rule_resource_test.go index 27f9f1d95d55..dbe50698e957 100644 --- a/internal/services/loadbalancer/loadbalancer_nat_rule_resource_test.go +++ b/internal/services/loadbalancer/loadbalancer_nat_rule_resource_test.go @@ -46,6 +46,58 @@ func TestAccAzureRMLoadBalancerNatRule_complete(t *testing.T) { }) } +func TestAccAzureRMLoadBalancerNatRule_mapToBackendAddressPool(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_lb_nat_rule", "test") + r := LoadBalancerNatRule{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.mapToBackendAddressPool(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccAzureRMLoadBalancerNatRule_mapToBackendAddressPoolUpdate(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_lb_nat_rule", "test") + r := LoadBalancerNatRule{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.complete(data, "Standard"), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.mapToBackendAddressPool(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccAzureRMLoadBalancerNatRule_mapToBackendAddressPoolMultiple(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_lb_nat_rule", "test") + r := LoadBalancerNatRule{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.multipleRuleMapToBackendAddressPool(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccAzureRMLoadBalancerNatRule_update(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_lb_nat_rule", "test") r := LoadBalancerNatRule{} @@ -361,6 +413,65 @@ resource "azurerm_lb_nat_rule" "test2" { `, template, data.RandomInteger, data2.RandomInteger) } +func (r LoadBalancerNatRule) mapToBackendAddressPool(data acceptance.TestData) string { + template := r.template(data, "Standard") + return fmt.Sprintf(` +%s +resource "azurerm_virtual_network" "test" { + name = "acctestvn-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + address_space = ["192.168.0.0/16"] +} + +resource "azurerm_lb_backend_address_pool" "test" { + name = "internal" + loadbalancer_id = azurerm_lb.test.id +} + +resource "azurerm_lb_backend_address_pool_address" "test" { + name = "address" + backend_address_pool_id = azurerm_lb_backend_address_pool.test.id + virtual_network_id = azurerm_virtual_network.test.id + ip_address = "191.168.0.1" +} + +resource "azurerm_lb_nat_rule" "test" { + name = "NatRule-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + loadbalancer_id = "${azurerm_lb.test.id}" + + protocol = "Tcp" + frontend_port_start = 3000 + frontend_port_end = 3389 + backend_port = 3389 + backend_address_pool_id = azurerm_lb_backend_address_pool.test.id + + frontend_ip_configuration_name = azurerm_lb.test.frontend_ip_configuration.0.name +} +`, template, data.RandomInteger, data.RandomInteger) +} + +func (r LoadBalancerNatRule) multipleRuleMapToBackendAddressPool(data acceptance.TestData) string { + template := r.mapToBackendAddressPool(data) + return fmt.Sprintf(` +%s +resource "azurerm_lb_nat_rule" "test1" { + name = "NatRule2-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + loadbalancer_id = "${azurerm_lb.test.id}" + + protocol = "Udp" + frontend_port_start = 3000 + frontend_port_end = 3389 + backend_port = 3389 + backend_address_pool_id = azurerm_lb_backend_address_pool.test.id + + frontend_ip_configuration_name = azurerm_lb.test.frontend_ip_configuration.0.name +} +`, template, data.RandomInteger) +} + func (r LoadBalancerNatRule) zeroPortNumber(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/loadbalancer/loadbalancer_resource.go b/internal/services/loadbalancer/loadbalancer_resource.go index 7cceac284127..944e065427f6 100644 --- a/internal/services/loadbalancer/loadbalancer_resource.go +++ b/internal/services/loadbalancer/loadbalancer_resource.go @@ -6,22 +6,20 @@ import ( "strings" "time" + "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/edgezones" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/zones" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/loadbalancer/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tf/state" - "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/loadbalancer/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/loadbalancer/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/state" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" diff --git a/internal/services/loadbalancer/nat_rule_resource.go b/internal/services/loadbalancer/nat_rule_resource.go index 1dcfa6f1843e..9a3468fe4b61 100644 --- a/internal/services/loadbalancer/nat_rule_resource.go +++ b/internal/services/loadbalancer/nat_rule_resource.go @@ -71,9 +71,10 @@ func resourceArmLoadBalancerNatRule() *pluginsdk.Resource { }, "frontend_port": { - Type: pluginsdk.TypeInt, - Required: true, - ValidateFunc: validate.PortNumberOrZero, + Type: pluginsdk.TypeInt, + Optional: true, + ValidateFunc: validate.PortNumberOrZero, + ConflictsWith: []string{"frontend_port_start", "frontend_port_end", "backend_address_pool_id"}, }, "backend_port": { @@ -101,6 +102,30 @@ func resourceArmLoadBalancerNatRule() *pluginsdk.Resource { Optional: true, }, + "backend_address_pool_id": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: azure.ValidateResourceID, + ConflictsWith: []string{"frontend_port"}, + RequiredWith: []string{"frontend_port_start", "frontend_port_end"}, + }, + + "frontend_port_start": { + Type: pluginsdk.TypeInt, + Optional: true, + ValidateFunc: validate.PortNumber, + RequiredWith: []string{"backend_address_pool_id", "frontend_port_end"}, + ConflictsWith: []string{"frontend_port"}, + }, + + "frontend_port_end": { + Type: pluginsdk.TypeInt, + Optional: true, + ValidateFunc: validate.PortNumber, + RequiredWith: []string{"backend_address_pool_id", "frontend_port_start"}, + ConflictsWith: []string{"frontend_port"}, + }, + "idle_timeout_in_minutes": { Type: pluginsdk.TypeInt, Optional: true, @@ -241,11 +266,22 @@ func resourceArmLoadBalancerNatRuleRead(d *pluginsdk.ResourceData, meta interfac d.Set("frontend_ip_configuration_name", frontendIPConfigName) d.Set("frontend_ip_configuration_id", frontendIPConfigID) + if props.BackendAddressPool != nil && props.BackendAddressPool.ID != nil { + d.Set("backend_address_pool_id", *props.BackendAddressPool.ID) + } + frontendPort := 0 if props.FrontendPort != nil { frontendPort = int(*props.FrontendPort) + d.Set("frontend_port", frontendPort) + } + + if props.FrontendPortRangeStart != nil { + d.Set("frontend_port_start", int(*props.FrontendPortRangeStart)) + } + if props.FrontendPortRangeEnd != nil { + d.Set("frontend_port_end", int(*props.FrontendPortRangeEnd)) } - d.Set("frontend_port", frontendPort) idleTimeoutInMinutes := 0 if props.IdleTimeoutInMinutes != nil { @@ -305,11 +341,33 @@ func resourceArmLoadBalancerNatRuleDelete(d *pluginsdk.ResourceData, meta interf func expandAzureRmLoadBalancerNatRule(d *pluginsdk.ResourceData, lb *network.LoadBalancer, loadBalancerId parse.LoadBalancerId) (*network.InboundNatRule, error) { properties := network.InboundNatRulePropertiesFormat{ Protocol: network.TransportProtocol(d.Get("protocol").(string)), - FrontendPort: utils.Int32(int32(d.Get("frontend_port").(int))), BackendPort: utils.Int32(int32(d.Get("backend_port").(int))), EnableTCPReset: utils.Bool(d.Get("enable_tcp_reset").(bool)), } + backendAddressPoolSet, frontendPort := false, false + if port := d.Get("frontend_port"); port != "" { + frontendPort = true + } + if _, ok := d.GetOk("backend_address_pool_id"); ok { + backendAddressPoolSet = true + } + + if backendAddressPoolSet { + properties.FrontendPortRangeStart = utils.Int32(int32(d.Get("frontend_port_start").(int))) + properties.FrontendPortRangeEnd = utils.Int32(int32(d.Get("frontend_port_end").(int))) + properties.BackendAddressPool = &network.SubResource{ + ID: utils.String(d.Get("backend_address_pool_id").(string)), + } + } else { + if frontendPort { + properties.FrontendPort = utils.Int32(int32(d.Get("frontend_port").(int))) + } else { + properties.FrontendPortRangeStart = utils.Int32(int32(d.Get("frontend_port_start").(int))) + properties.FrontendPortRangeEnd = utils.Int32(int32(d.Get("frontend_port_end").(int))) + } + } + if v, ok := d.GetOk("enable_floating_ip"); ok { properties.EnableFloatingIP = utils.Bool(v.(bool)) } diff --git a/internal/services/loadbalancer/rule_resource.go b/internal/services/loadbalancer/rule_resource.go index 6f18a329afbc..00f1cb05c966 100644 --- a/internal/services/loadbalancer/rule_resource.go +++ b/internal/services/loadbalancer/rule_resource.go @@ -5,14 +5,13 @@ import ( "log" "time" - "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" - loadBalancerValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/loadbalancer/validate" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" + "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" "github.com/hashicorp/terraform-provider-azurerm/internal/services/loadbalancer/parse" + loadBalancerValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/loadbalancer/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" diff --git a/internal/services/loganalytics/log_analytics_cluster_customer_managed_key_resource.go b/internal/services/loganalytics/log_analytics_cluster_customer_managed_key_resource.go index 51b4b324dc3f..4c34759829b9 100644 --- a/internal/services/loganalytics/log_analytics_cluster_customer_managed_key_resource.go +++ b/internal/services/loganalytics/log_analytics_cluster_customer_managed_key_resource.go @@ -5,13 +5,12 @@ import ( "log" "time" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/migration" - "github.com/Azure/azure-sdk-for-go/services/operationalinsights/mgmt/2020-08-01/operationalinsights" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" keyVaultParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/migration" "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" diff --git a/internal/services/loganalytics/log_analytics_cluster_resource.go b/internal/services/loganalytics/log_analytics_cluster_resource.go index f2143acf8018..177dc7550cfd 100644 --- a/internal/services/loganalytics/log_analytics_cluster_resource.go +++ b/internal/services/loganalytics/log_analytics_cluster_resource.go @@ -5,10 +5,9 @@ import ( "log" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" - "github.com/Azure/azure-sdk-for-go/services/operationalinsights/mgmt/2020-08-01/operationalinsights" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/loganalytics/log_analytics_saved_search_resource.go b/internal/services/loganalytics/log_analytics_saved_search_resource.go index 53de455e0507..d70bce3aacc0 100644 --- a/internal/services/loganalytics/log_analytics_saved_search_resource.go +++ b/internal/services/loganalytics/log_analytics_saved_search_resource.go @@ -6,11 +6,10 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/migration" - "github.com/Azure/azure-sdk-for-go/services/operationalinsights/mgmt/2020-08-01/operationalinsights" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/migration" "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" diff --git a/internal/services/loganalytics/migration/saved_search_v0_to_v1.go b/internal/services/loganalytics/migration/saved_search_v0_to_v1.go index 2e5cfc85b73b..c73f122a4808 100644 --- a/internal/services/loganalytics/migration/saved_search_v0_to_v1.go +++ b/internal/services/loganalytics/migration/saved_search_v0_to_v1.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" diff --git a/internal/services/logic/logic_app_standard_resource.go b/internal/services/logic/logic_app_standard_resource.go index dbea093deaf2..7fe71b370b90 100644 --- a/internal/services/logic/logic_app_standard_resource.go +++ b/internal/services/logic/logic_app_standard_resource.go @@ -7,11 +7,9 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/logz/client/client.go b/internal/services/logz/client/client.go index f2dcd91a9020..ff2e19423bee 100644 --- a/internal/services/logz/client/client.go +++ b/internal/services/logz/client/client.go @@ -6,8 +6,9 @@ import ( ) type Client struct { - MonitorClient *logz.MonitorsClient - TagRuleClient *logz.TagRulesClient + MonitorClient *logz.MonitorsClient + TagRuleClient *logz.TagRulesClient + SubAccountClient *logz.SubAccountClient } func NewClient(o *common.ClientOptions) *Client { @@ -17,8 +18,12 @@ func NewClient(o *common.ClientOptions) *Client { tagRuleClient := logz.NewTagRulesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&tagRuleClient.Client, o.ResourceManagerAuthorizer) + subAccountClient := logz.NewSubAccountClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&subAccountClient.Client, o.ResourceManagerAuthorizer) + return &Client{ - MonitorClient: &monitorClient, - TagRuleClient: &tagRuleClient, + MonitorClient: &monitorClient, + TagRuleClient: &tagRuleClient, + SubAccountClient: &subAccountClient, } } diff --git a/internal/services/logz/logz_common.go b/internal/services/logz/logz_common.go new file mode 100644 index 000000000000..e51f9321a8ee --- /dev/null +++ b/internal/services/logz/logz_common.go @@ -0,0 +1,97 @@ +package logz + +import ( + "github.com/Azure/azure-sdk-for-go/services/logz/mgmt/2020-10-01/logz" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +func SchemaUserInfo() *pluginsdk.Schema { + return &pluginsdk.Schema{ + Type: pluginsdk.TypeList, + Required: true, + ForceNew: true, + MaxItems: 1, + Elem: &pluginsdk.Resource{ + Schema: map[string]*pluginsdk.Schema{ + "email": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "first_name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 50), + }, + + "last_name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 50), + }, + + "phone_number": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 40), + }, + }, + }, + } +} + +func expandUserInfo(input []interface{}) *logz.UserInfo { + if len(input) == 0 || input[0] == nil { + return nil + } + + v := input[0].(map[string]interface{}) + return &logz.UserInfo{ + FirstName: utils.String(v["first_name"].(string)), + LastName: utils.String(v["last_name"].(string)), + EmailAddress: utils.String(v["email"].(string)), + PhoneNumber: utils.String(v["phone_number"].(string)), + } +} + +func flattenUserInfo(input *logz.UserInfo) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + var firstName string + if input.FirstName != nil { + firstName = *input.FirstName + } + + var lastName string + if input.LastName != nil { + lastName = *input.LastName + } + + var email string + if input.EmailAddress != nil { + email = *input.EmailAddress + } + + var phoneNumber string + if input.PhoneNumber != nil { + phoneNumber = *input.PhoneNumber + } + + return []interface{}{ + map[string]interface{}{ + "first_name": firstName, + "last_name": lastName, + "email": email, + "phone_number": phoneNumber, + }, + } +} diff --git a/internal/services/logz/logz_monitor_resource.go b/internal/services/logz/logz_monitor_resource.go index 896162b3b3ec..cd95ca588fae 100644 --- a/internal/services/logz/logz_monitor_resource.go +++ b/internal/services/logz/logz_monitor_resource.go @@ -3,7 +3,6 @@ package logz import ( "fmt" "log" - "regexp" "time" "github.com/Azure/azure-sdk-for-go/services/logz/mgmt/2020-10-01/logz" @@ -13,6 +12,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/logz/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/logz/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" @@ -42,13 +42,10 @@ func resourceLogzMonitor() *pluginsdk.Resource { Schema: map[string]*pluginsdk.Schema{ "name": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringMatch( - regexp.MustCompile(`^[\w\-]{1,32}$`), - `The name length must be from 1 to 32 characters. The name can only contain letters, numbers, hyphens and underscore.`, - ), + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.LogzMonitorName, }, "resource_group_name": azure.SchemaResourceGroupName(), @@ -126,43 +123,7 @@ func resourceLogzMonitor() *pluginsdk.Resource { }, }, - "user": { - Type: pluginsdk.TypeList, - Required: true, - ForceNew: true, - MaxItems: 1, - Elem: &pluginsdk.Resource{ - Schema: map[string]*pluginsdk.Schema{ - "email": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - - "first_name": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringLenBetween(1, 50), - }, - - "last_name": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringLenBetween(1, 50), - }, - - "phone_number": { - Type: pluginsdk.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringLenBetween(1, 40), - }, - }, - }, - }, + "user": SchemaUserInfo(), "enabled": { Type: pluginsdk.TypeBool, @@ -204,7 +165,7 @@ func resourceLogzMonitorCreate(d *pluginsdk.ResourceData, meta interface{}) erro Properties: &logz.MonitorProperties{ LogzOrganizationProperties: expandMonitorOrganizationProperties(d), PlanData: expandMonitorPlanData(d.Get("plan").([]interface{})), - UserInfo: expandMonitorUserInfo(d.Get("user").([]interface{})), + UserInfo: expandUserInfo(d.Get("user").([]interface{})), MonitoringStatus: monitoringStatus, }, Tags: tags.Expand(d.Get("tags").(map[string]interface{})), @@ -255,7 +216,9 @@ func resourceLogzMonitorRead(d *pluginsdk.ResourceData, meta interface{}) error return fmt.Errorf("setting `plan`: %+v", err) } - d.Set("user", d.Get("user")) + if err := d.Set("user", flattenUserInfo(expandUserInfo(d.Get("user").([]interface{})))); err != nil { + return fmt.Errorf("setting `user`: %+v", err) + } } return tags.FlattenAndSet(d, resp.Tags) @@ -346,20 +309,6 @@ func expandMonitorPlanData(input []interface{}) *logz.PlanData { } } -func expandMonitorUserInfo(input []interface{}) *logz.UserInfo { - if len(input) == 0 || input[0] == nil { - return nil - } - - v := input[0].(map[string]interface{}) - return &logz.UserInfo{ - FirstName: utils.String(v["first_name"].(string)), - LastName: utils.String(v["last_name"].(string)), - EmailAddress: utils.String(v["email"].(string)), - PhoneNumber: utils.String(v["phone_number"].(string)), - } -} - func flattenMonitorOrganizationProperties(d *pluginsdk.ResourceData, input *logz.OrganizationProperties) { if input == nil { return diff --git a/internal/services/logz/logz_monitor_resource_test.go b/internal/services/logz/logz_monitor_resource_test.go index ee2b3247b42b..6a11b1bcca3e 100644 --- a/internal/services/logz/logz_monitor_resource_test.go +++ b/internal/services/logz/logz_monitor_resource_test.go @@ -3,11 +3,9 @@ package logz_test import ( "context" "fmt" - "strconv" "testing" "time" - "github.com/google/uuid" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -22,7 +20,7 @@ func TestAccLogzMonitor_basic(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_logz_monitor", "test") r := LogzMonitorResource{} effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339) - email := uuid.New().String() + email := "9d186100-1e0f-4b4a-bb10-753d2d52b750@example.com" data.ResourceTest(t, r, []acceptance.TestStep{ { Config: r.basic(data, effectiveDate, email), @@ -38,7 +36,7 @@ func TestAccLogzMonitor_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_logz_monitor", "test") r := LogzMonitorResource{} effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339) - email := uuid.New().String() + email := "88841ffe-6376-487c-950c-1c3318f63dc5@example.com" data.ResourceTest(t, r, []acceptance.TestStep{ { Config: r.basic(data, effectiveDate, email), @@ -57,7 +55,7 @@ func TestAccLogzMonitor_complete(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_logz_monitor", "test") r := LogzMonitorResource{} effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339) - email := uuid.New().String() + email := "37d395aa-4b30-4566-b141-72ea4bf84e11@example.com" data.ResourceTest(t, r, []acceptance.TestStep{ { Config: r.complete(data, effectiveDate, email), @@ -73,7 +71,7 @@ func TestAccLogzMonitor_update(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_logz_monitor", "test") r := LogzMonitorResource{} effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339) - email := uuid.New().String() + email := "d5d750ce-94fd-475d-816f-48110e1ca04a@example.com" data.ResourceTest(t, r, []acceptance.TestStep{ { Config: r.basic(data, effectiveDate, email), @@ -133,7 +131,7 @@ func (r LogzMonitorResource) basic(data acceptance.TestData, effectiveDate strin %s resource "azurerm_logz_monitor" "test" { - name = "%s" + name = "acctest-lm-%d" resource_group_name = azurerm_resource_group.test.name location = azurerm_resource_group.test.location plan { @@ -144,13 +142,13 @@ resource "azurerm_logz_monitor" "test" { } user { - email = "%s@example.com" + email = "%s" first_name = "first" last_name = "last" phone_number = "123456" } } -`, template, getLogzInstanceName(data.RandomInteger), effectiveDate, email) +`, template, data.RandomInteger, effectiveDate, email) } func (r LogzMonitorResource) update(data acceptance.TestData, effectiveDate string, email string) string { @@ -159,7 +157,7 @@ func (r LogzMonitorResource) update(data acceptance.TestData, effectiveDate stri %s resource "azurerm_logz_monitor" "test" { - name = "%s" + name = "acctest-lm-%d" resource_group_name = azurerm_resource_group.test.name location = azurerm_resource_group.test.location plan { @@ -170,14 +168,14 @@ resource "azurerm_logz_monitor" "test" { } user { - email = "%s@example.com" + email = "%s" first_name = "first" last_name = "last" phone_number = "123456" } enabled = false } -`, template, getLogzInstanceName(data.RandomInteger), effectiveDate, email) +`, template, data.RandomInteger, effectiveDate, email) } func (r LogzMonitorResource) requiresImport(data acceptance.TestData, effectiveDate string, email string) string { @@ -197,7 +195,7 @@ resource "azurerm_logz_monitor" "import" { } user { - email = "%s@example.com" + email = "%s" first_name = "first" last_name = "last" phone_number = "123456" @@ -212,7 +210,7 @@ func (r LogzMonitorResource) complete(data acceptance.TestData, effectiveDate st %s resource "azurerm_logz_monitor" "test" { - name = "%s" + name = "acctest-lm-%d" resource_group_name = azurerm_resource_group.test.name location = azurerm_resource_group.test.location @@ -226,19 +224,15 @@ resource "azurerm_logz_monitor" "test" { } user { - email = "%s@example.com" + email = "%s" first_name = "first" last_name = "last" phone_number = "123456" } - enabled = false + enabled = true tags = { ENV = "Test" } } -`, template, getLogzInstanceName(data.RandomInteger), effectiveDate, email) -} - -func getLogzInstanceName(randomInteger int) string { - return "liftr_test_only_" + strconv.Itoa(randomInteger)[2:] +`, template, data.RandomInteger, effectiveDate, email) } diff --git a/internal/services/logz/logz_sub_account_resource.go b/internal/services/logz/logz_sub_account_resource.go new file mode 100644 index 000000000000..8da494e0d7b8 --- /dev/null +++ b/internal/services/logz/logz_sub_account_resource.go @@ -0,0 +1,246 @@ +package logz + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/Azure/azure-sdk-for-go/services/logz/mgmt/2020-10-01/logz" + "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/logz/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/logz/validate" + "github.com/hashicorp/terraform-provider-azurerm/internal/tags" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +func resourceLogzSubAccount() *pluginsdk.Resource { + return &pluginsdk.Resource{ + Create: resourceLogzSubAccountCreate, + Read: resourceLogzSubAccountRead, + Update: resourceLogzSubAccountUpdate, + Delete: resourceLogzSubAccountDelete, + + Timeouts: &pluginsdk.ResourceTimeout{ + Create: pluginsdk.DefaultTimeout(30 * time.Minute), + Read: pluginsdk.DefaultTimeout(5 * time.Minute), + Update: pluginsdk.DefaultTimeout(30 * time.Minute), + Delete: pluginsdk.DefaultTimeout(30 * time.Minute), + }, + + Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { + _, err := parse.LogzSubAccountID(id) + return err + }), + + Schema: map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.LogzMonitorName, + }, + + "logz_monitor_id": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.LogzMonitorID, + }, + + "user": SchemaUserInfo(), + + "enabled": { + Type: pluginsdk.TypeBool, + Optional: true, + Default: true, + }, + + "tags": tags.Schema(), + }, + } +} +func resourceLogzSubAccountCreate(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Logz.SubAccountClient + ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) + defer cancel() + + monitorId, err := parse.LogzMonitorID(d.Get("logz_monitor_id").(string)) + if err != nil { + return err + } + + id := parse.NewLogzSubAccountID(monitorId.SubscriptionId, monitorId.ResourceGroup, monitorId.MonitorName, d.Get("name").(string)) + existing, err := client.Get(ctx, id.ResourceGroup, id.MonitorName, id.AccountName) + if err != nil { + if !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("checking for existing %s: %+v", id, err) + } + } + + if !utils.ResponseWasNotFound(existing.Response) { + return tf.ImportAsExistsError("azurerm_logz_sub_account", id.ID()) + } + + monitoringStatus := logz.MonitoringStatusDisabled + if d.Get("enabled").(bool) { + monitoringStatus = logz.MonitoringStatusEnabled + } + + monitorClient := meta.(*clients.Client).Logz.MonitorClient + resp, err := monitorClient.Get(ctx, monitorId.ResourceGroup, monitorId.MonitorName) + if err != nil { + return fmt.Errorf("checking for existing %s: %+v", monitorId, err) + } + + props := logz.MonitorResource{ + Location: resp.Location, + Properties: &logz.MonitorProperties{ + UserInfo: expandUserInfo(d.Get("user").([]interface{})), + MonitoringStatus: monitoringStatus, + }, + Tags: tags.Expand(d.Get("tags").(map[string]interface{})), + } + + if properties := resp.Properties; properties != nil { + props.Properties.PlanData = properties.PlanData + } + + future, err := client.Create(ctx, id.ResourceGroup, id.MonitorName, id.AccountName, &props) + if err != nil { + return fmt.Errorf("creating %s: %+v", id, err) + } + + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for creation of the %s: %+v", id, err) + } + + d.SetId(id.ID()) + return resourceLogzSubAccountRead(d, meta) +} + +func resourceLogzSubAccountRead(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Logz.SubAccountClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.LogzSubAccountID(d.Id()) + if err != nil { + return err + } + + resp, err := client.Get(ctx, id.ResourceGroup, id.MonitorName, id.AccountName) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[INFO] logz %q does not exist - removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("retrieving %s: %+v", id, err) + } + + d.Set("name", id.AccountName) + d.Set("logz_monitor_id", parse.NewLogzMonitorID(id.SubscriptionId, id.ResourceGroup, id.MonitorName).ID()) + + if props := resp.Properties; props != nil { + d.Set("enabled", props.MonitoringStatus == logz.MonitoringStatusEnabled) + if err := d.Set("user", flattenUserInfo(expandUserInfo(d.Get("user").([]interface{})))); err != nil { + return fmt.Errorf("setting `user`: %+v", err) + } + } + + return tags.FlattenAndSet(d, resp.Tags) +} + +func resourceLogzSubAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Logz.SubAccountClient + ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.LogzSubAccountID(d.Id()) + if err != nil { + return err + } + + props := logz.MonitorResourceUpdateParameters{ + Properties: &logz.MonitorUpdateProperties{}, + } + + if d.HasChange("enabled") { + monitoringStatus := logz.MonitoringStatusDisabled + if d.Get("enabled").(bool) { + monitoringStatus = logz.MonitoringStatusEnabled + } + props.Properties.MonitoringStatus = monitoringStatus + } + + if d.HasChange("tags") { + props.Tags = tags.Expand(d.Get("tags").(map[string]interface{})) + } + + if _, err := client.Update(ctx, id.ResourceGroup, id.MonitorName, id.AccountName, &props); err != nil { + return fmt.Errorf("updating %s: %+v", id, err) + } + + return resourceLogzSubAccountRead(d, meta) +} + +func resourceLogzSubAccountDelete(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Logz.SubAccountClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.LogzSubAccountID(d.Id()) + if err != nil { + return err + } + + future, err := client.Delete(ctx, id.ResourceGroup, id.MonitorName, id.AccountName) + if err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) + } + + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for deletion of the %s: %+v", id, err) + } + + // API has bug, which appears to be eventually consistent. Tracked by this issue: https://github.com/Azure/azure-rest-api-specs/issues/18572 + log.Printf("[DEBUG] Waiting for %s to be fully deleted..", *id) + deadline, ok := ctx.Deadline() + if !ok { + return fmt.Errorf("context had no deadline") + } + + stateConf := &pluginsdk.StateChangeConf{ + Pending: []string{"Exists"}, + Target: []string{"NotFound"}, + Refresh: subAccountDeletedRefreshFunc(ctx, client, *id), + MinTimeout: 10 * time.Second, + ContinuousTargetOccurence: 20, + Timeout: time.Until(deadline), + } + + if _, err = stateConf.WaitForStateContext(ctx); err != nil { + return fmt.Errorf("waiting for %s to be fully deleted: %+v", *id, err) + } + + return nil +} + +func subAccountDeletedRefreshFunc(ctx context.Context, client *logz.SubAccountClient, id parse.LogzSubAccountId) pluginsdk.StateRefreshFunc { + return func() (interface{}, string, error) { + res, err := client.Get(ctx, id.ResourceGroup, id.MonitorName, id.AccountName) + if err != nil { + if utils.ResponseWasNotFound(res.Response) { + return "NotFound", "NotFound", nil + } + + return nil, "", fmt.Errorf("checking if %s has been deleted: %+v", id, err) + } + + return res, "Exists", nil + } +} diff --git a/internal/services/logz/logz_sub_account_resource_test.go b/internal/services/logz/logz_sub_account_resource_test.go new file mode 100644 index 000000000000..3e3d7063d7a0 --- /dev/null +++ b/internal/services/logz/logz_sub_account_resource_test.go @@ -0,0 +1,224 @@ +package logz_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/logz/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +type LogzSubAccountResource struct{} + +func TestAccLogzSubAccount_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_logz_sub_account", "test") + r := LogzSubAccountResource{} + effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339) + email := "0bc0fe71-6e2f-4552-bc48-6ca0c22f4db0@example.com" + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data, effectiveDate, email), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("user"), + }) +} + +func TestAccLogzSubAccount_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_logz_sub_account", "test") + r := LogzSubAccountResource{} + effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339) + email := "429420d4-0abf-4cd8-b149-fe63fa141fc6@example.com" + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data, effectiveDate, email), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + { + Config: r.requiresImport(data, effectiveDate, email), + ExpectError: acceptance.RequiresImportError(data.ResourceType), + }, + }) +} + +func TestAccLogzSubAccount_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_logz_sub_account", "test") + r := LogzSubAccountResource{} + effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339) + email := "253e466c-3a78-4a79-9260-98854eef2b5c@example.com" + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.complete(data, effectiveDate, email), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("user"), + }) +} + +func TestAccLogzSubAccount_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_logz_sub_account", "test") + r := LogzSubAccountResource{} + effectiveDate := time.Now().Add(time.Hour * 7).Format(time.RFC3339) + email := "5c3b9a35-06c5-4c75-928e-6505a10541a5@example.com" + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data, effectiveDate, email), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("user"), + { + Config: r.update(data, effectiveDate, email), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("user"), + { + Config: r.basic(data, effectiveDate, email), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("user"), + }) +} + +func (r LogzSubAccountResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { + id, err := parse.LogzSubAccountID(state.ID) + if err != nil { + return nil, err + } + + resp, err := clients.Logz.SubAccountClient.Get(ctx, id.ResourceGroup, id.MonitorName, id.AccountName) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return utils.Bool(false), nil + } + return nil, fmt.Errorf("retrieving %s: %+v", id, err) + } + + return utils.Bool(true), nil +} + +func (r LogzSubAccountResource) template(data acceptance.TestData, effectiveDate string, email string) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctest-logz-%d" + location = "%s" +} + +resource "azurerm_logz_monitor" "test" { + name = "acctest-lm-%d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + plan { + billing_cycle = "MONTHLY" + effective_date = "%s" + plan_id = "100gb14days" + usage_type = "COMMITTED" + } + + user { + email = "%s" + first_name = "first" + last_name = "last" + phone_number = "123456" + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, effectiveDate, email) +} + +func (r LogzSubAccountResource) basic(data acceptance.TestData, effectiveDate string, email string) string { + template := r.template(data, effectiveDate, email) + return fmt.Sprintf(` +%s + +resource "azurerm_logz_sub_account" "test" { + name = "acctest-lsa-%d" + logz_monitor_id = azurerm_logz_monitor.test.id + user { + email = azurerm_logz_monitor.test.user[0].email + first_name = azurerm_logz_monitor.test.user[0].first_name + last_name = azurerm_logz_monitor.test.user[0].last_name + phone_number = azurerm_logz_monitor.test.user[0].phone_number + } +} +`, template, data.RandomInteger) +} + +func (r LogzSubAccountResource) update(data acceptance.TestData, effectiveDate string, email string) string { + template := r.template(data, effectiveDate, email) + return fmt.Sprintf(` +%s + +resource "azurerm_logz_sub_account" "test" { + name = "acctest-lsa-%d" + logz_monitor_id = azurerm_logz_monitor.test.id + user { + email = azurerm_logz_monitor.test.user[0].email + first_name = azurerm_logz_monitor.test.user[0].first_name + last_name = azurerm_logz_monitor.test.user[0].last_name + phone_number = azurerm_logz_monitor.test.user[0].phone_number + } + enabled = false +} +`, template, data.RandomInteger) +} + +func (r LogzSubAccountResource) requiresImport(data acceptance.TestData, effectiveDate string, email string) string { + config := r.basic(data, effectiveDate, email) + return fmt.Sprintf(` +%s + +resource "azurerm_logz_sub_account" "import" { + name = azurerm_logz_sub_account.test.name + logz_monitor_id = azurerm_logz_sub_account.test.logz_monitor_id + user { + email = azurerm_logz_monitor.test.user[0].email + first_name = azurerm_logz_monitor.test.user[0].first_name + last_name = azurerm_logz_monitor.test.user[0].last_name + phone_number = azurerm_logz_monitor.test.user[0].phone_number + } +} +`, config) +} + +func (r LogzSubAccountResource) complete(data acceptance.TestData, effectiveDate string, email string) string { + template := r.template(data, effectiveDate, email) + return fmt.Sprintf(` +%s + +resource "azurerm_logz_sub_account" "test" { + name = "acctest-lsa-%d" + logz_monitor_id = azurerm_logz_monitor.test.id + user { + email = azurerm_logz_monitor.test.user[0].email + first_name = azurerm_logz_monitor.test.user[0].first_name + last_name = azurerm_logz_monitor.test.user[0].last_name + phone_number = azurerm_logz_monitor.test.user[0].phone_number + } + + tags = { + ENV = "Test" + } +} +`, template, data.RandomInteger) +} diff --git a/internal/services/logz/logz_tag_rule_resource_test.go b/internal/services/logz/logz_tag_rule_resource_test.go index ada509268cc8..a52caf731169 100644 --- a/internal/services/logz/logz_tag_rule_resource_test.go +++ b/internal/services/logz/logz_tag_rule_resource_test.go @@ -6,7 +6,6 @@ import ( "testing" "time" - "github.com/google/uuid" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -20,7 +19,7 @@ type LogzTagRuleResource struct{} func TestAccLogzTagRule_basic(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_logz_tag_rule", "test") r := LogzTagRuleResource{} - email := uuid.New().String() + email := "71212724-7a73-48c3-9399-de59313d4905@example.com" data.ResourceTest(t, r, []acceptance.TestStep{ { Config: r.basic(data, email), @@ -35,7 +34,7 @@ func TestAccLogzTagRule_basic(t *testing.T) { func TestAccLogzTagRule_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_logz_tag_rule", "test") r := LogzTagRuleResource{} - email := uuid.New().String() + email := "b993f18e-9094-4a38-9e80-a0530ebbc6e2@example.com" data.ResourceTest(t, r, []acceptance.TestStep{ { Config: r.basic(data, email), @@ -53,7 +52,7 @@ func TestAccLogzTagRule_requiresImport(t *testing.T) { func TestAccLogzTagRule_complete(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_logz_tag_rule", "test") r := LogzTagRuleResource{} - email := uuid.New().String() + email := "9121e724-355c-4b74-9d73-ff118ce7241e@example.com" data.ResourceTest(t, r, []acceptance.TestStep{ { Config: r.complete(data, email), @@ -68,7 +67,7 @@ func TestAccLogzTagRule_complete(t *testing.T) { func TestAccLogzTagRule_update(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_logz_tag_rule", "test") r := LogzTagRuleResource{} - email := uuid.New().String() + email := "41a35aed-12d8-46f3-a2a7-9f89404d7989@example.com" data.ResourceTest(t, r, []acceptance.TestStep{ { Config: r.basic(data, email), @@ -121,7 +120,7 @@ resource "azurerm_resource_group" "test" { } resource "azurerm_logz_monitor" "test" { - name = "%s" + name = "acctest-lm-%d" resource_group_name = azurerm_resource_group.test.name location = azurerm_resource_group.test.location plan { @@ -132,13 +131,13 @@ resource "azurerm_logz_monitor" "test" { } user { - email = "%s@example.com" + email = "%s" first_name = "first" last_name = "last" phone_number = "123456" } } -`, data.RandomInteger, data.Locations.Primary, getLogzInstanceName(data.RandomInteger), getEffectiveDate(), email) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, getEffectiveDate(), email) } func (r LogzTagRuleResource) basic(data acceptance.TestData, email string) string { diff --git a/internal/services/logz/parse/logz_sub_account.go b/internal/services/logz/parse/logz_sub_account.go new file mode 100644 index 000000000000..e2ad9624ceb1 --- /dev/null +++ b/internal/services/logz/parse/logz_sub_account.go @@ -0,0 +1,75 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +type LogzSubAccountId struct { + SubscriptionId string + ResourceGroup string + MonitorName string + AccountName string +} + +func NewLogzSubAccountID(subscriptionId, resourceGroup, monitorName, accountName string) LogzSubAccountId { + return LogzSubAccountId{ + SubscriptionId: subscriptionId, + ResourceGroup: resourceGroup, + MonitorName: monitorName, + AccountName: accountName, + } +} + +func (id LogzSubAccountId) String() string { + segments := []string{ + fmt.Sprintf("Account Name %q", id.AccountName), + fmt.Sprintf("Monitor Name %q", id.MonitorName), + fmt.Sprintf("Resource Group %q", id.ResourceGroup), + } + segmentsStr := strings.Join(segments, " / ") + return fmt.Sprintf("%s: (%s)", "Logz Sub Account", segmentsStr) +} + +func (id LogzSubAccountId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Logz/monitors/%s/accounts/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.MonitorName, id.AccountName) +} + +// LogzSubAccountID parses a LogzSubAccount ID into an LogzSubAccountId struct +func LogzSubAccountID(input string) (*LogzSubAccountId, error) { + id, err := resourceids.ParseAzureResourceID(input) + if err != nil { + return nil, err + } + + resourceId := LogzSubAccountId{ + SubscriptionId: id.SubscriptionID, + ResourceGroup: id.ResourceGroup, + } + + if resourceId.SubscriptionId == "" { + return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + } + + if resourceId.ResourceGroup == "" { + return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") + } + + if resourceId.MonitorName, err = id.PopSegment("monitors"); err != nil { + return nil, err + } + if resourceId.AccountName, err = id.PopSegment("accounts"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &resourceId, nil +} diff --git a/internal/services/logz/parse/logz_sub_account_test.go b/internal/services/logz/parse/logz_sub_account_test.go new file mode 100644 index 000000000000..1962c3c615e1 --- /dev/null +++ b/internal/services/logz/parse/logz_sub_account_test.go @@ -0,0 +1,128 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "testing" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.Id = LogzSubAccountId{} + +func TestLogzSubAccountIDFormatter(t *testing.T) { + actual := NewLogzSubAccountID("12345678-1234-9876-4563-123456789012", "resourceGroup1", "monitor1", "subAccount1").ID() + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1/accounts/subAccount1" + if actual != expected { + t.Fatalf("Expected %q but got %q", expected, actual) + } +} + +func TestLogzSubAccountID(t *testing.T) { + testData := []struct { + Input string + Error bool + Expected *LogzSubAccountId + }{ + + { + // empty + Input: "", + Error: true, + }, + + { + // missing SubscriptionId + Input: "/", + Error: true, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Error: true, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Error: true, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", + Error: true, + }, + + { + // missing MonitorName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/", + Error: true, + }, + + { + // missing value for MonitorName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/", + Error: true, + }, + + { + // missing AccountName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1/", + Error: true, + }, + + { + // missing value for AccountName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1/accounts/", + Error: true, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1/accounts/subAccount1", + Expected: &LogzSubAccountId{ + SubscriptionId: "12345678-1234-9876-4563-123456789012", + ResourceGroup: "resourceGroup1", + MonitorName: "monitor1", + AccountName: "subAccount1", + }, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESOURCEGROUP1/PROVIDERS/MICROSOFT.LOGZ/MONITORS/MONITOR1/ACCOUNTS/SUBACCOUNT1", + Error: true, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Input) + + actual, err := LogzSubAccountID(v.Input) + if err != nil { + if v.Error { + continue + } + + t.Fatalf("Expect a value but got an error: %s", err) + } + if v.Error { + t.Fatal("Expect an error but didn't get one") + } + + if actual.SubscriptionId != v.Expected.SubscriptionId { + t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) + } + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) + } + if actual.MonitorName != v.Expected.MonitorName { + t.Fatalf("Expected %q but got %q for MonitorName", v.Expected.MonitorName, actual.MonitorName) + } + if actual.AccountName != v.Expected.AccountName { + t.Fatalf("Expected %q but got %q for AccountName", v.Expected.AccountName, actual.AccountName) + } + } +} diff --git a/internal/services/logz/registration.go b/internal/services/logz/registration.go index 3ec26f95d149..f3ee2a115025 100644 --- a/internal/services/logz/registration.go +++ b/internal/services/logz/registration.go @@ -33,7 +33,8 @@ func (r Registration) SupportedDataSources() map[string]*pluginsdk.Resource { // SupportedResources returns the supported Resources supported by this Service func (r Registration) SupportedResources() map[string]*pluginsdk.Resource { return map[string]*pluginsdk.Resource{ - "azurerm_logz_monitor": resourceLogzMonitor(), - "azurerm_logz_tag_rule": resourceLogzTagRule(), + "azurerm_logz_monitor": resourceLogzMonitor(), + "azurerm_logz_tag_rule": resourceLogzTagRule(), + "azurerm_logz_sub_account": resourceLogzSubAccount(), } } diff --git a/internal/services/logz/resourceids.go b/internal/services/logz/resourceids.go index e5304b99af0b..229f947d4f71 100644 --- a/internal/services/logz/resourceids.go +++ b/internal/services/logz/resourceids.go @@ -2,3 +2,4 @@ package logz //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=LogzMonitor -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1 //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=LogzTagRule -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1/tagRules/ruleSet1 +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=LogzSubAccount -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1/accounts/subAccount1 diff --git a/internal/services/logz/validate/logz_monitor_name.go b/internal/services/logz/validate/logz_monitor_name.go new file mode 100644 index 000000000000..d43a00ad29f9 --- /dev/null +++ b/internal/services/logz/validate/logz_monitor_name.go @@ -0,0 +1,14 @@ +package validate + +import ( + "regexp" + + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" +) + +func LogzMonitorName(v interface{}, k string) (warnings []string, errors []error) { + return validation.StringMatch( + regexp.MustCompile(`^[\w\-]{1,32}$`), + `name must be between 1 and 32 characters in length and may contain only letters, numbers, hyphens and underscores`, + )(v, k) +} diff --git a/internal/services/logz/validate/logz_sub_account_id.go b/internal/services/logz/validate/logz_sub_account_id.go new file mode 100644 index 000000000000..fa962d5037f7 --- /dev/null +++ b/internal/services/logz/validate/logz_sub_account_id.go @@ -0,0 +1,23 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + + "github.com/hashicorp/terraform-provider-azurerm/internal/services/logz/parse" +) + +func LogzSubAccountID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := parse.LogzSubAccountID(v); err != nil { + errors = append(errors, err) + } + + return +} diff --git a/internal/services/logz/validate/logz_sub_account_id_test.go b/internal/services/logz/validate/logz_sub_account_id_test.go new file mode 100644 index 000000000000..049390a588e0 --- /dev/null +++ b/internal/services/logz/validate/logz_sub_account_id_test.go @@ -0,0 +1,88 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import "testing" + +func TestLogzSubAccountID(t *testing.T) { + cases := []struct { + Input string + Valid bool + }{ + + { + // empty + Input: "", + Valid: false, + }, + + { + // missing SubscriptionId + Input: "/", + Valid: false, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Valid: false, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Valid: false, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", + Valid: false, + }, + + { + // missing MonitorName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/", + Valid: false, + }, + + { + // missing value for MonitorName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/", + Valid: false, + }, + + { + // missing AccountName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1/", + Valid: false, + }, + + { + // missing value for AccountName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1/accounts/", + Valid: false, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.Logz/monitors/monitor1/accounts/subAccount1", + Valid: true, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESOURCEGROUP1/PROVIDERS/MICROSOFT.LOGZ/MONITORS/MONITOR1/ACCOUNTS/SUBACCOUNT1", + Valid: false, + }, + } + for _, tc := range cases { + t.Logf("[DEBUG] Testing Value %s", tc.Input) + _, errors := LogzSubAccountID(tc.Input, "test") + valid := len(errors) == 0 + + if tc.Valid != valid { + t.Fatalf("Expected %t but got %t", tc.Valid, valid) + } + } +} diff --git a/internal/services/maintenance/client/client.go b/internal/services/maintenance/client/client.go index ae4c89f5b2dd..5b0d8697c90c 100644 --- a/internal/services/maintenance/client/client.go +++ b/internal/services/maintenance/client/client.go @@ -8,6 +8,7 @@ import ( type Client struct { ConfigurationsClient *maintenance.ConfigurationsClient ConfigurationAssignmentsClient *maintenance.ConfigurationAssignmentsClient + PublicConfigurationsClient *maintenance.PublicMaintenanceConfigurationsClient } func NewClient(o *common.ClientOptions) *Client { @@ -17,8 +18,12 @@ func NewClient(o *common.ClientOptions) *Client { configurationAssignmentsClient := maintenance.NewConfigurationAssignmentsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&configurationAssignmentsClient.Client, o.ResourceManagerAuthorizer) + publicConfigurationsClient := maintenance.NewPublicMaintenanceConfigurationsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&publicConfigurationsClient.Client, o.ResourceManagerAuthorizer) + return &Client{ ConfigurationsClient: &configurationsClient, ConfigurationAssignmentsClient: &configurationAssignmentsClient, + PublicConfigurationsClient: &publicConfigurationsClient, } } diff --git a/internal/services/maintenance/public_maintenance_configurations_data_source.go b/internal/services/maintenance/public_maintenance_configurations_data_source.go new file mode 100644 index 000000000000..9b4f02fd4a88 --- /dev/null +++ b/internal/services/maintenance/public_maintenance_configurations_data_source.go @@ -0,0 +1,222 @@ +package maintenance + +import ( + "fmt" + "time" + + "github.com/Azure/azure-sdk-for-go/services/maintenance/mgmt/2021-05-01/maintenance" + "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" + "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" + "github.com/hashicorp/terraform-provider-azurerm/utils" +) + +const recurMondayToThursday = "Monday-Thursday" +const recurFridayToSunday = "Friday-Sunday" + +func dataSourcePublicMaintenanceConfigurations() *pluginsdk.Resource { + return &pluginsdk.Resource{ + Read: dataSourcePublicMaintenanceConfigurationsRead, + + Timeouts: &pluginsdk.ResourceTimeout{ + Read: pluginsdk.DefaultTimeout(5 * time.Minute), + }, + + Schema: map[string]*pluginsdk.Schema{ + + "location": { + Type: pluginsdk.TypeString, + Optional: true, + StateFunc: azure.NormalizeLocation, + }, + + "scope": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + "All", // All is still accepted by the API + string(maintenance.ScopeExtension), + string(maintenance.ScopeHost), + string(maintenance.ScopeInGuestPatch), + string(maintenance.ScopeOSImage), + string(maintenance.ScopeSQLDB), + string(maintenance.ScopeSQLManagedInstance), + }, false), + }, + + "recur_every": { + Type: pluginsdk.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + recurMondayToThursday, + recurFridayToSunday, + }, false), + }, + + "configs": { + Type: pluginsdk.TypeList, + Computed: true, + Elem: &pluginsdk.Resource{ + Schema: map[string]*pluginsdk.Schema{ + "name": { + Type: pluginsdk.TypeString, + Computed: true, + }, + + "id": { + Type: pluginsdk.TypeString, + Computed: true, + }, + + "location": { + Type: pluginsdk.TypeString, + Computed: true, + }, + + "description": { + Type: pluginsdk.TypeString, + Computed: true, + }, + + "duration": { + Type: pluginsdk.TypeString, + Computed: true, + }, + + "maintenance_scope": { + Type: pluginsdk.TypeString, + Computed: true, + }, + + "time_zone": { + Type: pluginsdk.TypeString, + Computed: true, + }, + + "recur_every": { + Type: pluginsdk.TypeString, + Computed: true, + }, + }, + }, + }, + }, + } +} + +func dataSourcePublicMaintenanceConfigurationsRead(d *pluginsdk.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Maintenance.PublicConfigurationsClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + resp, err := client.List(ctx) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("no Public Maintenance Configurations were found") + } + return fmt.Errorf("retrieving Public Maintenance Configurations: %+v", err) + } + + filteredPublicConfigs := make([]interface{}, 0) + + recurEveryFilter := d.Get("recur_every").(string) + if recurEveryFilter == recurFridayToSunday { + recurEveryFilter = "week Friday, Saturday, Sunday" + } else if recurEveryFilter == recurMondayToThursday { + recurEveryFilter = "week Monday, Tuesday, Wednesday, Thursday" + } + + locationFilter := azure.NormalizeLocation(d.Get("location").(string)) + scopeFilter := d.Get("scope").(string) + + if resp.Value != nil { + for _, maintenanceConfig := range *resp.Value { + + var configLocation, configRecurEvery, configScope string + if maintenanceConfig.Location != nil { + configLocation = azure.NormalizeLocation(*maintenanceConfig.Location) + } + if props := maintenanceConfig.ConfigurationProperties; props != nil { + if props.Window != nil && props.Window.RecurEvery != nil { + configRecurEvery = *props.Window.RecurEvery + } + if string(props.MaintenanceScope) != "" { + configScope = string(props.MaintenanceScope) + } + } + + if locationFilter != "" && locationFilter != configLocation { + continue + } + if recurEveryFilter != "" && recurEveryFilter != configRecurEvery { + continue + } + if scopeFilter != "" && scopeFilter != configScope { + continue + } + + filteredPublicConfigs = append(filteredPublicConfigs, flattenPublicMaintenanceConfiguration(maintenanceConfig)) + } + } + + if len(filteredPublicConfigs) == 0 { + return fmt.Errorf("no Public Maintenance Configurations were found") + } + + if err := d.Set("configs", filteredPublicConfigs); err != nil { + return fmt.Errorf("setting `configs`: %+v", err) + } + + d.SetId(time.Now().UTC().String()) + return nil +} + +func flattenPublicMaintenanceConfiguration(config maintenance.Configuration) map[string]interface{} { + output := make(map[string]interface{}) + + output["name"] = "" + if config.Name != nil { + output["name"] = *config.Name + } + + output["id"] = "" + if config.ID != nil { + output["id"] = *config.ID + } + + output["location"] = "" + if config.Location != nil { + output["location"] = azure.NormalizeLocation(*config.Location) + } + + output["maintenance_scope"] = string(config.MaintenanceScope) + + var description, recurEvery, timeZone, duration string + if props := config.ConfigurationProperties; props != nil { + if props.ExtensionProperties != nil { + if configDescription, ok := props.ExtensionProperties["description"]; ok { + description = *configDescription + } + } + if props.Window != nil { + if props.Window.RecurEvery != nil { + recurEvery = *props.Window.RecurEvery + } + if props.Window.TimeZone != nil { + timeZone = *props.Window.TimeZone + } + if props.Window.Duration != nil { + duration = *props.Window.Duration + } + } + } + + output["description"] = description + output["recur_every"] = recurEvery + output["time_zone"] = timeZone + output["duration"] = duration + + return output +} diff --git a/internal/services/maintenance/public_maintenance_configurations_data_source_test.go b/internal/services/maintenance/public_maintenance_configurations_data_source_test.go new file mode 100644 index 000000000000..c8c775cf48eb --- /dev/null +++ b/internal/services/maintenance/public_maintenance_configurations_data_source_test.go @@ -0,0 +1,84 @@ +package maintenance_test + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" + "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" +) + +type PublicMaintenanceConfigurationsDataSource struct{} + +func TestAccDataSourcePublicMaintenanceConfigurations_noFilters(t *testing.T) { + data := acceptance.BuildTestData(t, "data.azurerm_public_maintenance_configurations", "test") + r := PublicMaintenanceConfigurationsDataSource{} + + data.DataSourceTest(t, []acceptance.TestStep{ + { + Config: r.noFilters(), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).Key("configs.30.name").Exists(), + ), + }, + }) +} + +func TestAccDataSourcePublicMaintenanceConfigurations_allFilters(t *testing.T) { + data := acceptance.BuildTestData(t, "data.azurerm_public_maintenance_configurations", "test") + r := PublicMaintenanceConfigurationsDataSource{} + + data.DataSourceTest(t, []acceptance.TestStep{ + { + Config: r.allFilters(), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).Key("configs.#").HasValue("1"), + check.That(data.ResourceName).Key("configs.0.maintenance_scope").HasValue("SQLManagedInstance"), + check.That(data.ResourceName).Key("configs.0.name").HasValue("SQL_WestEurope_MI_1"), + check.That(data.ResourceName).Key("configs.0.recur_every").HasValue("week Monday, Tuesday, Wednesday, Thursday"), + ), + }, + }) +} + +func TestAccDataSourcePublicMaintenanceConfigurations_recurEvery(t *testing.T) { + data := acceptance.BuildTestData(t, "data.azurerm_public_maintenance_configurations", "test") + r := PublicMaintenanceConfigurationsDataSource{} + + data.DataSourceTest(t, []acceptance.TestStep{ + { + Config: r.recurEvery(), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).Key("configs.0.maintenance_scope").HasValue("SQLManagedInstance"), + check.That(data.ResourceName).Key("configs.0.recur_every").HasValue("week Friday, Saturday, Sunday"), + ), + }, + }) +} + +func (PublicMaintenanceConfigurationsDataSource) allFilters() string { + return fmt.Sprintf(` +data "azurerm_public_maintenance_configurations" "test" { + location = "West Europe" + scope = "SQLManagedInstance" + recur_every = "Monday-Thursday" +} +`) +} + +func (PublicMaintenanceConfigurationsDataSource) noFilters() string { + return fmt.Sprintf(` +data "azurerm_public_maintenance_configurations" "test" { + +} +`) +} + +func (PublicMaintenanceConfigurationsDataSource) recurEvery() string { + return fmt.Sprintf(` +data "azurerm_public_maintenance_configurations" "test" { + scope = "SQLManagedInstance" + recur_every = "Friday-Sunday" +} +`) +} diff --git a/internal/services/maintenance/registration.go b/internal/services/maintenance/registration.go index f73b3cf04a82..0bf99ffb28aa 100644 --- a/internal/services/maintenance/registration.go +++ b/internal/services/maintenance/registration.go @@ -25,7 +25,8 @@ func (r Registration) WebsiteCategories() []string { func (r Registration) SupportedDataSources() map[string]*pluginsdk.Resource { return map[string]*pluginsdk.Resource{ - "azurerm_maintenance_configuration": dataSourceMaintenanceConfiguration(), + "azurerm_maintenance_configuration": dataSourceMaintenanceConfiguration(), + "azurerm_public_maintenance_configurations": dataSourcePublicMaintenanceConfigurations(), } } diff --git a/internal/services/monitor/monitor_aad_diagnostic_setting_resource.go b/internal/services/monitor/monitor_aad_diagnostic_setting_resource.go index 81c15868a41b..dc67c21b7e47 100644 --- a/internal/services/monitor/monitor_aad_diagnostic_setting_resource.go +++ b/internal/services/monitor/monitor_aad_diagnostic_setting_resource.go @@ -9,9 +9,9 @@ import ( "github.com/Azure/azure-sdk-for-go/services/aad/mgmt/2017-04-01/aad" "github.com/hashicorp/go-azure-helpers/lang/response" + authRuleParse "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - authRuleParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationrulesnamespaces" logAnalyticsParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/parse" logAnalyticsValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/monitor/parse" diff --git a/internal/services/monitor/monitor_action_group_data_source.go b/internal/services/monitor/monitor_action_group_data_source.go index 778ce139b713..2534e632daf7 100644 --- a/internal/services/monitor/monitor_action_group_data_source.go +++ b/internal/services/monitor/monitor_action_group_data_source.go @@ -5,8 +5,8 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - eventHubValidation "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/monitor/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" @@ -316,7 +316,7 @@ func dataSourceMonitorActionGroup() *pluginsdk.Resource { "event_hub_id": { Type: pluginsdk.TypeString, Required: true, - ValidateFunc: eventHubValidation.EventhubID, + ValidateFunc: eventhubs.ValidateEventhubID, }, "tenant_id": { Type: pluginsdk.TypeString, diff --git a/internal/services/monitor/monitor_action_group_resource.go b/internal/services/monitor/monitor_action_group_resource.go index 4b5585372c04..befb477b696d 100644 --- a/internal/services/monitor/monitor_action_group_resource.go +++ b/internal/services/monitor/monitor_action_group_resource.go @@ -7,11 +7,10 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2021-09-01-preview/insights" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - eventHubParser "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/parse" - eventHubValidation "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/monitor/migration" "github.com/hashicorp/terraform-provider-azurerm/internal/services/monitor/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/monitor/validate" @@ -386,7 +385,7 @@ func resourceMonitorActionGroup() *pluginsdk.Resource { "event_hub_id": { Type: pluginsdk.TypeString, Required: true, - ValidateFunc: eventHubValidation.EventhubID, + ValidateFunc: eventhubs.ValidateEventhubID, }, "tenant_id": { Type: pluginsdk.TypeString, @@ -735,7 +734,7 @@ func expandMonitorActionGroupEventHubReceiver(tenantId string, v []interface{}) for _, receiverValue := range v { val := receiverValue.(map[string]interface{}) - eventHubId, err := eventHubParser.EventhubID(*utils.String(val["event_hub_id"].(string))) + eventHubId, err := eventhubs.ParseEventhubID(*utils.String(val["event_hub_id"].(string))) if err != nil { return nil, err } @@ -743,7 +742,7 @@ func expandMonitorActionGroupEventHubReceiver(tenantId string, v []interface{}) receiver := insights.EventHubReceiver{ Name: utils.String(val["name"].(string)), EventHubNameSpace: &eventHubId.NamespaceName, - EventHubName: &eventHubId.Name, + EventHubName: &eventHubId.EventHubName, UseCommonAlertSchema: utils.Bool(val["use_common_alert_schema"].(bool)), } if v := val["tenant_id"].(string); v != "" { @@ -1027,7 +1026,7 @@ func flattenMonitorActionGroupEventHubReceiver(resourceGroup string, receivers * event_hub_name := *receiver.EventHubName subscription_id := *receiver.SubscriptionID - val["event_hub_id"] = eventHubParser.NewEventhubID(subscription_id, resourceGroup, event_hub_namespace, event_hub_name).ID() + val["event_hub_id"] = eventhubs.NewEventhubID(subscription_id, resourceGroup, event_hub_namespace, event_hub_name).ID() } if receiver.UseCommonAlertSchema != nil { val["use_common_alert_schema"] = *receiver.UseCommonAlertSchema diff --git a/internal/services/monitor/monitor_diagnostic_setting_resource.go b/internal/services/monitor/monitor_diagnostic_setting_resource.go index b0ce65f979c0..d13c4f2290ea 100644 --- a/internal/services/monitor/monitor_diagnostic_setting_resource.go +++ b/internal/services/monitor/monitor_diagnostic_setting_resource.go @@ -9,10 +9,10 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2021-07-01-preview/insights" "github.com/hashicorp/go-azure-helpers/lang/response" + authRuleParse "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - authRuleParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/sdk/2017-04-01/authorizationrulesnamespaces" eventhubValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/eventhub/validate" logAnalyticsParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/parse" logAnalyticsValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/loganalytics/validate" diff --git a/internal/services/monitor/monitor_metric_alert_resource.go b/internal/services/monitor/monitor_metric_alert_resource.go index 17f8ae201cfe..d1f9d286b9ed 100644 --- a/internal/services/monitor/monitor_metric_alert_resource.go +++ b/internal/services/monitor/monitor_metric_alert_resource.go @@ -951,6 +951,9 @@ func resourceMonitorMetricAlertActionHash(input interface{}) int { var buf bytes.Buffer if v, ok := input.(map[string]interface{}); ok { buf.WriteString(fmt.Sprintf("%s-", v["action_group_id"].(string))) + if m, ok := v["webhook_properties"].(map[string]interface{}); ok && m != nil { + buf.WriteString(fmt.Sprintf("%v-", m)) + } } return pluginsdk.HashString(buf.String()) } diff --git a/internal/services/mssql/mssql_failover_group_resource.go b/internal/services/mssql/mssql_failover_group_resource.go index bd6fbefd6c3e..c62e1a4120a8 100644 --- a/internal/services/mssql/mssql_failover_group_resource.go +++ b/internal/services/mssql/mssql_failover_group_resource.go @@ -5,10 +5,9 @@ import ( "fmt" "time" + "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v5.0/sql" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - - "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v5.0/sql" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" "github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/parse" diff --git a/internal/services/mssql/mssql_managed_instance_failover_group_resource.go b/internal/services/mssql/mssql_managed_instance_failover_group_resource.go index 7b9e7f397115..3bd074a31517 100644 --- a/internal/services/mssql/mssql_managed_instance_failover_group_resource.go +++ b/internal/services/mssql/mssql_managed_instance_failover_group_resource.go @@ -232,6 +232,7 @@ func (r MsSqlManagedInstanceFailoverGroupResource) Update() sdk.ResourceFunc { Timeout: 30 * time.Minute, Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { client := metadata.Client.MSSQL.InstanceFailoverGroupsClient + instancesClient := metadata.Client.MSSQL.ManagedInstancesClient id, err := parse.InstanceFailoverGroupID(metadata.ResourceData.Id()) if err != nil { @@ -244,6 +245,21 @@ func (r MsSqlManagedInstanceFailoverGroupResource) Update() sdk.ResourceFunc { return err } + managedInstanceId, err := parse.ManagedInstanceID(state.ManagedInstanceId) + if err != nil { + return fmt.Errorf("parsing `managed_instance_id`: %v", err) + } + + partnerId, err := parse.ManagedInstanceID(state.PartnerManagedInstanceId) + if err != nil { + return err + } + + partner, err := instancesClient.Get(ctx, partnerId.ResourceGroup, partnerId.Name, "") + if err != nil || partner.Location == nil || *partner.Location == "" { + return fmt.Errorf("checking for existence and region of Partner of %q: %+v", id, err) + } + readOnlyFailoverPolicy := sql.ReadOnlyEndpointFailoverPolicyDisabled if state.ReadOnlyEndpointFailoverPolicyEnabled { readOnlyFailoverPolicy = sql.ReadOnlyEndpointFailoverPolicyEnabled @@ -255,6 +271,17 @@ func (r MsSqlManagedInstanceFailoverGroupResource) Update() sdk.ResourceFunc { FailoverPolicy: readOnlyFailoverPolicy, }, ReadWriteEndpoint: &sql.InstanceFailoverGroupReadWriteEndpoint{}, + PartnerRegions: &[]sql.PartnerRegionInfo{ + { + Location: partner.Location, + }, + }, + ManagedInstancePairs: &[]sql.ManagedInstancePairInfo{ + { + PrimaryManagedInstanceID: utils.String(managedInstanceId.ID()), + PartnerManagedInstanceID: utils.String(partnerId.ID()), + }, + }, }, } diff --git a/internal/services/mssql/mssql_managed_instance_failover_group_resource_test.go b/internal/services/mssql/mssql_managed_instance_failover_group_resource_test.go index 947cc322e069..a6327c51ac66 100644 --- a/internal/services/mssql/mssql_managed_instance_failover_group_resource_test.go +++ b/internal/services/mssql/mssql_managed_instance_failover_group_resource_test.go @@ -72,7 +72,6 @@ func (r MsSqlManagedInstanceFailoverGroupResource) basic(data acceptance.TestDat resource "azurerm_mssql_managed_instance_failover_group" "test" { name = "acctest-fog-%[2]d" - resource_group_name = azurerm_resource_group.test.name location = "%[3]s" managed_instance_id = azurerm_mssql_managed_instance.test.id partner_managed_instance_id = azurerm_mssql_managed_instance.secondary.id @@ -95,7 +94,6 @@ func (r MsSqlManagedInstanceFailoverGroupResource) update(data acceptance.TestDa resource "azurerm_mssql_managed_instance_failover_group" "test" { name = "acctest-fog-%[2]d" - resource_group_name = azurerm_resource_group.test.name location = "%[3]s" managed_instance_id = azurerm_mssql_managed_instance.test.id partner_managed_instance_id = azurerm_mssql_managed_instance.secondary.id diff --git a/internal/services/mssql/mssql_managed_instance_resource.go b/internal/services/mssql/mssql_managed_instance_resource.go index c58934d5d111..5f8f1d96c0d2 100644 --- a/internal/services/mssql/mssql_managed_instance_resource.go +++ b/internal/services/mssql/mssql_managed_instance_resource.go @@ -438,6 +438,8 @@ func (r MsSqlManagedInstanceResource) Read() sdk.ResourceFunc { // This value is not returned, so we'll just set whatever is in the state/config AdministratorLoginPassword: state.AdministratorLoginPassword, + // This value is not returned, so we'll just set whatever is in the state/config + DnsZonePartnerId: state.DnsZonePartnerId, } if sku := existing.Sku; sku != nil && sku.Name != nil { diff --git a/internal/services/mssql/mssql_server_dns_alias_resource_test.go b/internal/services/mssql/mssql_server_dns_alias_resource_test.go index d978a517978d..79d501b484d7 100644 --- a/internal/services/mssql/mssql_server_dns_alias_resource_test.go +++ b/internal/services/mssql/mssql_server_dns_alias_resource_test.go @@ -5,11 +5,10 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/mssql/mssql_server_resource.go b/internal/services/mssql/mssql_server_resource.go index 67607791cb66..088b50a53e9e 100644 --- a/internal/services/mssql/mssql_server_resource.go +++ b/internal/services/mssql/mssql_server_resource.go @@ -137,7 +137,7 @@ func resourceMsSqlServer() *pluginsdk.Resource { Computed: true, ValidateFunc: commonids.ValidateUserAssignedIdentityID, RequiredWith: []string{ - "identity.0.identity_ids", + "identity", }, }, diff --git a/internal/services/netapp/client/client.go b/internal/services/netapp/client/client.go index 16c7c10fbee2..8ff393abbfa9 100644 --- a/internal/services/netapp/client/client.go +++ b/internal/services/netapp/client/client.go @@ -1,39 +1,49 @@ package client import ( - "github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication" "github.com/hashicorp/terraform-provider-azurerm/internal/common" ) type Client struct { - AccountClient *netapp.AccountsClient - PoolClient *netapp.PoolsClient - VolumeClient *netapp.VolumesClient - SnapshotClient *netapp.SnapshotsClient - SnapshotPoliciesClient *netapp.SnapshotPoliciesClient + AccountClient *netappaccounts.NetAppAccountsClient + PoolClient *capacitypools.CapacityPoolsClient + VolumeClient *volumes.VolumesClient + VolumeReplicationClient *volumesreplication.VolumesReplicationClient + SnapshotClient *snapshots.SnapshotsClient + SnapshotPoliciesClient *snapshotpolicy.SnapshotPolicyClient } func NewClient(o *common.ClientOptions) *Client { - accountClient := netapp.NewAccountsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + accountClient := netappaccounts.NewNetAppAccountsClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&accountClient.Client, o.ResourceManagerAuthorizer) - poolClient := netapp.NewPoolsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + poolClient := capacitypools.NewCapacityPoolsClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&poolClient.Client, o.ResourceManagerAuthorizer) - volumeClient := netapp.NewVolumesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + volumeClient := volumes.NewVolumesClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&volumeClient.Client, o.ResourceManagerAuthorizer) - snapshotClient := netapp.NewSnapshotsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + volumeReplicationClient := volumesreplication.NewVolumesReplicationClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&volumeReplicationClient.Client, o.ResourceManagerAuthorizer) + + snapshotClient := snapshots.NewSnapshotsClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&snapshotClient.Client, o.ResourceManagerAuthorizer) - snapshotPoliciesClient := netapp.NewSnapshotPoliciesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + snapshotPoliciesClient := snapshotpolicy.NewSnapshotPolicyClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&snapshotPoliciesClient.Client, o.ResourceManagerAuthorizer) return &Client{ - AccountClient: &accountClient, - PoolClient: &poolClient, - VolumeClient: &volumeClient, - SnapshotClient: &snapshotClient, - SnapshotPoliciesClient: &snapshotPoliciesClient, + AccountClient: &accountClient, + PoolClient: &poolClient, + VolumeClient: &volumeClient, + VolumeReplicationClient: &volumeReplicationClient, + SnapshotClient: &snapshotClient, + SnapshotPoliciesClient: &snapshotPoliciesClient, } } diff --git a/internal/services/netapp/netapp_account_data_source.go b/internal/services/netapp/netapp_account_data_source.go index 7b4012061bf9..27699a8203b1 100644 --- a/internal/services/netapp/netapp_account_data_source.go +++ b/internal/services/netapp/netapp_account_data_source.go @@ -4,14 +4,14 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceNetAppAccount() *pluginsdk.Resource { @@ -44,10 +44,10 @@ func dataSourceNetAppAccountRead(d *pluginsdk.ResourceData, meta interface{}) er ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewAccountID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName) + id := netappaccounts.NewNetAppAccountID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + resp, err := client.AccountsGet(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } @@ -55,10 +55,13 @@ func dataSourceNetAppAccountRead(d *pluginsdk.ResourceData, meta interface{}) er } d.SetId(id.ID()) - d.Set("name", id.NetAppAccountName) - d.Set("resource_group_name", id.ResourceGroup) + d.Set("name", id.AccountName) + d.Set("resource_group_name", id.ResourceGroupName) - d.Set("location", location.NormalizeNilable(resp.Location)) + if model := resp.Model; model != nil { + d.Set("location", location.NormalizeNilable(&model.Location)) + + } return nil } diff --git a/internal/services/netapp/netapp_account_resource.go b/internal/services/netapp/netapp_account_resource.go index 4dc362e895b8..ab1ab8e2cc92 100644 --- a/internal/services/netapp/netapp_account_resource.go +++ b/internal/services/netapp/netapp_account_resource.go @@ -9,14 +9,15 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" netAppValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -37,7 +38,7 @@ func resourceNetAppAccount() *pluginsdk.Resource { Delete: pluginsdk.DefaultTimeout(30 * time.Minute), }, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.AccountID(id) + _, err := netappaccounts.ParseNetAppAccountID(id) return err }), @@ -102,7 +103,7 @@ func resourceNetAppAccount() *pluginsdk.Resource { }, }, - "tags": tags.Schema(), + "tags": commonschema.Tags(), }, } } @@ -113,37 +114,30 @@ func resourceNetAppAccountCreate(d *pluginsdk.ResourceData, meta interface{}) er ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewAccountID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := netappaccounts.NewNetAppAccountID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName) + existing, err := client.AccountsGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_netapp_account", id.ID()) } } - location := azure.NormalizeLocation(d.Get("location").(string)) - activeDirectories := d.Get("active_directory").([]interface{}) - - accountParameters := netapp.Account{ - Location: utils.String(location), - AccountProperties: &netapp.AccountProperties{ - ActiveDirectories: expandNetAppActiveDirectories(activeDirectories), + accountParameters := netappaccounts.NetAppAccount{ + Location: azure.NormalizeLocation(d.Get("location").(string)), + Properties: &netappaccounts.AccountProperties{ + ActiveDirectories: expandNetAppActiveDirectories(d.Get("active_directory").([]interface{})), }, Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } - future, err := client.CreateOrUpdate(ctx, accountParameters, id.ResourceGroup, id.NetAppAccountName) - if err != nil { + if err := client.AccountsCreateOrUpdateThenPoll(ctx, id, accountParameters); err != nil { return fmt.Errorf("creating %s: %+v", id, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the creation of %s: %+v", id, err) - } // Wait for account to complete create if err := waitForAccountCreateOrUpdate(ctx, client, id); err != nil { @@ -159,21 +153,21 @@ func resourceNetAppAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) er ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AccountID(d.Id()) + id, err := netappaccounts.ParseNetAppAccountID(d.Id()) if err != nil { return err } shouldUpdate := false - update := netapp.AccountPatch{ - AccountProperties: &netapp.AccountProperties{}, + update := netappaccounts.NetAppAccountPatch{ + Properties: &netappaccounts.AccountProperties{}, } if d.HasChange("active_directory") { shouldUpdate = true activeDirectoriesRaw := d.Get("active_directory").([]interface{}) activeDirectories := expandNetAppActiveDirectories(activeDirectoriesRaw) - update.AccountProperties.ActiveDirectories = activeDirectories + update.Properties.ActiveDirectories = activeDirectories } if d.HasChange("tags") { @@ -183,16 +177,12 @@ func resourceNetAppAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) er } if shouldUpdate { - future, err := client.Update(ctx, update, id.ResourceGroup, id.NetAppAccountName) - if err != nil { - return fmt.Errorf("updating Account %q: %+v", id.NetAppAccountName, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the update of %s: %+v", id, err) + if err = client.AccountsUpdateThenPoll(ctx, *id, update); err != nil { + return fmt.Errorf("updating %s: %+v", id.ID(), err) } // Wait for account to complete update - if err := waitForAccountCreateOrUpdate(ctx, client, *id); err != nil { + if err = waitForAccountCreateOrUpdate(ctx, client, *id); err != nil { return err } } @@ -205,14 +195,14 @@ func resourceNetAppAccountRead(d *pluginsdk.ResourceData, meta interface{}) erro ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AccountID(d.Id()) + id, err := netappaccounts.ParseNetAppAccountID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName) + resp, err := client.AccountsGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[INFO] %s does not exist - removing from state", *id) d.SetId("") return nil @@ -220,14 +210,16 @@ func resourceNetAppAccountRead(d *pluginsdk.ResourceData, meta interface{}) erro return fmt.Errorf("retrieving %s: %+v", *id, err) } - d.Set("name", id.NetAppAccountName) - d.Set("resource_group_name", id.ResourceGroup) + d.Set("name", id.AccountName) + d.Set("resource_group_name", id.ResourceGroupName) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) + if model := resp.Model; model != nil { + d.Set("location", azure.NormalizeLocation(model.Location)) + + return tags.FlattenAndSet(d, model.Tags) } - return tags.FlattenAndSet(d, resp.Tags) + return nil } func resourceNetAppAccountDelete(d *pluginsdk.ResourceData, meta interface{}) error { @@ -235,30 +227,26 @@ func resourceNetAppAccountDelete(d *pluginsdk.ResourceData, meta interface{}) er ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.AccountID(d.Id()) + id, err := netappaccounts.ParseNetAppAccountID(d.Id()) if err != nil { return err } - future, err := client.Delete(ctx, id.ResourceGroup, id.NetAppAccountName) - if err != nil { + if err := client.AccountsDeleteThenPoll(ctx, *id); err != nil { return fmt.Errorf("deleting %s: %+v", *id, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for deletion of %s: %+v", *id, err) - } return nil } -func expandNetAppActiveDirectories(input []interface{}) *[]netapp.ActiveDirectory { - results := make([]netapp.ActiveDirectory, 0) +func expandNetAppActiveDirectories(input []interface{}) *[]netappaccounts.ActiveDirectory { + results := make([]netappaccounts.ActiveDirectory, 0) for _, item := range input { v := item.(map[string]interface{}) dns := strings.Join(*utils.ExpandStringSlice(v["dns_servers"].([]interface{})), ",") - result := netapp.ActiveDirectory{ - DNS: utils.String(dns), + result := netappaccounts.ActiveDirectory{ + Dns: utils.String(dns), Domain: utils.String(v["domain"].(string)), OrganizationalUnit: utils.String(v["organizational_unit"].(string)), Password: utils.String(v["password"].(string)), @@ -271,7 +259,7 @@ func expandNetAppActiveDirectories(input []interface{}) *[]netapp.ActiveDirector return &results } -func waitForAccountCreateOrUpdate(ctx context.Context, client *netapp.AccountsClient, id parse.AccountId) error { +func waitForAccountCreateOrUpdate(ctx context.Context, client *netappaccounts.NetAppAccountsClient, id netappaccounts.NetAppAccountId) error { deadline, ok := ctx.Deadline() if !ok { return fmt.Errorf("context had no deadline") @@ -293,15 +281,15 @@ func waitForAccountCreateOrUpdate(ctx context.Context, client *netapp.AccountsCl return nil } -func netappAccountStateRefreshFunc(ctx context.Context, client *netapp.AccountsClient, id parse.AccountId) pluginsdk.StateRefreshFunc { +func netappAccountStateRefreshFunc(ctx context.Context, client *netappaccounts.NetAppAccountsClient, id netappaccounts.NetAppAccountId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - res, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName) + res, err := client.AccountsGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(res.Response) { - return nil, "", fmt.Errorf("retrieving NetApp Account %q (Resource Group %q): %s", id.NetAppAccountName, id.ResourceGroup, err) + if !response.WasNotFound(res.HttpResponse) { + return nil, "", fmt.Errorf("retrieving %s: %s", id.ID(), err) } } - return res, strconv.Itoa(res.StatusCode), nil + return res, strconv.Itoa(res.HttpResponse.StatusCode), nil } } diff --git a/internal/services/netapp/netapp_account_resource_test.go b/internal/services/netapp/netapp_account_resource_test.go index 7cf258ded663..618cde189ae8 100644 --- a/internal/services/netapp/netapp_account_resource_test.go +++ b/internal/services/netapp/netapp_account_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -85,7 +85,7 @@ func testAccNetAppAccount_complete(t *testing.T) { Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("active_directory.#").HasValue("1"), - check.That(data.ResourceName).Key("tags.%").HasValue("1"), + check.That(data.ResourceName).Key("tags.%").HasValue("2"), check.That(data.ResourceName).Key("tags.FoO").HasValue("BaR"), ), }, @@ -103,7 +103,7 @@ func testAccNetAppAccount_update(t *testing.T) { Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("active_directory.#").HasValue("0"), - check.That(data.ResourceName).Key("tags.%").HasValue("0"), + check.That(data.ResourceName).Key("tags.%").HasValue("1"), ), }, { @@ -111,7 +111,7 @@ func testAccNetAppAccount_update(t *testing.T) { Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("active_directory.#").HasValue("1"), - check.That(data.ResourceName).Key("tags.%").HasValue("1"), + check.That(data.ResourceName).Key("tags.%").HasValue("2"), check.That(data.ResourceName).Key("tags.FoO").HasValue("BaR"), ), }, @@ -120,17 +120,17 @@ func testAccNetAppAccount_update(t *testing.T) { } func (t NetAppAccountResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.AccountID(state.ID) + id, err := netappaccounts.ParseNetAppAccountID(state.ID) if err != nil { return nil, err } - resp, err := clients.NetApp.AccountClient.Get(ctx, id.ResourceGroup, id.NetAppAccountName) + resp, err := clients.NetApp.AccountClient.AccountsGet(ctx, *id) if err != nil { return nil, fmt.Errorf("reading Netapp Account (%s): %+v", id.String(), err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (NetAppAccountResource) basicConfig(data acceptance.TestData) string { @@ -142,12 +142,22 @@ provider "azurerm" { resource "azurerm_resource_group" "test" { name = "acctestRG-netapp-%d" location = "%s" + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "SkipASMAzSecPack" = "true", + "SkipNRMSNSG" = "true" + } } resource "azurerm_netapp_account" "test" { name = "acctest-NetAppAccount-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + } } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } @@ -160,6 +170,10 @@ resource "azurerm_netapp_account" "import" { name = azurerm_netapp_account.test.name location = azurerm_netapp_account.test.location resource_group_name = azurerm_netapp_account.test.resource_group_name + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + } } `, r.basicConfig(data)) } @@ -173,6 +187,12 @@ provider "azurerm" { resource "azurerm_resource_group" "test" { name = "acctestRG-netapp-%d" location = "%s" + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "SkipASMAzSecPack" = "true", + "SkipNRMSNSG" = "true" + } } resource "azurerm_netapp_account" "test" { @@ -190,7 +210,8 @@ resource "azurerm_netapp_account" "test" { } tags = { - "FoO" = "BaR" + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "FoO" = "BaR" } } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) diff --git a/internal/services/netapp/netapp_pool_data_source.go b/internal/services/netapp/netapp_pool_data_source.go index f5d2dde7fc1a..28972ab23ba7 100644 --- a/internal/services/netapp/netapp_pool_data_source.go +++ b/internal/services/netapp/netapp_pool_data_source.go @@ -4,14 +4,14 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceNetAppPool() *pluginsdk.Resource { @@ -58,10 +58,10 @@ func dataSourceNetAppPoolRead(d *pluginsdk.ResourceData, meta interface{}) error defer cancel() subscriptionId := meta.(*clients.Client).Account.SubscriptionId - id := parse.NewCapacityPoolID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("name").(string)) - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + id := capacitypools.NewCapacityPoolID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("name").(string)) + resp, err := client.PoolsGet(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } @@ -69,17 +69,14 @@ func dataSourceNetAppPoolRead(d *pluginsdk.ResourceData, meta interface{}) error } d.SetId(id.ID()) - d.Set("name", id.Name) - d.Set("account_name", id.NetAppAccountName) - d.Set("resource_group_name", id.ResourceGroup) - - d.Set("location", location.NormalizeNilable(resp.Location)) - - if poolProperties := resp.PoolProperties; poolProperties != nil { - d.Set("service_level", string(poolProperties.ServiceLevel)) - if poolProperties.Size != nil { - d.Set("size_in_tb", *poolProperties.Size/1099511627776) - } + d.Set("name", id.PoolName) + d.Set("account_name", id.AccountName) + d.Set("resource_group_name", id.ResourceGroupName) + + if model := resp.Model; model != nil { + d.Set("location", location.NormalizeNilable(&model.Location)) + d.Set("service_level", string(model.Properties.ServiceLevel)) + d.Set("size_in_tb", model.Properties.Size/1099511627776) } return nil diff --git a/internal/services/netapp/netapp_pool_resource.go b/internal/services/netapp/netapp_pool_resource.go index 944ee8063cb9..1c8839e7fdd1 100644 --- a/internal/services/netapp/netapp_pool_resource.go +++ b/internal/services/netapp/netapp_pool_resource.go @@ -7,13 +7,14 @@ import ( "strconv" "time" - "github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -34,7 +35,7 @@ func resourceNetAppPool() *pluginsdk.Resource { Delete: pluginsdk.DefaultTimeout(30 * time.Minute), }, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.CapacityPoolID(id) + _, err := capacitypools.ParseCapacityPoolID(id) return err }), @@ -62,9 +63,9 @@ func resourceNetAppPool() *pluginsdk.Resource { Required: true, ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ - string(netapp.ServiceLevelPremium), - string(netapp.ServiceLevelStandard), - string(netapp.ServiceLevelUltra), + string(capacitypools.ServiceLevelPremium), + string(capacitypools.ServiceLevelStandard), + string(capacitypools.ServiceLevelUltra), }, false), }, @@ -79,12 +80,12 @@ func resourceNetAppPool() *pluginsdk.Resource { Optional: true, Computed: true, ValidateFunc: validation.StringInSlice([]string{ - string(netapp.QosTypeAuto), - string(netapp.QosTypeManual), + string(capacitypools.QosTypeAuto), + string(capacitypools.QosTypeManual), }, false), }, - "tags": tags.Schema(), + "tags": commonschema.Tags(), }, } } @@ -95,47 +96,42 @@ func resourceNetAppPoolCreate(d *pluginsdk.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewCapacityPoolID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("name").(string)) + id := capacitypools.NewCapacityPoolID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + existing, err := client.PoolsGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_netapp_pool", id.ID()) } } - location := azure.NormalizeLocation(d.Get("location").(string)) - serviceLevel := d.Get("service_level").(string) sizeInTB := int64(d.Get("size_in_tb").(int)) sizeInMB := sizeInTB * 1024 * 1024 sizeInBytes := sizeInMB * 1024 * 1024 - capacityPoolParameters := netapp.CapacityPool{ - Location: utils.String(location), - PoolProperties: &netapp.PoolProperties{ - ServiceLevel: netapp.ServiceLevel(serviceLevel), - Size: utils.Int64(sizeInBytes), + capacityPoolParameters := capacitypools.CapacityPool{ + Location: azure.NormalizeLocation(d.Get("location").(string)), + Properties: capacitypools.PoolProperties{ + ServiceLevel: capacitypools.ServiceLevel(d.Get("service_level").(string)), + Size: sizeInBytes, }, Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } if qosType, ok := d.GetOk("qos_type"); ok { - capacityPoolParameters.PoolProperties.QosType = netapp.QosType(qosType.(string)) + qos := capacitypools.QosType(qosType.(string)) + capacityPoolParameters.Properties.QosType = &qos } - future, err := client.CreateOrUpdate(ctx, capacityPoolParameters, id.ResourceGroup, id.NetAppAccountName, id.Name) - if err != nil { + if err := client.PoolsCreateOrUpdateThenPoll(ctx, id, capacityPoolParameters); err != nil { return fmt.Errorf("creating %s: %+v", id, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation of %s: %+v", id, err) - } - // Wait for pool to complete update + // Wait for pool to complete create if err := waitForPoolCreateOrUpdate(ctx, client, id); err != nil { return err } @@ -149,14 +145,14 @@ func resourceNetAppPoolUpdate(d *pluginsdk.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.CapacityPoolID(d.Id()) + id, err := capacitypools.ParseCapacityPoolID(d.Id()) if err != nil { return err } shouldUpdate := false - update := netapp.CapacityPoolPatch{ - PoolPatchProperties: &netapp.PoolPatchProperties{}, + update := capacitypools.CapacityPoolPatch{ + Properties: &capacitypools.PoolPatchProperties{}, } if d.HasChange("size_in_tb") { @@ -166,13 +162,13 @@ func resourceNetAppPoolUpdate(d *pluginsdk.ResourceData, meta interface{}) error sizeInMB := sizeInTB * 1024 * 1024 sizeInBytes := sizeInMB * 1024 * 1024 - update.PoolPatchProperties.Size = utils.Int64(sizeInBytes) + update.Properties.Size = utils.Int64(sizeInBytes) } if d.HasChange("qos_type") { shouldUpdate = true - qosType := d.Get("qos_type") - update.PoolPatchProperties.QosType = netapp.QosType(qosType.(string)) + qosType := capacitypools.QosType(d.Get("qos_type").(string)) + update.Properties.QosType = &qosType } if d.HasChange("tags") { @@ -182,16 +178,12 @@ func resourceNetAppPoolUpdate(d *pluginsdk.ResourceData, meta interface{}) error } if shouldUpdate { - future, err := client.Update(ctx, update, id.ResourceGroup, id.NetAppAccountName, id.Name) - if err != nil { - return fmt.Errorf("updating Capacity Pool %q: %+v", id.Name, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the update of %s: %+v", id, err) + if err = client.PoolsUpdateThenPoll(ctx, *id, update); err != nil { + return fmt.Errorf("updating %s: %+v", id.ID(), err) } // Wait for pool to complete update - if err := waitForPoolCreateOrUpdate(ctx, client, *id); err != nil { + if err = waitForPoolCreateOrUpdate(ctx, client, *id); err != nil { return err } } @@ -204,14 +196,14 @@ func resourceNetAppPoolRead(d *pluginsdk.ResourceData, meta interface{}) error { ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.CapacityPoolID(d.Id()) + id, err := capacitypools.ParseCapacityPoolID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + resp, err := client.PoolsGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[INFO] %s does not exist - removing from state", *id) d.SetId("") return nil @@ -219,26 +211,31 @@ func resourceNetAppPoolRead(d *pluginsdk.ResourceData, meta interface{}) error { return fmt.Errorf("retrieving %s: %+v", *id, err) } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("account_name", id.NetAppAccountName) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - if poolProperties := resp.PoolProperties; poolProperties != nil { + d.Set("name", id.PoolName) + d.Set("resource_group_name", id.ResourceGroupName) + d.Set("account_name", id.AccountName) + + if model := resp.Model; model != nil { + d.Set("location", azure.NormalizeLocation(model.Location)) + + poolProperties := model.Properties d.Set("service_level", poolProperties.ServiceLevel) sizeInTB := int64(0) - if poolProperties.Size != nil { - sizeInBytes := *poolProperties.Size - sizeInMB := sizeInBytes / 1024 / 1024 - sizeInTB = sizeInMB / 1024 / 1024 - } + sizeInBytes := poolProperties.Size + sizeInMB := sizeInBytes / 1024 / 1024 + sizeInTB = sizeInMB / 1024 / 1024 d.Set("size_in_tb", int(sizeInTB)) - d.Set("qos_type", string(poolProperties.QosType)) + qosType := "" + if poolProperties.QosType != nil { + qosType = string(*poolProperties.QosType) + } + d.Set("qos_type", qosType) + + return tags.FlattenAndSet(d, model.Tags) } - return tags.FlattenAndSet(d, resp.Tags) + return nil } func resourceNetAppPoolDelete(d *pluginsdk.ResourceData, meta interface{}) error { @@ -246,18 +243,14 @@ func resourceNetAppPoolDelete(d *pluginsdk.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.CapacityPoolID(d.Id()) + id, err := capacitypools.ParseCapacityPoolID(d.Id()) if err != nil { return err } - future, err := client.Delete(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) - if err != nil { + if err := client.PoolsDeleteThenPoll(ctx, *id); err != nil { return fmt.Errorf("deleting %s: %+v", *id, err) } - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation/update of %q: %+v", id, err) - } // The resource NetApp Pool depends on the resource NetApp Account. // Although the delete API returns 404 which means the NetApp Pool resource has been deleted. @@ -286,20 +279,20 @@ func resourceNetAppPoolDelete(d *pluginsdk.ResourceData, meta interface{}) error return nil } -func netappPoolDeleteStateRefreshFunc(ctx context.Context, client *netapp.PoolsClient, id parse.CapacityPoolId) pluginsdk.StateRefreshFunc { +func netappPoolDeleteStateRefreshFunc(ctx context.Context, client *capacitypools.CapacityPoolsClient, id capacitypools.CapacityPoolId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - res, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + res, err := client.PoolsGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(res.Response) { + if !response.WasNotFound(res.HttpResponse) { return nil, "", fmt.Errorf("retrieving %s: %+v", id, err) } } - return res, strconv.Itoa(res.StatusCode), nil + return res, strconv.Itoa(res.HttpResponse.StatusCode), nil } } -func waitForPoolCreateOrUpdate(ctx context.Context, client *netapp.PoolsClient, id parse.CapacityPoolId) error { +func waitForPoolCreateOrUpdate(ctx context.Context, client *capacitypools.CapacityPoolsClient, id capacitypools.CapacityPoolId) error { deadline, ok := ctx.Deadline() if !ok { return fmt.Errorf("context had no deadline") @@ -321,15 +314,15 @@ func waitForPoolCreateOrUpdate(ctx context.Context, client *netapp.PoolsClient, return nil } -func netappPoolStateRefreshFunc(ctx context.Context, client *netapp.PoolsClient, id parse.CapacityPoolId) pluginsdk.StateRefreshFunc { +func netappPoolStateRefreshFunc(ctx context.Context, client *capacitypools.CapacityPoolsClient, id capacitypools.CapacityPoolId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - res, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + res, err := client.PoolsGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(res.Response) { - return nil, "", fmt.Errorf("retrieving NetApp Capacity Pool %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err) + if !response.WasNotFound(res.HttpResponse) { + return nil, "", fmt.Errorf("retrieving %s: %s", id.ID(), err) } } - return res, strconv.Itoa(res.StatusCode), nil + return res, strconv.Itoa(res.HttpResponse.StatusCode), nil } } diff --git a/internal/services/netapp/netapp_pool_resource_test.go b/internal/services/netapp/netapp_pool_resource_test.go index 59457816bd30..4c8396269afb 100644 --- a/internal/services/netapp/netapp_pool_resource_test.go +++ b/internal/services/netapp/netapp_pool_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -59,7 +59,7 @@ func TestAccNetAppPool_complete(t *testing.T) { check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("service_level").HasValue("Standard"), check.That(data.ResourceName).Key("size_in_tb").HasValue("15"), - check.That(data.ResourceName).Key("tags.%").HasValue("1"), + check.That(data.ResourceName).Key("tags.%").HasValue("2"), check.That(data.ResourceName).Key("tags.FoO").HasValue("BaR"), check.That(data.ResourceName).Key("qos_type").HasValue("Auto"), ), @@ -78,7 +78,7 @@ func TestAccNetAppPool_update(t *testing.T) { Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("size_in_tb").HasValue("4"), - check.That(data.ResourceName).Key("tags.%").HasValue("0"), + check.That(data.ResourceName).Key("tags.%").HasValue("1"), check.That(data.ResourceName).Key("qos_type").HasValue("Auto"), ), }, @@ -88,7 +88,7 @@ func TestAccNetAppPool_update(t *testing.T) { Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("size_in_tb").HasValue("15"), - check.That(data.ResourceName).Key("tags.%").HasValue("1"), + check.That(data.ResourceName).Key("tags.%").HasValue("2"), check.That(data.ResourceName).Key("tags.FoO").HasValue("BaR"), check.That(data.ResourceName).Key("qos_type").HasValue("Auto"), ), @@ -99,7 +99,7 @@ func TestAccNetAppPool_update(t *testing.T) { Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("size_in_tb").HasValue("15"), - check.That(data.ResourceName).Key("tags.%").HasValue("1"), + check.That(data.ResourceName).Key("tags.%").HasValue("2"), check.That(data.ResourceName).Key("tags.FoO").HasValue("BaR"), check.That(data.ResourceName).Key("qos_type").HasValue("Manual"), ), @@ -108,17 +108,17 @@ func TestAccNetAppPool_update(t *testing.T) { } func (t NetAppPoolResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.CapacityPoolID(state.ID) + id, err := capacitypools.ParseCapacityPoolID(state.ID) if err != nil { return nil, err } - resp, err := clients.NetApp.PoolClient.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + resp, err := clients.NetApp.PoolClient.PoolsGet(ctx, *id) if err != nil { return nil, fmt.Errorf("reading Netapp Pool (%s): %+v", id.String(), err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (NetAppPoolResource) basic(data acceptance.TestData) string { @@ -130,6 +130,12 @@ provider "azurerm" { resource "azurerm_resource_group" "test" { name = "acctestRG-netapp-%d" location = "%s" + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "SkipASMAzSecPack" = "true", + "SkipNRMSNSG" = "true" + } } resource "azurerm_netapp_account" "test" { @@ -145,6 +151,10 @@ resource "azurerm_netapp_pool" "test" { resource_group_name = azurerm_resource_group.test.name service_level = "Standard" size_in_tb = 4 + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + } } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) } @@ -172,12 +182,23 @@ provider "azurerm" { resource "azurerm_resource_group" "test" { name = "acctestRG-netapp-%d" location = "%s" + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "SkipASMAzSecPack" = "true", + "SkipNRMSNSG" = "true" + } } resource "azurerm_netapp_account" "test" { name = "acctest-NetAppAccount-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "SkipASMAzSecPack" = "true" + } } resource "azurerm_netapp_pool" "test" { @@ -190,7 +211,8 @@ resource "azurerm_netapp_pool" "test" { qos_type = "Auto" tags = { - "FoO" = "BaR" + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "FoO" = "BaR" } } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) @@ -205,12 +227,23 @@ provider "azurerm" { resource "azurerm_resource_group" "test" { name = "acctestRG-netapp-%d" location = "%s" + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "SkipASMAzSecPack" = "true", + "SkipNRMSNSG" = "true" + } } resource "azurerm_netapp_account" "test" { name = "acctest-NetAppAccount-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "SkipASMAzSecPack" = "true" + } } resource "azurerm_netapp_pool" "test" { @@ -223,7 +256,8 @@ resource "azurerm_netapp_pool" "test" { qos_type = "Manual" tags = { - "FoO" = "BaR" + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "FoO" = "BaR" } } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) diff --git a/internal/services/netapp/netapp_snapshot_data_source.go b/internal/services/netapp/netapp_snapshot_data_source.go index 306338ab3902..e5f7e540f7c9 100644 --- a/internal/services/netapp/netapp_snapshot_data_source.go +++ b/internal/services/netapp/netapp_snapshot_data_source.go @@ -4,14 +4,14 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceNetAppSnapshot() *pluginsdk.Resource { @@ -60,23 +60,25 @@ func dataSourceNetAppSnapshotRead(d *pluginsdk.ResourceData, meta interface{}) e ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewSnapshotID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("pool_name").(string), d.Get("volume_name").(string), d.Get("name").(string)) - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.VolumeName, id.Name) + id := snapshots.NewSnapshotID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("pool_name").(string), d.Get("volume_name").(string), d.Get("name").(string)) + resp, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } return fmt.Errorf("retrieving %s: %+v", id, err) } d.SetId(id.ID()) - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("account_name", id.NetAppAccountName) - d.Set("pool_name", id.CapacityPoolName) + d.Set("name", id.SnapshotName) + d.Set("resource_group_name", id.ResourceGroupName) + d.Set("account_name", id.AccountName) + d.Set("pool_name", id.PoolName) d.Set("volume_name", id.VolumeName) - d.Set("location", location.NormalizeNilable(resp.Location)) + if model := resp.Model; model != nil { + d.Set("location", location.NormalizeNilable(&model.Location)) + } return nil } diff --git a/internal/services/netapp/netapp_snapshot_policy_data_source.go b/internal/services/netapp/netapp_snapshot_policy_data_source.go index 5e449469091f..227a1d90e9af 100644 --- a/internal/services/netapp/netapp_snapshot_policy_data_source.go +++ b/internal/services/netapp/netapp_snapshot_policy_data_source.go @@ -4,15 +4,15 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceNetAppSnapshotPolicy() *pluginsdk.Resource { @@ -159,10 +159,10 @@ func dataSourceNetAppSnapshotPolicyRead(d *pluginsdk.ResourceData, meta interfac ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewSnapshotPolicyID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("name").(string)) - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + id := snapshotpolicy.NewSnapshotPoliciesID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("name").(string)) + resp, err := client.SnapshotPoliciesGet(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } return fmt.Errorf("retrieving %s: %+v", id, err) @@ -170,13 +170,14 @@ func dataSourceNetAppSnapshotPolicyRead(d *pluginsdk.ResourceData, meta interfac d.SetId(id.ID()) - d.Set("name", id.Name) - d.Set("account_name", id.NetAppAccountName) - d.Set("resource_group_name", id.ResourceGroup) + d.Set("name", id.SnapshotPolicyName) + d.Set("account_name", id.AccountName) + d.Set("resource_group_name", id.ResourceGroupName) - d.Set("location", location.NormalizeNilable(resp.Location)) + if model := resp.Model; model != nil { + d.Set("location", location.NormalizeNilable(&model.Location)) - if props := resp.SnapshotPolicyProperties; props != nil { + props := model.Properties d.Set("enabled", props.Enabled) if err := d.Set("hourly_schedule", flattenNetAppVolumeSnapshotPolicyHourlySchedule(props.HourlySchedule)); err != nil { return fmt.Errorf("setting `hourly_schedule`: %+v", err) diff --git a/internal/services/netapp/netapp_snapshot_policy_resource.go b/internal/services/netapp/netapp_snapshot_policy_resource.go index 78c363e8bc0e..13e39b898c31 100644 --- a/internal/services/netapp/netapp_snapshot_policy_resource.go +++ b/internal/services/netapp/netapp_snapshot_policy_resource.go @@ -8,13 +8,14 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" netAppValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -35,7 +36,7 @@ func resourceNetAppSnapshotPolicy() *pluginsdk.Resource { Delete: pluginsdk.DefaultTimeout(30 * time.Minute), }, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.SnapshotPolicyID(id) + _, err := snapshotpolicy.ParseSnapshotPoliciesID(id) return err }), @@ -189,68 +190,50 @@ func resourceNetAppSnapshotPolicy() *pluginsdk.Resource { }, }, - "tags": tags.Schema(), + "tags": commonschema.Tags(), }, } } func resourceNetAppSnapshotPolicyCreate(d *pluginsdk.ResourceData, meta interface{}) error { client := meta.(*clients.Client).NetApp.SnapshotPoliciesClient + subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - accountName := d.Get("account_name").(string) + id := snapshotpolicy.NewSnapshotPoliciesID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, resourceGroup, accountName, name) + existing, err := client.SnapshotPoliciesGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing NetApp SnapshotPolicy %q (Resource Group %q): %+v", name, resourceGroup, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of existing %s: %+v", id.ID(), err) } } - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_netapp_snapshot_policy", *existing.ID) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_netapp_snapshot_policy", id.ID()) } } - location := azure.NormalizeLocation(d.Get("location").(string)) - - enabled := d.Get("enabled").(bool) - - hourlyScheduleRaw := d.Get("hourly_schedule").([]interface{}) - hourlySchedule := expandNetAppSnapshotPolicyHourlySchedule(hourlyScheduleRaw) - - dailyScheduleRaw := d.Get("daily_schedule").([]interface{}) - dailySchedule := expandNetAppSnapshotPolicyDailySchedule(dailyScheduleRaw) - - weeklyScheduleRaw := d.Get("weekly_schedule").([]interface{}) - weeklySchedule := expandNetAppSnapshotPolicyWeeklySchedule(weeklyScheduleRaw) - - monthlyScheduleRaw := d.Get("monthly_schedule").([]interface{}) - monthlySchedule := expandNetAppSnapshotPolicyMonthlySchedule(monthlyScheduleRaw) - - parameters := netapp.SnapshotPolicy{ - Location: utils.String(location), - Name: utils.String(name), - SnapshotPolicyProperties: &netapp.SnapshotPolicyProperties{ - HourlySchedule: hourlySchedule, - DailySchedule: dailySchedule, - WeeklySchedule: weeklySchedule, - MonthlySchedule: monthlySchedule, - Enabled: utils.Bool(enabled), + parameters := snapshotpolicy.SnapshotPolicy{ + Location: azure.NormalizeLocation(d.Get("location").(string)), + Name: utils.String(id.SnapshotPolicyName), + Properties: snapshotpolicy.SnapshotPolicyProperties{ + HourlySchedule: expandNetAppSnapshotPolicyHourlySchedule(d.Get("hourly_schedule").([]interface{})), + DailySchedule: expandNetAppSnapshotPolicyDailySchedule(d.Get("daily_schedule").([]interface{})), + WeeklySchedule: expandNetAppSnapshotPolicyWeeklySchedule(d.Get("weekly_schedule").([]interface{})), + MonthlySchedule: expandNetAppSnapshotPolicyMonthlySchedule(d.Get("monthly_schedule").([]interface{})), + Enabled: utils.Bool(d.Get("enabled").(bool)), }, Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } - if _, err := client.Create(ctx, parameters, resourceGroup, accountName, name); err != nil { - return fmt.Errorf("creating NetApp SnapshotPolicy %q (Resource Group %q): %+v", name, resourceGroup, err) + if _, err := client.SnapshotPoliciesCreate(ctx, id, parameters); err != nil { + return fmt.Errorf("creating %s: %+v", id, err) } // Waiting for snapshot policy be completely provisioned - id := parse.NewSnapshotPolicyID(client.SubscriptionID, resourceGroup, accountName, name) - log.Printf("[DEBUG] Waiting for NetApp Snapshot Policy Provisioning Service %q (Resource Group %q) to complete", id.Name, id.ResourceGroup) + log.Printf("[DEBUG] Waiting for %s to complete", id) if err := waitForSnapshotPolicyCreation(ctx, client, id, d.Timeout(pluginsdk.TimeoutDelete)); err != nil { return err } @@ -265,46 +248,26 @@ func resourceNetAppSnapshotPolicyUpdate(d *pluginsdk.ResourceData, meta interfac ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - accountName := d.Get("account_name").(string) - - location := azure.NormalizeLocation(d.Get("location").(string)) - - enabled := d.Get("enabled").(bool) - - hourlyScheduleRaw := d.Get("hourly_schedule").([]interface{}) - hourlySchedule := expandNetAppSnapshotPolicyHourlySchedule(hourlyScheduleRaw) - - dailyScheduleRaw := d.Get("daily_schedule").([]interface{}) - dailySchedule := expandNetAppSnapshotPolicyDailySchedule(dailyScheduleRaw) - - weeklyScheduleRaw := d.Get("weekly_schedule").([]interface{}) - weeklySchedule := expandNetAppSnapshotPolicyWeeklySchedule(weeklyScheduleRaw) - - monthlyScheduleRaw := d.Get("monthly_schedule").([]interface{}) - monthlySchedule := expandNetAppSnapshotPolicyMonthlySchedule(monthlyScheduleRaw) + id, err := snapshotpolicy.ParseSnapshotPoliciesID(d.Id()) + if err != nil { + return err + } - parameters := netapp.SnapshotPolicyPatch{ - Location: utils.String(location), - Name: utils.String(name), - SnapshotPolicyProperties: &netapp.SnapshotPolicyProperties{ - HourlySchedule: hourlySchedule, - DailySchedule: dailySchedule, - WeeklySchedule: weeklySchedule, - MonthlySchedule: monthlySchedule, - Enabled: utils.Bool(enabled), + parameters := snapshotpolicy.SnapshotPolicyPatch{ + Location: utils.String(azure.NormalizeLocation(d.Get("location").(string))), + Name: utils.String(id.SnapshotPolicyName), + Properties: &snapshotpolicy.SnapshotPolicyProperties{ + HourlySchedule: expandNetAppSnapshotPolicyHourlySchedule(d.Get("hourly_schedule").([]interface{})), + DailySchedule: expandNetAppSnapshotPolicyDailySchedule(d.Get("daily_schedule").([]interface{})), + WeeklySchedule: expandNetAppSnapshotPolicyWeeklySchedule(d.Get("weekly_schedule").([]interface{})), + MonthlySchedule: expandNetAppSnapshotPolicyMonthlySchedule(d.Get("monthly_schedule").([]interface{})), + Enabled: utils.Bool(d.Get("enabled").(bool)), }, Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } - future, err := client.Update(ctx, parameters, resourceGroup, accountName, name) - if err != nil { - return fmt.Errorf("updating NetApp SnapshotPolicy %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation/update of %q (Resource Group %q): %+v", name, resourceGroup, err) + if err = client.SnapshotPoliciesUpdateThenPoll(ctx, *id, parameters); err != nil { + return fmt.Errorf("updating %s: %+v", id, err) } return resourceNetAppSnapshotPolicyRead(d, meta) @@ -315,44 +278,47 @@ func resourceNetAppSnapshotPolicyRead(d *pluginsdk.ResourceData, meta interface{ ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SnapshotPolicyID(d.Id()) + id, err := snapshotpolicy.ParseSnapshotPoliciesID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + resp, err := client.SnapshotPoliciesGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[INFO] NetApp SnapshotPolicy %q does not exist - removing from state", d.Id()) d.SetId("") return nil } - return fmt.Errorf("reading NetApp SnapshotPolicy %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("reading %s: %+v", *id, err) } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("account_name", id.NetAppAccountName) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - if props := resp.SnapshotPolicyProperties; props != nil { + d.Set("name", id.SnapshotPolicyName) + d.Set("resource_group_name", id.ResourceGroupName) + d.Set("account_name", id.AccountName) + + if model := resp.Model; model != nil { + d.Set("location", azure.NormalizeLocation(model.Location)) + + props := model.Properties d.Set("enabled", props.Enabled) - if err := d.Set("hourly_schedule", flattenNetAppVolumeSnapshotPolicyHourlySchedule(props.HourlySchedule)); err != nil { + if err = d.Set("hourly_schedule", flattenNetAppVolumeSnapshotPolicyHourlySchedule(props.HourlySchedule)); err != nil { return fmt.Errorf("setting `hourly_schedule`: %+v", err) } - if err := d.Set("daily_schedule", flattenNetAppVolumeSnapshotPolicyDailySchedule(props.DailySchedule)); err != nil { + if err = d.Set("daily_schedule", flattenNetAppVolumeSnapshotPolicyDailySchedule(props.DailySchedule)); err != nil { return fmt.Errorf("setting `daily_schedule`: %+v", err) } - if err := d.Set("weekly_schedule", flattenNetAppVolumeSnapshotPolicyWeeklySchedule(props.WeeklySchedule)); err != nil { + if err = d.Set("weekly_schedule", flattenNetAppVolumeSnapshotPolicyWeeklySchedule(props.WeeklySchedule)); err != nil { return fmt.Errorf("setting `weekly_schedule`: %+v", err) } - if err := d.Set("monthly_schedule", flattenNetAppVolumeSnapshotPolicyMonthlySchedule(props.MonthlySchedule)); err != nil { + if err = d.Set("monthly_schedule", flattenNetAppVolumeSnapshotPolicyMonthlySchedule(props.MonthlySchedule)); err != nil { return fmt.Errorf("setting `monthly_schedule`: %+v", err) } + + return tags.FlattenAndSet(d, model.Tags) } - return tags.FlattenAndSet(d, resp.Tags) + return nil } func resourceNetAppSnapshotPolicyDelete(d *pluginsdk.ResourceData, meta interface{}) error { @@ -360,21 +326,17 @@ func resourceNetAppSnapshotPolicyDelete(d *pluginsdk.ResourceData, meta interfac ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SnapshotPolicyID(d.Id()) + id, err := snapshotpolicy.ParseSnapshotPoliciesID(d.Id()) if err != nil { return err } // Deleting snapshot policy and waiting for it fo fully complete the operation - future, err := client.Delete(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) - if err != nil { - return fmt.Errorf("deleting NetApp Snapshot Policy %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + if err = client.SnapshotPoliciesDeleteThenPoll(ctx, *id); err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) } - log.Printf("[DEBUG] Waiting for NetApp SnapshotPolicy Provisioning Service %q (Resource Group %q) to be deleted", id.Name, id.ResourceGroup) - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for deletion of %q: %+v", id, err) - } + log.Printf("[DEBUG] Waiting for %s to be deleted", id) if err := waitForSnapshotPolicyDeletion(ctx, client, *id, d.Timeout(pluginsdk.TimeoutDelete)); err != nil { return err } @@ -382,98 +344,98 @@ func resourceNetAppSnapshotPolicyDelete(d *pluginsdk.ResourceData, meta interfac return nil } -func expandNetAppSnapshotPolicyHourlySchedule(input []interface{}) *netapp.HourlySchedule { +func expandNetAppSnapshotPolicyHourlySchedule(input []interface{}) *snapshotpolicy.HourlySchedule { if len(input) == 0 || input[0] == nil { - return &netapp.HourlySchedule{} + return &snapshotpolicy.HourlySchedule{} } - hourlyScheduleObject := netapp.HourlySchedule{} + hourlyScheduleObject := snapshotpolicy.HourlySchedule{} hourlyScheduleRaw := input[0].(map[string]interface{}) if v, ok := hourlyScheduleRaw["snapshots_to_keep"]; ok { - hourlyScheduleObject.SnapshotsToKeep = utils.Int32(int32(v.(int))) + hourlyScheduleObject.SnapshotsToKeep = utils.Int64(int64(v.(int))) } if v, ok := hourlyScheduleRaw["minute"]; ok { - hourlyScheduleObject.Minute = utils.Int32(int32(v.(int))) + hourlyScheduleObject.Minute = utils.Int64(int64(v.(int))) } return &hourlyScheduleObject } -func expandNetAppSnapshotPolicyDailySchedule(input []interface{}) *netapp.DailySchedule { +func expandNetAppSnapshotPolicyDailySchedule(input []interface{}) *snapshotpolicy.DailySchedule { if len(input) == 0 || input[0] == nil { - return &netapp.DailySchedule{} + return &snapshotpolicy.DailySchedule{} } - dailyScheduleObject := netapp.DailySchedule{} + dailyScheduleObject := snapshotpolicy.DailySchedule{} dailyScheduleRaw := input[0].(map[string]interface{}) if v, ok := dailyScheduleRaw["snapshots_to_keep"]; ok { - dailyScheduleObject.SnapshotsToKeep = utils.Int32(int32(v.(int))) + dailyScheduleObject.SnapshotsToKeep = utils.Int64(int64(v.(int))) } if v, ok := dailyScheduleRaw["hour"]; ok { - dailyScheduleObject.Hour = utils.Int32(int32(v.(int))) + dailyScheduleObject.Hour = utils.Int64(int64(v.(int))) } if v, ok := dailyScheduleRaw["minute"]; ok { - dailyScheduleObject.Minute = utils.Int32(int32(v.(int))) + dailyScheduleObject.Minute = utils.Int64(int64(v.(int))) } return &dailyScheduleObject } -func expandNetAppSnapshotPolicyWeeklySchedule(input []interface{}) *netapp.WeeklySchedule { +func expandNetAppSnapshotPolicyWeeklySchedule(input []interface{}) *snapshotpolicy.WeeklySchedule { if len(input) == 0 || input[0] == nil { - return &netapp.WeeklySchedule{} + return &snapshotpolicy.WeeklySchedule{} } - weeklyScheduleObject := netapp.WeeklySchedule{} + weeklyScheduleObject := snapshotpolicy.WeeklySchedule{} weeklyScheduleRaw := input[0].(map[string]interface{}) if v, ok := weeklyScheduleRaw["snapshots_to_keep"]; ok { - weeklyScheduleObject.SnapshotsToKeep = utils.Int32(int32(v.(int))) + weeklyScheduleObject.SnapshotsToKeep = utils.Int64(int64(v.(int))) } if _, ok := weeklyScheduleRaw["days_of_week"]; ok { weeklyScheduleObject.Day = utils.ExpandStringSliceWithDelimiter(weeklyScheduleRaw["days_of_week"].(*pluginsdk.Set).List(), ",") } if v, ok := weeklyScheduleRaw["hour"]; ok { - weeklyScheduleObject.Hour = utils.Int32(int32(v.(int))) + weeklyScheduleObject.Hour = utils.Int64(int64(v.(int))) } if v, ok := weeklyScheduleRaw["minute"]; ok { - weeklyScheduleObject.Minute = utils.Int32(int32(v.(int))) + weeklyScheduleObject.Minute = utils.Int64(int64(v.(int))) } return &weeklyScheduleObject } -func expandNetAppSnapshotPolicyMonthlySchedule(input []interface{}) *netapp.MonthlySchedule { +func expandNetAppSnapshotPolicyMonthlySchedule(input []interface{}) *snapshotpolicy.MonthlySchedule { if len(input) == 0 || input[0] == nil { - return &netapp.MonthlySchedule{} + return &snapshotpolicy.MonthlySchedule{} } - monthlyScheduleObject := netapp.MonthlySchedule{} + monthlyScheduleObject := snapshotpolicy.MonthlySchedule{} monthlyScheduleRaw := input[0].(map[string]interface{}) if v, ok := monthlyScheduleRaw["snapshots_to_keep"]; ok { - monthlyScheduleObject.SnapshotsToKeep = utils.Int32(int32(v.(int))) + monthlyScheduleObject.SnapshotsToKeep = utils.Int64(int64(v.(int))) } if _, ok := monthlyScheduleRaw["days_of_month"]; ok { monthlyScheduleObject.DaysOfMonth = utils.ExpandIntSliceWithDelimiter(monthlyScheduleRaw["days_of_month"].(*pluginsdk.Set).List(), ",") } if v, ok := monthlyScheduleRaw["hour"]; ok { - monthlyScheduleObject.Hour = utils.Int32(int32(v.(int))) + monthlyScheduleObject.Hour = utils.Int64(int64(v.(int))) } if v, ok := monthlyScheduleRaw["minute"]; ok { - monthlyScheduleObject.Minute = utils.Int32(int32(v.(int))) + monthlyScheduleObject.Minute = utils.Int64(int64(v.(int))) } return &monthlyScheduleObject } -func flattenNetAppVolumeSnapshotPolicyHourlySchedule(input *netapp.HourlySchedule) []interface{} { +func flattenNetAppVolumeSnapshotPolicyHourlySchedule(input *snapshotpolicy.HourlySchedule) []interface{} { if input == nil { return []interface{}{} } @@ -486,7 +448,7 @@ func flattenNetAppVolumeSnapshotPolicyHourlySchedule(input *netapp.HourlySchedul } } -func flattenNetAppVolumeSnapshotPolicyDailySchedule(input *netapp.DailySchedule) []interface{} { +func flattenNetAppVolumeSnapshotPolicyDailySchedule(input *snapshotpolicy.DailySchedule) []interface{} { if input == nil { return []interface{}{} } @@ -500,7 +462,7 @@ func flattenNetAppVolumeSnapshotPolicyDailySchedule(input *netapp.DailySchedule) } } -func flattenNetAppVolumeSnapshotPolicyWeeklySchedule(input *netapp.WeeklySchedule) []interface{} { +func flattenNetAppVolumeSnapshotPolicyWeeklySchedule(input *snapshotpolicy.WeeklySchedule) []interface{} { if input == nil { return []interface{}{} } @@ -522,7 +484,7 @@ func flattenNetAppVolumeSnapshotPolicyWeeklySchedule(input *netapp.WeeklySchedul } } -func flattenNetAppVolumeSnapshotPolicyMonthlySchedule(input *netapp.MonthlySchedule) []interface{} { +func flattenNetAppVolumeSnapshotPolicyMonthlySchedule(input *snapshotpolicy.MonthlySchedule) []interface{} { if input == nil { return []interface{}{} } @@ -545,7 +507,7 @@ func flattenNetAppVolumeSnapshotPolicyMonthlySchedule(input *netapp.MonthlySched } } -func waitForSnapshotPolicyCreation(ctx context.Context, client *netapp.SnapshotPoliciesClient, id parse.SnapshotPolicyId, timeout time.Duration) error { +func waitForSnapshotPolicyCreation(ctx context.Context, client *snapshotpolicy.SnapshotPolicyClient, id snapshotpolicy.SnapshotPoliciesId, timeout time.Duration) error { stateConf := &pluginsdk.StateChangeConf{ ContinuousTargetOccurence: 5, Delay: 10 * time.Second, @@ -557,13 +519,13 @@ func waitForSnapshotPolicyCreation(ctx context.Context, client *netapp.SnapshotP } if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting NetApp Volume Provisioning Service %q (Resource Group %q) to complete: %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("waiting for %s to complete: %+v", id, err) } return nil } -func waitForSnapshotPolicyDeletion(ctx context.Context, client *netapp.SnapshotPoliciesClient, id parse.SnapshotPolicyId, timeout time.Duration) error { +func waitForSnapshotPolicyDeletion(ctx context.Context, client *snapshotpolicy.SnapshotPolicyClient, id snapshotpolicy.SnapshotPoliciesId, timeout time.Duration) error { stateConf := &pluginsdk.StateChangeConf{ ContinuousTargetOccurence: 5, Delay: 10 * time.Second, @@ -575,21 +537,21 @@ func waitForSnapshotPolicyDeletion(ctx context.Context, client *netapp.SnapshotP } if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for NetApp SnapshotPolicy Provisioning Service %q (Resource Group %q) to be deleted: %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("waiting for %s to be deleted: %+v", id, err) } return nil } -func netappSnapshotPolicyStateRefreshFunc(ctx context.Context, client *netapp.SnapshotPoliciesClient, id parse.SnapshotPolicyId) pluginsdk.StateRefreshFunc { +func netappSnapshotPolicyStateRefreshFunc(ctx context.Context, client *snapshotpolicy.SnapshotPolicyClient, id snapshotpolicy.SnapshotPoliciesId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - res, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + res, err := client.SnapshotPoliciesGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(res.Response) { - return nil, "", fmt.Errorf("retrieving NetApp SnapshotPolicy %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err) + if !response.WasNotFound(res.HttpResponse) { + return nil, "", fmt.Errorf("retrieving %s: %s", id, err) } } - return res, strconv.Itoa(res.StatusCode), nil + return res, strconv.Itoa(res.HttpResponse.StatusCode), nil } } diff --git a/internal/services/netapp/netapp_snapshot_policy_test.go b/internal/services/netapp/netapp_snapshot_policy_test.go index d6d654b6728d..e34eb0b19a71 100644 --- a/internal/services/netapp/netapp_snapshot_policy_test.go +++ b/internal/services/netapp/netapp_snapshot_policy_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -156,17 +156,17 @@ func TestAccNetAppSnapshotPolicy_complete(t *testing.T) { } func (t NetAppSnapshotPolicyResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.SnapshotPolicyID(state.ID) + id, err := snapshotpolicy.ParseSnapshotPoliciesID(state.ID) if err != nil { return nil, err } - resp, err := clients.NetApp.SnapshotPoliciesClient.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.Name) + resp, err := clients.NetApp.SnapshotPoliciesClient.SnapshotPoliciesGet(ctx, *id) if err != nil { return nil, fmt.Errorf("reading Netapp SnapshotPolicy (%s): %+v", id.String(), err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (NetAppSnapshotPolicyResource) basic(data acceptance.TestData) string { diff --git a/internal/services/netapp/netapp_snapshot_resource.go b/internal/services/netapp/netapp_snapshot_resource.go index 4c5f045af0fd..8ae77671d270 100644 --- a/internal/services/netapp/netapp_snapshot_resource.go +++ b/internal/services/netapp/netapp_snapshot_resource.go @@ -7,15 +7,14 @@ import ( "strconv" "time" - "github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func resourceNetAppSnapshot() *pluginsdk.Resource { @@ -31,7 +30,7 @@ func resourceNetAppSnapshot() *pluginsdk.Resource { Delete: pluginsdk.DefaultTimeout(30 * time.Minute), }, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.SnapshotID(id) + _, err := snapshots.ParseSnapshotID(id) return err }), @@ -77,32 +76,28 @@ func resourceNetAppSnapshotCreate(d *pluginsdk.ResourceData, meta interface{}) e ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewSnapshotID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("pool_name").(string), d.Get("volume_name").(string), d.Get("name").(string)) + id := snapshots.NewSnapshotID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("pool_name").(string), d.Get("volume_name").(string), d.Get("name").(string)) if d.IsNewResource() { - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.VolumeName, id.Name) + resp, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(resp.Response) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("checking for presence of %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(resp.Response) { + if !response.WasNotFound(resp.HttpResponse) { return tf.ImportAsExistsError("azurerm_netapp_snapshot", id.ID()) } } location := azure.NormalizeLocation(d.Get("location").(string)) - parameters := netapp.Snapshot{ - Location: utils.String(location), + parameters := snapshots.Snapshot{ + Location: location, } - future, err := client.Create(ctx, parameters, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.VolumeName, id.Name) - if err != nil { + if err := client.CreateThenPoll(ctx, id, parameters); err != nil { return fmt.Errorf("creating %s: %+v", id, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for creation of %s: %+v", id, err) - } d.SetId(id.ID()) return resourceNetAppSnapshotRead(d, meta) @@ -113,28 +108,29 @@ func resourceNetAppSnapshotRead(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SnapshotID(d.Id()) + id, err := snapshots.ParseSnapshotID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.VolumeName, id.Name) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[INFO] NetApp Snapshots %q does not exist - removing from state", d.Id()) d.SetId("") return nil } - return fmt.Errorf("reading NetApp Snapshots %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("reading %s: %+v", *id, err) } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("account_name", id.NetAppAccountName) - d.Set("pool_name", id.CapacityPoolName) + d.Set("name", id.SnapshotName) + d.Set("resource_group_name", id.ResourceGroupName) + d.Set("account_name", id.AccountName) + d.Set("pool_name", id.PoolName) d.Set("volume_name", id.VolumeName) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) + + if model := resp.Model; model != nil { + d.Set("location", azure.NormalizeLocation(model.Location)) } return nil @@ -145,13 +141,13 @@ func resourceNetAppSnapshotDelete(d *pluginsdk.ResourceData, meta interface{}) e ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SnapshotID(d.Id()) + id, err := snapshots.ParseSnapshotID(d.Id()) if err != nil { return err } - if _, err = client.Delete(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.VolumeName, id.Name); err != nil { - return fmt.Errorf("deleting NetApp Snapshot %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + if _, err = client.Delete(ctx, *id); err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) } // The resource NetApp Snapshot depends on the resource NetApp Volume. @@ -159,33 +155,33 @@ func resourceNetAppSnapshotDelete(d *pluginsdk.ResourceData, meta interface{}) e // Then it tries to immediately delete NetApp Volume but it still throws error `Can not delete resource before nested resources are deleted.` // In this case we're going to re-check status code again. // For more details, see related Bug: https://github.com/Azure/azure-sdk-for-go/issues/11475 - log.Printf("[DEBUG] Waiting for NetApp Snapshot %q (Resource Group %q) to be deleted", id.Name, id.ResourceGroup) + log.Printf("[DEBUG] Waiting for %s to be deleted", id) stateConf := &pluginsdk.StateChangeConf{ ContinuousTargetOccurence: 5, Delay: 10 * time.Second, MinTimeout: 10 * time.Second, Pending: []string{"200", "202"}, Target: []string{"204", "404"}, - Refresh: netappSnapshotDeleteStateRefreshFunc(ctx, client, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.VolumeName, id.Name), + Refresh: netappSnapshotDeleteStateRefreshFunc(ctx, client, *id), Timeout: d.Timeout(pluginsdk.TimeoutDelete), } if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for NetApp Snapshot %q (Resource Group %q) to be deleted: %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("waiting for %s to be deleted: %+v", id, err) } return nil } -func netappSnapshotDeleteStateRefreshFunc(ctx context.Context, client *netapp.SnapshotsClient, resourceGroupName string, accountName string, poolName string, volumeName string, name string) pluginsdk.StateRefreshFunc { +func netappSnapshotDeleteStateRefreshFunc(ctx context.Context, client *snapshots.SnapshotsClient, id snapshots.SnapshotId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - res, err := client.Get(ctx, resourceGroupName, accountName, poolName, volumeName, name) + res, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(res.Response) { - return nil, "", fmt.Errorf("retrieving NetApp Snapshot %q (Resource Group %q): %s", name, resourceGroupName, err) + if !response.WasNotFound(res.HttpResponse) { + return nil, "", fmt.Errorf("retrieving %s: %s", id, err) } } - return res, strconv.Itoa(res.StatusCode), nil + return res, strconv.Itoa(res.HttpResponse.StatusCode), nil } } diff --git a/internal/services/netapp/netapp_snapshot_resource_test.go b/internal/services/netapp/netapp_snapshot_resource_test.go index cc5c38821e19..0321f8a671e5 100644 --- a/internal/services/netapp/netapp_snapshot_resource_test.go +++ b/internal/services/netapp/netapp_snapshot_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -64,17 +64,17 @@ func TestAccNetAppSnapshot_complete(t *testing.T) { } func (t NetAppSnapshotResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.SnapshotID(state.ID) + id, err := snapshots.ParseSnapshotID(state.ID) if err != nil { return nil, err } - resp, err := clients.NetApp.SnapshotClient.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.VolumeName, id.Name) + resp, err := clients.NetApp.SnapshotClient.Get(ctx, *id) if err != nil { - return nil, fmt.Errorf("reading Netapp Snapshot (%s): %+v", id.String(), err) + return nil, fmt.Errorf("reading %s: %+v", id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (r NetAppSnapshotResource) basic(data acceptance.TestData) string { diff --git a/internal/services/netapp/netapp_volume_data_source.go b/internal/services/netapp/netapp_volume_data_source.go index 3d435a927dbd..b6413b4da7d5 100644 --- a/internal/services/netapp/netapp_volume_data_source.go +++ b/internal/services/netapp/netapp_volume_data_source.go @@ -4,14 +4,14 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceNetAppVolume() *pluginsdk.Resource { @@ -123,10 +123,10 @@ func dataSourceNetAppVolumeRead(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewVolumeID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("pool_name").(string), d.Get("name").(string)) - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name) + id := volumes.NewVolumeID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("pool_name").(string), d.Get("name").(string)) + resp, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } return fmt.Errorf("retrieving %s: %+v", id, err) @@ -134,17 +134,18 @@ func dataSourceNetAppVolumeRead(d *pluginsdk.ResourceData, meta interface{}) err d.SetId(id.ID()) - d.Set("name", id.Name) - d.Set("pool_name", id.CapacityPoolName) - d.Set("account_name", id.NetAppAccountName) - d.Set("resource_group_name", id.ResourceGroup) + d.Set("name", id.VolumeName) + d.Set("pool_name", id.PoolName) + d.Set("account_name", id.AccountName) + d.Set("resource_group_name", id.ResourceGroupName) - d.Set("location", location.NormalizeNilable(resp.Location)) + if model := resp.Model; model != nil { + d.Set("location", location.NormalizeNilable(&model.Location)) - if props := resp.VolumeProperties; props != nil { + props := model.Properties d.Set("volume_path", props.CreationToken) d.Set("service_level", props.ServiceLevel) - d.Set("subnet_id", props.SubnetID) + d.Set("subnet_id", props.SubnetId) d.Set("network_features", props.NetworkFeatures) protocolTypes := make([]string, 0) @@ -155,9 +156,7 @@ func dataSourceNetAppVolumeRead(d *pluginsdk.ResourceData, meta interface{}) err d.Set("security_style", props.SecurityStyle) - if props.UsageThreshold != nil { - d.Set("storage_quota_in_gb", *props.UsageThreshold/1073741824) - } + d.Set("storage_quota_in_gb", props.UsageThreshold/1073741824) if err := d.Set("mount_ip_addresses", flattenNetAppVolumeMountIPAddresses(props.MountTargets)); err != nil { return fmt.Errorf("setting `mount_ip_addresses`: %+v", err) } diff --git a/internal/services/netapp/netapp_volume_resource.go b/internal/services/netapp/netapp_volume_resource.go index 7ddde3a07f49..1dbe6bec3111 100644 --- a/internal/services/netapp/netapp_volume_resource.go +++ b/internal/services/netapp/netapp_volume_resource.go @@ -8,16 +8,18 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - - "github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" netAppValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -38,7 +40,7 @@ func resourceNetAppVolume() *pluginsdk.Resource { Delete: pluginsdk.DefaultTimeout(60 * time.Minute), }, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.VolumeID(id) + _, err := volumes.ParseVolumeID(id) return err }), @@ -80,9 +82,9 @@ func resourceNetAppVolume() *pluginsdk.Resource { Required: true, ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ - string(netapp.ServiceLevelPremium), - string(netapp.ServiceLevelStandard), - string(netapp.ServiceLevelUltra), + string(volumes.ServiceLevelPremium), + string(volumes.ServiceLevelStandard), + string(volumes.ServiceLevelUltra), }, false), }, @@ -98,7 +100,7 @@ func resourceNetAppVolume() *pluginsdk.Resource { Optional: true, Computed: true, ForceNew: true, - ValidateFunc: netAppValidate.SnapshotID, + ValidateFunc: snapshots.ValidateSnapshotID, }, "network_features": { @@ -107,8 +109,8 @@ func resourceNetAppVolume() *pluginsdk.Resource { Computed: true, ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ - string(netapp.NetworkFeaturesBasic), - string(netapp.NetworkFeaturesStandard), + string(volumes.NetworkFeaturesBasic), + string(volumes.NetworkFeaturesStandard), }, false), }, @@ -206,7 +208,7 @@ func resourceNetAppVolume() *pluginsdk.Resource { }, }, - "tags": tags.Schema(), + "tags": commonschema.Tags(), "mount_ip_addresses": { Type: pluginsdk.TypeList, @@ -283,28 +285,30 @@ func resourceNetAppVolumeCreate(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewVolumeID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("pool_name").(string), d.Get("name").(string)) + id := volumes.NewVolumeID(subscriptionId, d.Get("resource_group_name").(string), d.Get("account_name").(string), d.Get("pool_name").(string), d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_netapp_volume", id.ID()) } } location := azure.NormalizeLocation(d.Get("location").(string)) volumePath := d.Get("volume_path").(string) - serviceLevel := d.Get("service_level").(string) + serviceLevel := volumes.ServiceLevel(d.Get("service_level").(string)) subnetID := d.Get("subnet_id").(string) - networkFeatures := d.Get("network_features").(string) - if networkFeatures == "" { - networkFeatures = string(netapp.NetworkFeaturesBasic) + var networkFeatures volumes.NetworkFeatures + networkFeaturesString := d.Get("network_features").(string) + if networkFeaturesString == "" { + networkFeatures = volumes.NetworkFeaturesBasic } + networkFeatures = volumes.NetworkFeatures(networkFeaturesString) protocols := d.Get("protocols").(*pluginsdk.Set).List() if len(protocols) == 0 { @@ -312,11 +316,11 @@ func resourceNetAppVolumeCreate(d *pluginsdk.ResourceData, meta interface{}) err } // Handling security style property - securityStyle := d.Get("security_style").(string) - if strings.EqualFold(securityStyle, "unix") && len(protocols) == 1 && strings.EqualFold(protocols[0].(string), "cifs") { + securityStyle := volumes.SecurityStyle(d.Get("security_style").(string)) + if strings.EqualFold(string(securityStyle), "unix") && len(protocols) == 1 && strings.EqualFold(protocols[0].(string), "cifs") { return fmt.Errorf("unix security style cannot be used in a CIFS enabled volume for %s", id) } - if strings.EqualFold(securityStyle, "ntfs") && len(protocols) == 1 && (strings.EqualFold(protocols[0].(string), "nfsv3") || strings.EqualFold(protocols[0].(string), "nfsv4.1")) { + if strings.EqualFold(string(securityStyle), "ntfs") && len(protocols) == 1 && (strings.EqualFold(protocols[0].(string), "nfsv3") || strings.EqualFold(protocols[0].(string), "nfsv4.1")) { return fmt.Errorf("ntfs security style cannot be used in a NFSv3/NFSv4.1 enabled volume for %s", id) } @@ -333,14 +337,20 @@ func resourceNetAppVolumeCreate(d *pluginsdk.ResourceData, meta interface{}) err authorizeReplication := false volumeType := "" - if dataProtectionReplication != nil && dataProtectionReplication.Replication != nil && strings.ToLower(string(dataProtectionReplication.Replication.EndpointType)) == "dst" { - authorizeReplication = true - volumeType = "DataProtection" + if dataProtectionReplication != nil && dataProtectionReplication.Replication != nil { + endpointType := "" + if dataProtectionReplication.Replication.EndpointType != nil { + endpointType = string(*dataProtectionReplication.Replication.EndpointType) + } + if strings.ToLower(endpointType) == "dst" { + authorizeReplication = true + volumeType = "DataProtection" + } } // Validating that snapshot policies are not being created in a data protection volume if dataProtectionSnapshotPolicy.Snapshot != nil && volumeType != "" { - return fmt.Errorf("snapshot policy cannot be enabled on a data protection volume, NetApp Volume %q (Resource Group %q)", id.Name, id.ResourceGroup) + return fmt.Errorf("snapshot policy cannot be enabled on a data protection volume, NetApp Volume %q (Resource Group %q)", id.VolumeName, id.ResourceGroupName) } snapshotDirectoryVisible := d.Get("snapshot_directory_visible").(bool) @@ -350,82 +360,70 @@ func resourceNetAppVolumeCreate(d *pluginsdk.ResourceData, meta interface{}) err snapshotID := "" if snapshotResourceID != "" { // Get snapshot ID GUID value - parsedSnapshotResourceID, err := parse.SnapshotID(snapshotResourceID) + parsedSnapshotResourceID, err := snapshots.ParseSnapshotID(snapshotResourceID) if err != nil { return fmt.Errorf("parsing snapshotResourceID %q: %+v", snapshotResourceID, err) } snapshotClient := meta.(*clients.Client).NetApp.SnapshotClient - snapshotResponse, err := snapshotClient.Get( - ctx, - parsedSnapshotResourceID.ResourceGroup, - parsedSnapshotResourceID.NetAppAccountName, - parsedSnapshotResourceID.CapacityPoolName, - parsedSnapshotResourceID.VolumeName, - parsedSnapshotResourceID.Name, - ) + _, err = snapshotClient.Get(ctx, *parsedSnapshotResourceID) if err != nil { - return fmt.Errorf("getting snapshot from NetApp Volume %q (Resource Group %q): %+v", parsedSnapshotResourceID.VolumeName, parsedSnapshotResourceID.ResourceGroup, err) + return fmt.Errorf("getting snapshot from %s: %+v", id, err) } - snapshotID = *snapshotResponse.SnapshotID + sourceVolumeId := volumes.NewVolumeID(parsedSnapshotResourceID.SubscriptionId, parsedSnapshotResourceID.ResourceGroupName, parsedSnapshotResourceID.AccountName, parsedSnapshotResourceID.PoolName, parsedSnapshotResourceID.VolumeName) // Validate if properties that cannot be changed matches (protocols, subnet_id, location, resource group, account_name, pool_name, service_level) - sourceVolume, err := client.Get( - ctx, - parsedSnapshotResourceID.ResourceGroup, - parsedSnapshotResourceID.NetAppAccountName, - parsedSnapshotResourceID.CapacityPoolName, - parsedSnapshotResourceID.VolumeName, - ) + sourceVolume, err := client.Get(ctx, sourceVolumeId) if err != nil { - return fmt.Errorf("getting source NetApp Volume (snapshot's parent resource) %q (Resource Group %q): %+v", parsedSnapshotResourceID.VolumeName, parsedSnapshotResourceID.ResourceGroup, err) + return fmt.Errorf("getting source NetApp Volume (snapshot's parent resource) %q (Resource Group %q): %+v", parsedSnapshotResourceID.VolumeName, parsedSnapshotResourceID.ResourceGroupName, err) } - parsedVolumeID, err := parse.VolumeID(*sourceVolume.ID) - if err != nil { - return fmt.Errorf("parsing Source Volume ID: %s", err) - } propertyMismatch := []string{} - if !ValidateSlicesEquality(*sourceVolume.ProtocolTypes, *utils.ExpandStringSlice(protocols), false) { - propertyMismatch = append(propertyMismatch, "protocols") - } - if !strings.EqualFold(*sourceVolume.SubnetID, subnetID) { - propertyMismatch = append(propertyMismatch, "subnet_id") - } - if !strings.EqualFold(*sourceVolume.Location, location) { - propertyMismatch = append(propertyMismatch, "location") - } - if !strings.EqualFold(string(sourceVolume.ServiceLevel), serviceLevel) { - propertyMismatch = append(propertyMismatch, "service_level") - } - if !strings.EqualFold(parsedVolumeID.ResourceGroup, id.ResourceGroup) { - propertyMismatch = append(propertyMismatch, "resource_group_name") - } - if !strings.EqualFold(parsedVolumeID.NetAppAccountName, id.NetAppAccountName) { - propertyMismatch = append(propertyMismatch, "account_name") - } - if !strings.EqualFold(parsedVolumeID.CapacityPoolName, id.CapacityPoolName) { - propertyMismatch = append(propertyMismatch, "pool_name") - } - if len(propertyMismatch) > 0 { - return fmt.Errorf("following NetApp Volume properties on new Volume from Snapshot does not match Snapshot's source %s: %s", id, strings.Join(propertyMismatch, ", ")) + if model := sourceVolume.Model; model != nil { + props := model.Properties + if !ValidateSlicesEquality(*props.ProtocolTypes, *utils.ExpandStringSlice(protocols), false) { + propertyMismatch = append(propertyMismatch, "protocols") + } + if !strings.EqualFold(props.SubnetId, subnetID) { + propertyMismatch = append(propertyMismatch, "subnet_id") + } + if !strings.EqualFold(model.Location, location) { + propertyMismatch = append(propertyMismatch, "location") + } + if volumeServiceLevel := props.ServiceLevel; volumeServiceLevel != nil { + if !strings.EqualFold(string(*props.ServiceLevel), string(serviceLevel)) { + propertyMismatch = append(propertyMismatch, "service_level") + } + } + if !strings.EqualFold(sourceVolumeId.ResourceGroupName, id.ResourceGroupName) { + propertyMismatch = append(propertyMismatch, "resource_group_name") + } + if !strings.EqualFold(sourceVolumeId.AccountName, id.AccountName) { + propertyMismatch = append(propertyMismatch, "account_name") + } + if !strings.EqualFold(sourceVolumeId.PoolName, id.PoolName) { + propertyMismatch = append(propertyMismatch, "pool_name") + } + if len(propertyMismatch) > 0 { + return fmt.Errorf("following NetApp Volume properties on new Volume from Snapshot does not match Snapshot's source %s: %s", id, strings.Join(propertyMismatch, ", ")) + } } } - parameters := netapp.Volume{ - Location: utils.String(location), - VolumeProperties: &netapp.VolumeProperties{ - CreationToken: utils.String(volumePath), - ServiceLevel: netapp.ServiceLevel(serviceLevel), - SubnetID: utils.String(subnetID), - NetworkFeatures: netapp.NetworkFeatures(networkFeatures), + parameters := volumes.Volume{ + Location: location, + Properties: volumes.VolumeProperties{ + CreationToken: volumePath, + ServiceLevel: &serviceLevel, + SubnetId: subnetID, + NetworkFeatures: &networkFeatures, ProtocolTypes: utils.ExpandStringSlice(protocols), - SecurityStyle: netapp.SecurityStyle(securityStyle), - UsageThreshold: utils.Int64(storageQuotaInGB), + SecurityStyle: &securityStyle, + UsageThreshold: storageQuotaInGB, ExportPolicy: exportPolicyRule, VolumeType: utils.String(volumeType), - SnapshotID: utils.String(snapshotID), - DataProtection: &netapp.VolumePropertiesDataProtection{ + SnapshotId: utils.String(snapshotID), + DataProtection: &volumes.VolumePropertiesDataProtection{ Replication: dataProtectionReplication.Replication, Snapshot: dataProtectionSnapshotPolicy.Snapshot, }, @@ -435,16 +433,12 @@ func resourceNetAppVolumeCreate(d *pluginsdk.ResourceData, meta interface{}) err } if throughputMibps, ok := d.GetOk("throughput_in_mibps"); ok { - parameters.VolumeProperties.ThroughputMibps = utils.Float(throughputMibps.(float64)) + parameters.Properties.ThroughputMibps = utils.Float(throughputMibps.(float64)) } - future, err := client.CreateOrUpdate(ctx, parameters, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name) - if err != nil { + if err := client.CreateOrUpdateThenPoll(ctx, id, parameters); err != nil { return fmt.Errorf("creating %s: %+v", id, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the creation of %s: %+v", id, err) - } // Waiting for volume be completely provisioned if err := waitForVolumeCreateOrUpdate(ctx, client, id); err != nil { @@ -453,32 +447,22 @@ func resourceNetAppVolumeCreate(d *pluginsdk.ResourceData, meta interface{}) err // If this is a data replication secondary volume, authorize replication on primary volume if authorizeReplication { - replVolID, err := parse.VolumeID(*dataProtectionReplication.Replication.RemoteVolumeResourceID) + replicationClient := meta.(*clients.Client).NetApp.VolumeReplicationClient + replVolID, err := volumesreplication.ParseVolumeID(dataProtectionReplication.Replication.RemoteVolumeResourceId) if err != nil { return err } - future, err := client.AuthorizeReplication( - ctx, - replVolID.ResourceGroup, - replVolID.NetAppAccountName, - replVolID.CapacityPoolName, - replVolID.Name, - netapp.AuthorizeRequest{ - RemoteVolumeResourceID: utils.String(id.ID()), - }, - ) - if err != nil { + if err = replicationClient.VolumesAuthorizeReplicationThenPoll(ctx, *replVolID, volumesreplication.AuthorizeRequest{ + RemoteVolumeResourceId: utils.String(id.ID()), + }, + ); err != nil { return fmt.Errorf("cannot authorize volume replication: %v", err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("cannot get authorize volume replication future response: %v", err) - } - // Wait for volume replication authorization to complete - log.Printf("[DEBUG] Waiting for replication authorization on NetApp Volume Provisioning Service %q (Resource Group %q) to complete", id.Name, id.ResourceGroup) - if err := waitForReplAuthorization(ctx, client, id); err != nil { + log.Printf("[DEBUG] Waiting for replication authorization on %s to complete", id) + if err := waitForReplAuthorization(ctx, replicationClient, *replVolID); err != nil { return err } } @@ -493,27 +477,27 @@ func resourceNetAppVolumeUpdate(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.VolumeID(d.Id()) + id, err := volumes.ParseVolumeID(d.Id()) if err != nil { return err } shouldUpdate := false - update := netapp.VolumePatch{ - VolumePatchProperties: &netapp.VolumePatchProperties{}, + update := volumes.VolumePatch{ + Properties: &volumes.VolumePatchProperties{}, } if d.HasChange("storage_quota_in_gb") { shouldUpdate = true storageQuotaInBytes := int64(d.Get("storage_quota_in_gb").(int) * 1073741824) - update.VolumePatchProperties.UsageThreshold = utils.Int64(storageQuotaInBytes) + update.Properties.UsageThreshold = utils.Int64(storageQuotaInBytes) } if d.HasChange("export_policy_rule") { shouldUpdate = true exportPolicyRuleRaw := d.Get("export_policy_rule").([]interface{}) exportPolicyRule := expandNetAppVolumeExportPolicyRulePatch(exportPolicyRuleRaw) - update.VolumePatchProperties.ExportPolicy = exportPolicyRule + update.Properties.ExportPolicy = exportPolicyRule } if d.HasChange("data_protection_snapshot_policy") { @@ -521,20 +505,20 @@ func resourceNetAppVolumeUpdate(d *pluginsdk.ResourceData, meta interface{}) err dataProtectionReplicationRaw := d.Get("data_protection_replication").([]interface{}) dataProtectionReplication := expandNetAppVolumeDataProtectionReplication(dataProtectionReplicationRaw) - if dataProtectionReplication != nil && dataProtectionReplication.Replication != nil && strings.ToLower(string(dataProtectionReplication.Replication.EndpointType)) == "dst" { - return fmt.Errorf("snapshot policy cannot be enabled on a data protection volume, NetApp Volume %q (Resource Group %q)", id.Name, id.ResourceGroup) + if dataProtectionReplication != nil && dataProtectionReplication.Replication != nil && dataProtectionReplication.Replication.EndpointType != nil && strings.ToLower(string(*dataProtectionReplication.Replication.EndpointType)) == "dst" { + return fmt.Errorf("snapshot policy cannot be enabled on a data protection volume, %s", id) } shouldUpdate = true dataProtectionSnapshotPolicyRaw := d.Get("data_protection_snapshot_policy").([]interface{}) dataProtectionSnapshotPolicy := expandNetAppVolumeDataProtectionSnapshotPolicyPatch(dataProtectionSnapshotPolicyRaw) - update.VolumePatchProperties.DataProtection = dataProtectionSnapshotPolicy + update.Properties.DataProtection = dataProtectionSnapshotPolicy } if d.HasChange("throughput_in_mibps") { shouldUpdate = true throughputMibps := d.Get("throughput_in_mibps") - update.VolumePatchProperties.ThroughputMibps = utils.Float(throughputMibps.(float64)) + update.Properties.ThroughputMibps = utils.Float(throughputMibps.(float64)) } if d.HasChange("tags") { @@ -544,12 +528,8 @@ func resourceNetAppVolumeUpdate(d *pluginsdk.ResourceData, meta interface{}) err } if shouldUpdate { - future, err := client.Update(ctx, update, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name) - if err != nil { - return fmt.Errorf("updating Volume %q: %+v", id.Name, err) - } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the update of %s: %+v", id, err) + if err = client.UpdateThenPoll(ctx, *id, update); err != nil { + return fmt.Errorf("updating %s: %+v", id, err) } // Wait for volume to complete update @@ -566,14 +546,14 @@ func resourceNetAppVolumeRead(d *pluginsdk.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.VolumeID(d.Id()) + id, err := volumes.ParseVolumeID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[INFO] %s was not found - removing from state", *id) d.SetId("") return nil @@ -581,25 +561,24 @@ func resourceNetAppVolumeRead(d *pluginsdk.ResourceData, meta interface{}) error return fmt.Errorf("reading %s: %+v", *id, err) } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("account_name", id.NetAppAccountName) - d.Set("pool_name", id.CapacityPoolName) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - if props := resp.VolumeProperties; props != nil { + d.Set("name", id.VolumeName) + d.Set("resource_group_name", id.ResourceGroupName) + d.Set("account_name", id.AccountName) + d.Set("pool_name", id.PoolName) + + if model := resp.Model; model != nil { + d.Set("location", azure.NormalizeLocation(model.Location)) + + props := model.Properties d.Set("volume_path", props.CreationToken) d.Set("service_level", props.ServiceLevel) - d.Set("subnet_id", props.SubnetID) + d.Set("subnet_id", props.SubnetId) d.Set("network_features", props.NetworkFeatures) d.Set("protocols", props.ProtocolTypes) d.Set("security_style", props.SecurityStyle) d.Set("snapshot_directory_visible", props.SnapshotDirectoryVisible) d.Set("throughput_in_mibps", props.ThroughputMibps) - if props.UsageThreshold != nil { - d.Set("storage_quota_in_gb", *props.UsageThreshold/1073741824) - } + d.Set("storage_quota_in_gb", props.UsageThreshold/1073741824) if err := d.Set("export_policy_rule", flattenNetAppVolumeExportPolicyRule(props.ExportPolicy)); err != nil { return fmt.Errorf("setting `export_policy_rule`: %+v", err) } @@ -612,9 +591,10 @@ func resourceNetAppVolumeRead(d *pluginsdk.ResourceData, meta interface{}) error if err := d.Set("data_protection_snapshot_policy", flattenNetAppVolumeDataProtectionSnapshotPolicy(props.DataProtection)); err != nil { return fmt.Errorf("setting `data_protection_snapshot_policy`: %+v", err) } - } - return tags.FlattenAndSet(d, resp.Tags) + return tags.FlattenAndSet(d, model.Tags) + } + return nil } func resourceNetAppVolumeDelete(d *pluginsdk.ResourceData, meta interface{}) error { @@ -622,7 +602,7 @@ func resourceNetAppVolumeDelete(d *pluginsdk.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.VolumeID(d.Id()) + id, err := volumes.ParseVolumeID(d.Id()) if err != nil { return err } @@ -631,82 +611,70 @@ func resourceNetAppVolumeDelete(d *pluginsdk.ResourceData, meta interface{}) err dataProtectionReplicationRaw := d.Get("data_protection_replication").([]interface{}) dataProtectionReplication := expandNetAppVolumeDataProtectionReplication(dataProtectionReplicationRaw) - if replicaVolumeId := id; dataProtectionReplication != nil && dataProtectionReplication.Replication != nil { - if dataProtectionReplication.Replication.RemoteVolumeResourceID == nil { - return fmt.Errorf("remote volume id was nil") + if dataProtectionReplication != nil && dataProtectionReplication.Replication != nil { + replicaVolumeId, err := volumesreplication.ParseVolumeID(id.ID()) + if err != nil { + return err } - - if strings.ToLower(string(dataProtectionReplication.Replication.EndpointType)) != "dst" { + if dataProtectionReplication.Replication.EndpointType != nil && strings.ToLower(string(*dataProtectionReplication.Replication.EndpointType)) != "dst" { // This is the case where primary volume started the deletion, in this case, to be consistent we will remove replication from secondary - replicaVolumeId, err = parse.VolumeID(*dataProtectionReplication.Replication.RemoteVolumeResourceID) + replicaVolumeId, err = volumesreplication.ParseVolumeID(dataProtectionReplication.Replication.RemoteVolumeResourceId) if err != nil { return err } } + replicationClient := meta.(*clients.Client).NetApp.VolumeReplicationClient // Checking replication status before deletion, it need to be broken before proceeding with deletion - if res, err := client.ReplicationStatusMethod(ctx, replicaVolumeId.ResourceGroup, replicaVolumeId.NetAppAccountName, replicaVolumeId.CapacityPoolName, replicaVolumeId.Name); err == nil { + if res, err := replicationClient.VolumesReplicationStatus(ctx, *replicaVolumeId); err == nil { // Wait for replication state = "mirrored" - if strings.ToLower(string(res.MirrorState)) == "uninitialized" { - if err := waitForReplMirrorState(ctx, client, *replicaVolumeId, "mirrored"); err != nil { - return fmt.Errorf("waiting for replica %s to become 'mirrored': %+v", *replicaVolumeId, err) + if model := res.Model; model != nil { + if model.MirrorState != nil && strings.ToLower(string(*model.MirrorState)) == "uninitialized" { + if err := waitForReplMirrorState(ctx, replicationClient, *replicaVolumeId, "mirrored"); err != nil { + return fmt.Errorf("waiting for replica %s to become 'mirrored': %+v", *replicaVolumeId, err) + } } } // Breaking replication - _, err = client.BreakReplication(ctx, - replicaVolumeId.ResourceGroup, - replicaVolumeId.NetAppAccountName, - replicaVolumeId.CapacityPoolName, - replicaVolumeId.Name, - &netapp.BreakReplicationRequest{ - ForceBreakReplication: utils.Bool(true), - }) - - if err != nil { + if err = replicationClient.VolumesBreakReplicationThenPoll(ctx, *replicaVolumeId, volumesreplication.BreakReplicationRequest{ + ForceBreakReplication: utils.Bool(true), + }); err != nil { return fmt.Errorf("breaking replication for %s: %+v", *replicaVolumeId, err) } // Waiting for replication be in broken state log.Printf("[DEBUG] Waiting for the replication of %s to be in broken state", *replicaVolumeId) - if err := waitForReplMirrorState(ctx, client, *replicaVolumeId, "broken"); err != nil { + if err := waitForReplMirrorState(ctx, replicationClient, *replicaVolumeId, "broken"); err != nil { return fmt.Errorf("waiting for the breaking of replication for %s: %+v", *replicaVolumeId, err) } } // Deleting replication and waiting for it to fully complete the operation - future, err := client.DeleteReplication(ctx, replicaVolumeId.ResourceGroup, replicaVolumeId.NetAppAccountName, replicaVolumeId.CapacityPoolName, replicaVolumeId.Name) - if err != nil { + if err = replicationClient.VolumesDeleteReplicationThenPoll(ctx, *replicaVolumeId); err != nil { return fmt.Errorf("deleting replicate %s: %+v", *replicaVolumeId, err) } - log.Printf("[DEBUG] Waiting for the replica of %s to be deleted", replicaVolumeId) - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for the replica %s to be deleted: %+v", *replicaVolumeId, err) - } - if err := waitForReplicationDeletion(ctx, client, *replicaVolumeId); err != nil { + if err := waitForReplicationDeletion(ctx, replicationClient, *replicaVolumeId); err != nil { return fmt.Errorf("waiting for the replica %s to be deleted: %+v", *replicaVolumeId, err) } } // Deleting volume and waiting for it fo fully complete the operation - future, err := client.Delete(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name, utils.Bool(true)) - if err != nil { + if err = client.DeleteThenPoll(ctx, *id, volumes.DeleteOperationOptions{ + ForceDelete: utils.Bool(true), + }); err != nil { return fmt.Errorf("deleting %s: %+v", *id, err) } - log.Printf("[DEBUG] Waiting for %s to be deleted", *id) - if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for deletion of %q: %+v", id, err) - } - if err := waitForVolumeDeletion(ctx, client, *id); err != nil { + if err = waitForVolumeDeletion(ctx, client, *id); err != nil { return fmt.Errorf("waiting for deletion of %s: %+v", *id, err) } return nil } -func waitForVolumeCreateOrUpdate(ctx context.Context, client *netapp.VolumesClient, id parse.VolumeId) error { +func waitForVolumeCreateOrUpdate(ctx context.Context, client *volumes.VolumesClient, id volumes.VolumeId) error { deadline, ok := ctx.Deadline() if !ok { return fmt.Errorf("context had no deadline") @@ -728,7 +696,7 @@ func waitForVolumeCreateOrUpdate(ctx context.Context, client *netapp.VolumesClie return nil } -func waitForReplAuthorization(ctx context.Context, client *netapp.VolumesClient, id parse.VolumeId) error { +func waitForReplAuthorization(ctx context.Context, client *volumesreplication.VolumesReplicationClient, id volumesreplication.VolumeId) error { deadline, ok := ctx.Deadline() if !ok { return fmt.Errorf("context had no deadline") @@ -744,13 +712,13 @@ func waitForReplAuthorization(ctx context.Context, client *netapp.VolumesClient, } if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for replication authorization NetApp Volume Provisioning Service %q (Resource Group %q) to complete: %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("waiting for replication authorization %s to complete: %+v", id, err) } return nil } -func waitForReplMirrorState(ctx context.Context, client *netapp.VolumesClient, id parse.VolumeId, desiredState string) error { +func waitForReplMirrorState(ctx context.Context, client *volumesreplication.VolumesReplicationClient, id volumesreplication.VolumeId, desiredState string) error { deadline, ok := ctx.Deadline() if !ok { return fmt.Errorf("context had no deadline") @@ -772,7 +740,7 @@ func waitForReplMirrorState(ctx context.Context, client *netapp.VolumesClient, i return nil } -func waitForReplicationDeletion(ctx context.Context, client *netapp.VolumesClient, id parse.VolumeId) error { +func waitForReplicationDeletion(ctx context.Context, client *volumesreplication.VolumesReplicationClient, id volumesreplication.VolumeId) error { deadline, ok := ctx.Deadline() if !ok { return fmt.Errorf("context had no deadline") @@ -795,7 +763,7 @@ func waitForReplicationDeletion(ctx context.Context, client *netapp.VolumesClien return nil } -func waitForVolumeDeletion(ctx context.Context, client *netapp.VolumesClient, id parse.VolumeId) error { +func waitForVolumeDeletion(ctx context.Context, client *volumes.VolumesClient, id volumes.VolumeId) error { deadline, ok := ctx.Deadline() if !ok { return fmt.Errorf("context had no deadline") @@ -817,40 +785,40 @@ func waitForVolumeDeletion(ctx context.Context, client *netapp.VolumesClient, id return nil } -func netappVolumeStateRefreshFunc(ctx context.Context, client *netapp.VolumesClient, id parse.VolumeId) pluginsdk.StateRefreshFunc { +func netappVolumeStateRefreshFunc(ctx context.Context, client *volumes.VolumesClient, id volumes.VolumeId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - res, err := client.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name) + res, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(res.Response) { - return nil, "", fmt.Errorf("retrieving NetApp Volume %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err) + if !response.WasNotFound(res.HttpResponse) { + return nil, "", fmt.Errorf("retrieving %s: %s", id, err) } } - return res, strconv.Itoa(res.StatusCode), nil + return res, strconv.Itoa(res.HttpResponse.StatusCode), nil } } -func netappVolumeReplicationMirrorStateRefreshFunc(ctx context.Context, client *netapp.VolumesClient, id parse.VolumeId, desiredState string) pluginsdk.StateRefreshFunc { +func netappVolumeReplicationMirrorStateRefreshFunc(ctx context.Context, client *volumesreplication.VolumesReplicationClient, id volumesreplication.VolumeId, desiredState string) pluginsdk.StateRefreshFunc { validStates := []string{"mirrored", "broken", "uninitialized"} return func() (interface{}, string, error) { // Possible Mirror States to be used as desiredStates: // mirrored, broken or uninitialized if !utils.SliceContainsValue(validStates, strings.ToLower(desiredState)) { - return nil, "", fmt.Errorf("Invalid desired mirror state was passed to check mirror replication state (%s), possible values: (%+v)", desiredState, netapp.PossibleMirrorStateValues()) + return nil, "", fmt.Errorf("Invalid desired mirror state was passed to check mirror replication state (%s), possible values: (%+v)", desiredState, volumesreplication.PossibleValuesForMirrorState()) } - res, err := client.ReplicationStatusMethod(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name) + res, err := client.VolumesReplicationStatus(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(res.Response) { - return nil, "", fmt.Errorf("retrieving replication status information from NetApp Volume %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err) + if !response.WasNotFound(res.HttpResponse) { + return nil, "", fmt.Errorf("retrieving replication status information from %s: %s", id, err) } } // TODO: fix this refresh function to use strings instead of fake status codes // Setting 200 as default response response := 200 - if strings.EqualFold(string(res.MirrorState), desiredState) { + if res.Model != nil && res.Model.MirrorState != nil && strings.EqualFold(string(*res.Model.MirrorState), desiredState) { // return 204 if state matches desired state response = 204 } @@ -859,28 +827,30 @@ func netappVolumeReplicationMirrorStateRefreshFunc(ctx context.Context, client * } } -func netappVolumeReplicationStateRefreshFunc(ctx context.Context, client *netapp.VolumesClient, id parse.VolumeId) pluginsdk.StateRefreshFunc { +func netappVolumeReplicationStateRefreshFunc(ctx context.Context, client *volumesreplication.VolumesReplicationClient, id volumesreplication.VolumeId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - res, err := client.ReplicationStatusMethod(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name) + res, err := client.VolumesReplicationStatus(ctx, id) if err != nil { - if res.StatusCode == 400 && (strings.Contains(strings.ToLower(err.Error()), "deleting") || strings.Contains(strings.ToLower(err.Error()), "volume replication missing or deleted")) { - // This error can be ignored until a bug is fixed on RP side that it is returning 400 while the replication is in "Deleting" process - // TODO: remove this workaround when above bug is fixed - } else if !utils.ResponseWasNotFound(res.Response) { - return nil, "", fmt.Errorf("retrieving replication status from NetApp Volume %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err) + if httpResponse := res.HttpResponse; httpResponse != nil { + if httpResponse.StatusCode == 400 && (strings.Contains(strings.ToLower(err.Error()), "deleting") || strings.Contains(strings.ToLower(err.Error()), "volume replication missing or deleted")) { + // This error can be ignored until a bug is fixed on RP side that it is returning 400 while the replication is in "Deleting" process + // TODO: remove this workaround when above bug is fixed + } else if !response.WasNotFound(httpResponse) { + return nil, "", fmt.Errorf("retrieving replication status from %s: %s", id, err) + } } } - return res, strconv.Itoa(res.StatusCode), nil + return res, strconv.Itoa(res.HttpResponse.StatusCode), nil } } -func expandNetAppVolumeExportPolicyRule(input []interface{}) *netapp.VolumePropertiesExportPolicy { - results := make([]netapp.ExportPolicyRule, 0) +func expandNetAppVolumeExportPolicyRule(input []interface{}) *volumes.VolumePropertiesExportPolicy { + results := make([]volumes.ExportPolicyRule, 0) for _, item := range input { if item != nil { v := item.(map[string]interface{}) - ruleIndex := int32(v["rule_index"].(int)) + ruleIndex := int64(v["rule_index"].(int)) allowedClients := strings.Join(*utils.ExpandStringSlice(v["allowed_clients"].(*pluginsdk.Set).List()), ",") cifsEnabled := false @@ -909,12 +879,12 @@ func expandNetAppVolumeExportPolicyRule(input []interface{}) *netapp.VolumePrope unixReadWrite := v["unix_read_write"].(bool) rootAccessEnabled := v["root_access_enabled"].(bool) - result := netapp.ExportPolicyRule{ + result := volumes.ExportPolicyRule{ AllowedClients: utils.String(allowedClients), Cifs: utils.Bool(cifsEnabled), Nfsv3: utils.Bool(nfsv3Enabled), Nfsv41: utils.Bool(nfsv41Enabled), - RuleIndex: utils.Int32(ruleIndex), + RuleIndex: utils.Int64(ruleIndex), UnixReadOnly: utils.Bool(unixReadOnly), UnixReadWrite: utils.Bool(unixReadWrite), HasRootAccess: utils.Bool(rootAccessEnabled), @@ -924,17 +894,17 @@ func expandNetAppVolumeExportPolicyRule(input []interface{}) *netapp.VolumePrope } } - return &netapp.VolumePropertiesExportPolicy{ + return &volumes.VolumePropertiesExportPolicy{ Rules: &results, } } -func expandNetAppVolumeExportPolicyRulePatch(input []interface{}) *netapp.VolumePatchPropertiesExportPolicy { - results := make([]netapp.ExportPolicyRule, 0) +func expandNetAppVolumeExportPolicyRulePatch(input []interface{}) *volumes.VolumePatchPropertiesExportPolicy { + results := make([]volumes.ExportPolicyRule, 0) for _, item := range input { if item != nil { v := item.(map[string]interface{}) - ruleIndex := int32(v["rule_index"].(int)) + ruleIndex := int64(v["rule_index"].(int)) allowedClients := strings.Join(*utils.ExpandStringSlice(v["allowed_clients"].(*pluginsdk.Set).List()), ",") cifsEnabled := false @@ -963,12 +933,12 @@ func expandNetAppVolumeExportPolicyRulePatch(input []interface{}) *netapp.Volume unixReadWrite := v["unix_read_write"].(bool) rootAccessEnabled := v["root_access_enabled"].(bool) - result := netapp.ExportPolicyRule{ + result := volumes.ExportPolicyRule{ AllowedClients: utils.String(allowedClients), Cifs: utils.Bool(cifsEnabled), Nfsv3: utils.Bool(nfsv3Enabled), Nfsv41: utils.Bool(nfsv41Enabled), - RuleIndex: utils.Int32(ruleIndex), + RuleIndex: utils.Int64(ruleIndex), UnixReadOnly: utils.Bool(unixReadOnly), UnixReadWrite: utils.Bool(unixReadWrite), HasRootAccess: utils.Bool(rootAccessEnabled), @@ -978,82 +948,84 @@ func expandNetAppVolumeExportPolicyRulePatch(input []interface{}) *netapp.Volume } } - return &netapp.VolumePatchPropertiesExportPolicy{ + return &volumes.VolumePatchPropertiesExportPolicy{ Rules: &results, } } -func expandNetAppVolumeDataProtectionReplication(input []interface{}) *netapp.VolumePropertiesDataProtection { +func expandNetAppVolumeDataProtectionReplication(input []interface{}) *volumes.VolumePropertiesDataProtection { if len(input) == 0 || input[0] == nil { - return &netapp.VolumePropertiesDataProtection{} + return &volumes.VolumePropertiesDataProtection{} } - replicationObject := netapp.ReplicationObject{} + replicationObject := volumes.ReplicationObject{} replicationRaw := input[0].(map[string]interface{}) if v, ok := replicationRaw["endpoint_type"]; ok { - replicationObject.EndpointType = netapp.EndpointType(v.(string)) + endpointType := volumes.EndpointType(v.(string)) + replicationObject.EndpointType = &endpointType } if v, ok := replicationRaw["remote_volume_location"]; ok { replicationObject.RemoteVolumeRegion = utils.String(v.(string)) } if v, ok := replicationRaw["remote_volume_resource_id"]; ok { - replicationObject.RemoteVolumeResourceID = utils.String(v.(string)) + replicationObject.RemoteVolumeResourceId = v.(string) } if v, ok := replicationRaw["replication_frequency"]; ok { - replicationObject.ReplicationSchedule = netapp.ReplicationSchedule(translateTFSchedule(v.(string))) + replicationSchedule := volumes.ReplicationSchedule(translateTFSchedule(v.(string))) + replicationObject.ReplicationSchedule = &replicationSchedule } - return &netapp.VolumePropertiesDataProtection{ + return &volumes.VolumePropertiesDataProtection{ Replication: &replicationObject, } } -func expandNetAppVolumeDataProtectionSnapshotPolicy(input []interface{}) *netapp.VolumePropertiesDataProtection { +func expandNetAppVolumeDataProtectionSnapshotPolicy(input []interface{}) *volumes.VolumePropertiesDataProtection { if len(input) == 0 || input[0] == nil { - return &netapp.VolumePropertiesDataProtection{} + return &volumes.VolumePropertiesDataProtection{} } - snapshotObject := netapp.VolumeSnapshotProperties{} + snapshotObject := volumes.VolumeSnapshotProperties{} snapshotRaw := input[0].(map[string]interface{}) if v, ok := snapshotRaw["snapshot_policy_id"]; ok { - snapshotObject.SnapshotPolicyID = utils.String(v.(string)) + snapshotObject.SnapshotPolicyId = utils.String(v.(string)) } - return &netapp.VolumePropertiesDataProtection{ + return &volumes.VolumePropertiesDataProtection{ Snapshot: &snapshotObject, } } -func expandNetAppVolumeDataProtectionSnapshotPolicyPatch(input []interface{}) *netapp.VolumePatchPropertiesDataProtection { +func expandNetAppVolumeDataProtectionSnapshotPolicyPatch(input []interface{}) *volumes.VolumePatchPropertiesDataProtection { if len(input) == 0 || input[0] == nil { - return &netapp.VolumePatchPropertiesDataProtection{} + return &volumes.VolumePatchPropertiesDataProtection{} } - snapshotObject := netapp.VolumeSnapshotProperties{} + snapshotObject := volumes.VolumeSnapshotProperties{} snapshotRaw := input[0].(map[string]interface{}) if v, ok := snapshotRaw["snapshot_policy_id"]; ok { - snapshotObject.SnapshotPolicyID = utils.String(v.(string)) + snapshotObject.SnapshotPolicyId = utils.String(v.(string)) } - return &netapp.VolumePatchPropertiesDataProtection{ + return &volumes.VolumePatchPropertiesDataProtection{ Snapshot: &snapshotObject, } } -func flattenNetAppVolumeExportPolicyRule(input *netapp.VolumePropertiesExportPolicy) []interface{} { +func flattenNetAppVolumeExportPolicyRule(input *volumes.VolumePropertiesExportPolicy) []interface{} { results := make([]interface{}, 0) if input == nil || input.Rules == nil { return results } for _, item := range *input.Rules { - ruleIndex := int32(0) + ruleIndex := int64(0) if v := item.RuleIndex; v != nil { ruleIndex = *v } @@ -1105,48 +1077,53 @@ func flattenNetAppVolumeExportPolicyRule(input *netapp.VolumePropertiesExportPol return results } -func flattenNetAppVolumeMountIPAddresses(input *[]netapp.MountTargetProperties) []interface{} { +func flattenNetAppVolumeMountIPAddresses(input *[]volumes.MountTargetProperties) []interface{} { results := make([]interface{}, 0) if input == nil { return results } for _, item := range *input { - if item.IPAddress != nil { - results = append(results, item.IPAddress) + if item.IpAddress != nil { + results = append(results, item.IpAddress) } } return results } -func flattenNetAppVolumeDataProtectionReplication(input *netapp.VolumePropertiesDataProtection) []interface{} { - if input == nil || input.Replication == nil { +func flattenNetAppVolumeDataProtectionReplication(input *volumes.VolumePropertiesDataProtection) []interface{} { + if input == nil || input.Replication == nil || input.Replication.EndpointType == nil { return []interface{}{} } - if strings.ToLower(string(input.Replication.EndpointType)) == "" || strings.ToLower(string(input.Replication.EndpointType)) != "dst" { + if strings.ToLower(string(*input.Replication.EndpointType)) == "" || strings.ToLower(string(*input.Replication.EndpointType)) != "dst" { return []interface{}{} } + replicationFrequency := "" + if input.Replication.ReplicationSchedule != nil { + replicationFrequency = translateSDKSchedule(strings.ToLower(string(*input.Replication.ReplicationSchedule))) + } + return []interface{}{ map[string]interface{}{ - "endpoint_type": strings.ToLower(string(input.Replication.EndpointType)), + "endpoint_type": strings.ToLower(string(*input.Replication.EndpointType)), "remote_volume_location": location.NormalizeNilable(input.Replication.RemoteVolumeRegion), - "remote_volume_resource_id": input.Replication.RemoteVolumeResourceID, - "replication_frequency": translateSDKSchedule(strings.ToLower(string(input.Replication.ReplicationSchedule))), + "remote_volume_resource_id": input.Replication.RemoteVolumeResourceId, + "replication_frequency": replicationFrequency, }, } } -func flattenNetAppVolumeDataProtectionSnapshotPolicy(input *netapp.VolumePropertiesDataProtection) []interface{} { +func flattenNetAppVolumeDataProtectionSnapshotPolicy(input *volumes.VolumePropertiesDataProtection) []interface{} { if input == nil || input.Snapshot == nil { return []interface{}{} } return []interface{}{ map[string]interface{}{ - "snapshot_policy_id": input.Snapshot.SnapshotPolicyID, + "snapshot_policy_id": input.Snapshot.SnapshotPolicyId, }, } } diff --git a/internal/services/netapp/netapp_volume_resource_test.go b/internal/services/netapp/netapp_volume_resource_test.go index 336a36cba8ba..e6c971498a91 100644 --- a/internal/services/netapp/netapp_volume_resource_test.go +++ b/internal/services/netapp/netapp_volume_resource_test.go @@ -6,11 +6,10 @@ import ( "os" "testing" - "github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp" + "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/netapp/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -41,7 +40,7 @@ func TestAccNetAppVolume_nfsv41(t *testing.T) { Config: r.nfsv41(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), - check.That(data.ResourceName).Key("network_features").HasValue(string(netapp.NetworkFeaturesBasic)), + check.That(data.ResourceName).Key("network_features").HasValue(string(volumes.NetworkFeaturesBasic)), ), }, data.ImportStep(), @@ -57,7 +56,7 @@ func TestAccNetAppVolume_standardNetworkFeature(t *testing.T) { Config: r.standardNetworkFeature(data), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), - check.That(data.ResourceName).Key("network_features").HasValue(string(netapp.NetworkFeaturesStandard)), + check.That(data.ResourceName).Key("network_features").HasValue(string(volumes.NetworkFeaturesStandard)), ), }, data.ImportStep(), @@ -157,7 +156,7 @@ func TestAccNetAppVolume_complete(t *testing.T) { check.That(data.ResourceName).Key("service_level").HasValue("Standard"), check.That(data.ResourceName).Key("storage_quota_in_gb").HasValue("101"), check.That(data.ResourceName).Key("export_policy_rule.#").HasValue("3"), - check.That(data.ResourceName).Key("tags.%").HasValue("2"), + check.That(data.ResourceName).Key("tags.%").HasValue("3"), check.That(data.ResourceName).Key("tags.FoO").HasValue("BaR"), check.That(data.ResourceName).Key("mount_ip_addresses.#").HasValue("1"), ), @@ -177,8 +176,8 @@ func TestAccNetAppVolume_update(t *testing.T) { check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("storage_quota_in_gb").HasValue("100"), check.That(data.ResourceName).Key("export_policy_rule.#").HasValue("3"), - check.That(data.ResourceName).Key("tags.%").HasValue("2"), - check.That(data.ResourceName).Key("throughput_in_mibps").HasValue("1.6"), + check.That(data.ResourceName).Key("tags.%").HasValue("3"), + check.That(data.ResourceName).Key("throughput_in_mibps").HasValue("1.562"), ), }, data.ImportStep(), @@ -188,7 +187,7 @@ func TestAccNetAppVolume_update(t *testing.T) { check.That(data.ResourceName).ExistsInAzure(r), check.That(data.ResourceName).Key("storage_quota_in_gb").HasValue("101"), check.That(data.ResourceName).Key("export_policy_rule.#").HasValue("2"), - check.That(data.ResourceName).Key("tags.%").HasValue("3"), + check.That(data.ResourceName).Key("tags.%").HasValue("4"), check.That(data.ResourceName).Key("tags.FoO").HasValue("BaR"), check.That(data.ResourceName).Key("tags.bAr").HasValue("fOo"), check.That(data.ResourceName).Key("throughput_in_mibps").HasValue("65"), @@ -257,17 +256,17 @@ func TestAccNetAppVolume_updateExportPolicyRule(t *testing.T) { } func (t NetAppVolumeResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.VolumeID(state.ID) + id, err := volumes.ParseVolumeID(state.ID) if err != nil { return nil, err } - resp, err := clients.NetApp.VolumeClient.Get(ctx, id.ResourceGroup, id.NetAppAccountName, id.CapacityPoolName, id.Name) + resp, err := clients.NetApp.VolumeClient.Get(ctx, *id) if err != nil { return nil, fmt.Errorf("reading Netapp Volume (%s): %+v", id.String(), err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (NetAppVolumeResource) basic(data acceptance.TestData) string { @@ -287,6 +286,7 @@ resource "azurerm_netapp_volume" "test" { storage_quota_in_gb = 100 tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -310,7 +310,7 @@ resource "azurerm_netapp_volume" "test" { protocols = ["NFSv4.1"] security_style = "Unix" storage_quota_in_gb = 100 - throughput_in_mibps = 1.6 + throughput_in_mibps = 1.562 export_policy_rule { rule_index = 1 @@ -321,6 +321,7 @@ resource "azurerm_netapp_volume" "test" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -346,6 +347,7 @@ resource "azurerm_netapp_volume" "test" { storage_quota_in_gb = 100 tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -384,13 +386,14 @@ resource "azurerm_netapp_volume" "test" { protocols = ["NFSv3"] security_style = "Unix" storage_quota_in_gb = 100 - throughput_in_mibps = 1.6 + throughput_in_mibps = 1.562 data_protection_snapshot_policy { snapshot_policy_id = azurerm_netapp_snapshot_policy.test.id } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -413,7 +416,7 @@ resource "azurerm_netapp_volume" "test_primary" { subnet_id = azurerm_subnet.test.id protocols = ["NFSv3"] storage_quota_in_gb = 100 - throughput_in_mibps = 1.6 + throughput_in_mibps = 1.562 export_policy_rule { rule_index = 1 @@ -424,6 +427,7 @@ resource "azurerm_netapp_volume" "test_primary" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -440,7 +444,7 @@ resource "azurerm_netapp_volume" "test_secondary" { protocols = ["NFSv3"] storage_quota_in_gb = 100 snapshot_directory_visible = false - throughput_in_mibps = 1.6 + throughput_in_mibps = 1.562 export_policy_rule { rule_index = 1 @@ -458,6 +462,7 @@ resource "azurerm_netapp_volume" "test_secondary" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -480,7 +485,7 @@ resource "azurerm_netapp_volume" "test" { subnet_id = azurerm_subnet.test.id protocols = ["NFSv3"] storage_quota_in_gb = 100 - throughput_in_mibps = 1.6 + throughput_in_mibps = 1.562 export_policy_rule { rule_index = 1 @@ -491,6 +496,7 @@ resource "azurerm_netapp_volume" "test" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -526,6 +532,7 @@ resource "azurerm_netapp_volume" "test_snapshot_vol" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -549,7 +556,7 @@ resource "azurerm_netapp_volume" "test_snapshot_directory_visible_false" { protocols = ["NFSv3"] storage_quota_in_gb = 100 snapshot_directory_visible = false - throughput_in_mibps = 1.6 + throughput_in_mibps = 1.562 export_policy_rule { rule_index = 1 @@ -560,6 +567,7 @@ resource "azurerm_netapp_volume" "test_snapshot_directory_visible_false" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -626,6 +634,7 @@ resource "azurerm_netapp_volume" "test" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "FoO" = "BaR", "SkipASMAzSecPack" = "true" } @@ -648,7 +657,7 @@ resource "azurerm_netapp_volume" "test" { subnet_id = azurerm_subnet.test.id protocols = ["NFSv3"] storage_quota_in_gb = 100 - throughput_in_mibps = 1.6 + throughput_in_mibps = 1.562 export_policy_rule { rule_index = 1 @@ -675,6 +684,7 @@ resource "azurerm_netapp_volume" "test" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "FoO" = "BaR", "SkipASMAzSecPack" = "true" } @@ -716,6 +726,7 @@ resource "azurerm_netapp_volume" "test" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "FoO" = "BaR", "bAr" = "fOo", "SkipASMAzSecPack" = "true" @@ -735,6 +746,7 @@ resource "azurerm_virtual_network" "updated" { address_space = ["10.1.0.0/16"] tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -766,9 +778,10 @@ resource "azurerm_netapp_volume" "test" { subnet_id = azurerm_subnet.updated.id protocols = ["NFSv3"] storage_quota_in_gb = 100 - throughput_in_mibps = 1.6 + throughput_in_mibps = 1.562 tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -801,6 +814,7 @@ resource "azurerm_netapp_volume" "test" { } tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "FoO" = "BaR", "SkipASMAzSecPack" = "true" } @@ -819,6 +833,7 @@ resource "azurerm_virtual_network" "test_secondary" { address_space = ["10.6.0.0/16"] tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -845,6 +860,7 @@ resource "azurerm_netapp_account" "test_secondary" { resource_group_name = azurerm_resource_group.test.name tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -859,6 +875,7 @@ resource "azurerm_netapp_pool" "test_secondary" { qos_type = "Manual" tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -881,7 +898,9 @@ resource "azurerm_resource_group" "test" { location = "%s" tags = { - "SkipASMAzSecPack" = "true" + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "SkipASMAzSecPack" = "true", + "SkipNRMSNSG" = "true" } } @@ -892,6 +911,7 @@ resource "azurerm_virtual_network" "test" { address_space = ["10.6.0.0/16"] tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -916,6 +936,11 @@ resource "azurerm_netapp_account" "test" { name = "acctest-NetAppAccount-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name + + tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", + "SkipASMAzSecPack" = "true" + } } resource "azurerm_netapp_pool" "test" { @@ -927,6 +952,7 @@ resource "azurerm_netapp_pool" "test" { size_in_tb = 4 tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -949,6 +975,7 @@ resource "azurerm_resource_group" "test" { location = "%s" tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -959,6 +986,7 @@ resource "azurerm_network_security_group" "test" { resource_group_name = azurerm_resource_group.test.name tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", environment = "Production", "SkipASMAzSecPack" = "true" } @@ -971,6 +999,7 @@ resource "azurerm_virtual_network" "test" { address_space = ["10.6.0.0/16"] tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -997,6 +1026,7 @@ resource "azurerm_netapp_account" "test" { resource_group_name = azurerm_resource_group.test.name tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } @@ -1011,6 +1041,7 @@ resource "azurerm_netapp_pool" "test" { qos_type = "Manual" tags = { + "CreatedOnDate" = "2022-07-08T23:50:21Z", "SkipASMAzSecPack" = "true" } } diff --git a/internal/services/network/application_gateway_data_source.go b/internal/services/network/application_gateway_data_source.go index 380f5c42c451..3d5c17636aac 100644 --- a/internal/services/network/application_gateway_data_source.go +++ b/internal/services/network/application_gateway_data_source.go @@ -5,7 +5,6 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/parse" diff --git a/internal/services/network/application_gateway_resource.go b/internal/services/network/application_gateway_resource.go index ba98dbde0ec3..47ab875139f9 100644 --- a/internal/services/network/application_gateway_resource.go +++ b/internal/services/network/application_gateway_resource.go @@ -663,7 +663,7 @@ func resourceApplicationGateway() *pluginsdk.Resource { "priority": { Type: pluginsdk.TypeInt, - Required: true, + Optional: true, ValidateFunc: validation.IntBetween(1, 20000), }, diff --git a/internal/services/network/application_gateway_resource_test.go b/internal/services/network/application_gateway_resource_test.go index 56eea08051d6..68f1e833d7fd 100644 --- a/internal/services/network/application_gateway_resource_test.go +++ b/internal/services/network/application_gateway_resource_test.go @@ -1067,12 +1067,6 @@ func TestAccApplicationGateway_requestRoutingRulePriority(t *testing.T) { r := ApplicationGatewayResource{} data.ResourceTest(t, r, []acceptance.TestStep{ - { - Config: r.requestRoutingRulePriorityNotSet(data), - Check: acceptance.ComposeTestCheckFunc( - check.That(data.ResourceName).ExistsInAzure(r), - ), - }, { Config: r.requestRoutingRulePrioritySet(data), Check: acceptance.ComposeTestCheckFunc( @@ -1081,10 +1075,6 @@ func TestAccApplicationGateway_requestRoutingRulePriority(t *testing.T) { check.That(data.ResourceName).Key("request_routing_rule.1.priority").HasValue("20000"), ), }, - { - Config: r.requestRoutingRulePriorityValidation(data), - ExpectError: regexp.MustCompile("If you wish to use rule priority, you will have to specify rule-priority field values for all the existing request routing rules."), - }, }) } @@ -1384,6 +1374,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -1474,6 +1465,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomString, data.RandomInteger, data.RandomInteger) @@ -1554,6 +1546,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -1636,6 +1629,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger, minCapacity, maxCapacity) @@ -1717,6 +1711,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -2147,6 +2142,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger) @@ -2321,6 +2317,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger) @@ -2480,6 +2477,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger) @@ -2583,6 +2581,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger) @@ -2702,6 +2701,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger) @@ -2821,6 +2821,7 @@ resource "azurerm_application_gateway" "test" { rule_type = "PathBasedRouting" url_path_map_name = local.url_path_map_name http_listener_name = local.listener_name + priority = 10 } url_path_map { @@ -3004,6 +3005,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger) @@ -3793,6 +3795,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -3945,6 +3948,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -4160,6 +4164,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } ssl_certificate { @@ -4309,6 +4314,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } ssl_certificate { @@ -5014,6 +5020,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -5111,6 +5118,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -5227,6 +5235,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -5321,6 +5330,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -5403,6 +5413,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -5486,6 +5497,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -5567,6 +5579,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -5776,6 +5789,7 @@ resource "azurerm_application_gateway" "test" { backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name rewrite_rule_set_name = local.rewrite_rule_set_name + priority = 10 } rewrite_rule_set { @@ -5890,6 +5904,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name redirect_configuration_name = local.redirect_configuration_name rewrite_rule_set_name = local.rewrite_rule_set_name + priority = 10 } rewrite_rule_set { @@ -6012,6 +6027,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name redirect_configuration_name = local.redirect_configuration_name rewrite_rule_set_name = local.rewrite_rule_set_name + priority = 10 } rewrite_rule_set { @@ -6342,6 +6358,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) @@ -6624,6 +6641,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } ssl_profile { @@ -6720,6 +6738,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } ssl_profile { @@ -6818,6 +6837,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } ssl_profile { @@ -6922,6 +6942,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } ssl_profile { @@ -7025,6 +7046,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } ssl_profile { @@ -7046,90 +7068,6 @@ resource "azurerm_application_gateway" "test" { `, r.template(data), data.RandomInteger, data.RandomInteger) } -func (r ApplicationGatewayResource) requestRoutingRulePriorityNotSet(data acceptance.TestData) string { - return fmt.Sprintf(` -%s - -# since these variables are re-used - a locals block makes this more maintainable -locals { - backend_address_pool_name = "${azurerm_virtual_network.test.name}-beap" - frontend_port_name = "${azurerm_virtual_network.test.name}-feport" - frontend_ip_configuration_name = "${azurerm_virtual_network.test.name}-feip" - http_setting_name = "${azurerm_virtual_network.test.name}-be-htst" - listener_name = "${azurerm_virtual_network.test.name}-httplstn" - request_routing_rule_name = "${azurerm_virtual_network.test.name}-rqrt" -} - -resource "azurerm_public_ip" "test_standard" { - name = "acctest-pubip-%d-standard" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - sku = "Standard" - allocation_method = "Static" -} - -resource "azurerm_application_gateway" "test" { - name = "acctestag-%d" - resource_group_name = azurerm_resource_group.test.name - location = azurerm_resource_group.test.location - - sku { - name = "Standard_v2" - tier = "Standard_v2" - capacity = 1 - } - - ssl_policy { - policy_type = "Custom" - min_protocol_version = "TLSv1_1" - cipher_suites = ["TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256"] - } - - gateway_ip_configuration { - name = "my-gateway-ip-configuration" - subnet_id = azurerm_subnet.test.id - } - - frontend_port { - name = local.frontend_port_name - port = 80 - } - - frontend_ip_configuration { - name = local.frontend_ip_configuration_name - public_ip_address_id = azurerm_public_ip.test_standard.id - } - - backend_address_pool { - name = local.backend_address_pool_name - } - - backend_http_settings { - name = local.http_setting_name - cookie_based_affinity = "Disabled" - port = 80 - protocol = "Http" - request_timeout = 1 - } - - http_listener { - name = local.listener_name - frontend_ip_configuration_name = local.frontend_ip_configuration_name - frontend_port_name = local.frontend_port_name - protocol = "Http" - } - - request_routing_rule { - name = local.request_routing_rule_name - rule_type = "Basic" - http_listener_name = local.listener_name - backend_address_pool_name = local.backend_address_pool_name - backend_http_settings_name = local.http_setting_name - } -} -`, r.template(data), data.RandomInteger, data.RandomInteger) -} - func (r ApplicationGatewayResource) requestRoutingRulePrioritySet(data acceptance.TestData) string { return fmt.Sprintf(` %s @@ -7239,114 +7177,6 @@ resource "azurerm_application_gateway" "test" { `, r.template(data), data.RandomInteger, data.RandomInteger) } -func (r ApplicationGatewayResource) requestRoutingRulePriorityValidation(data acceptance.TestData) string { - return fmt.Sprintf(` -%s - -# since these variables are re-used - a locals block makes this more maintainable -locals { - backend_address_pool_name = "${azurerm_virtual_network.test.name}-beap" - frontend_port_name_1 = "${azurerm_virtual_network.test.name}-feport-1" - frontend_port_name_2 = "${azurerm_virtual_network.test.name}-feport-2" - frontend_ip_configuration_name = "${azurerm_virtual_network.test.name}-feip" - http_setting_name = "${azurerm_virtual_network.test.name}-be-htst" - listener_name_1 = "${azurerm_virtual_network.test.name}-httplstn-1" - listener_name_2 = "${azurerm_virtual_network.test.name}-httplstn-2" - request_routing_rule_name_1 = "${azurerm_virtual_network.test.name}-rqrt-1" - request_routing_rule_name_2 = "${azurerm_virtual_network.test.name}-rqrt-2" -} - -resource "azurerm_public_ip" "test_standard" { - name = "acctest-pubip-%d-standard" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - sku = "Standard" - allocation_method = "Static" -} - -resource "azurerm_application_gateway" "test" { - name = "acctestag-%d" - resource_group_name = azurerm_resource_group.test.name - location = azurerm_resource_group.test.location - - sku { - name = "Standard_v2" - tier = "Standard_v2" - capacity = 1 - } - - ssl_policy { - policy_type = "Custom" - min_protocol_version = "TLSv1_1" - cipher_suites = ["TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256"] - } - - gateway_ip_configuration { - name = "my-gateway-ip-configuration" - subnet_id = azurerm_subnet.test.id - } - - frontend_port { - name = local.frontend_port_name_1 - port = 80 - } - - frontend_port { - name = local.frontend_port_name_2 - port = 8080 - } - - frontend_ip_configuration { - name = local.frontend_ip_configuration_name - public_ip_address_id = azurerm_public_ip.test_standard.id - } - - backend_address_pool { - name = local.backend_address_pool_name - } - - backend_http_settings { - name = local.http_setting_name - cookie_based_affinity = "Disabled" - port = 80 - protocol = "Http" - request_timeout = 1 - } - - http_listener { - name = local.listener_name_1 - frontend_ip_configuration_name = local.frontend_ip_configuration_name - frontend_port_name = local.frontend_port_name_1 - protocol = "Http" - } - - http_listener { - name = local.listener_name_2 - frontend_ip_configuration_name = local.frontend_ip_configuration_name - frontend_port_name = local.frontend_port_name_2 - protocol = "Http" - } - - request_routing_rule { - name = local.request_routing_rule_name_1 - rule_type = "Basic" - http_listener_name = local.listener_name_1 - backend_address_pool_name = local.backend_address_pool_name - backend_http_settings_name = local.http_setting_name - priority = 1 - } - - request_routing_rule { - name = local.request_routing_rule_name_2 - rule_type = "Basic" - http_listener_name = local.listener_name_2 - backend_address_pool_name = local.backend_address_pool_name - backend_http_settings_name = local.http_setting_name - } -} -`, r.template(data), data.RandomInteger, data.RandomInteger) -} - func (r ApplicationGatewayResource) privateLink(data acceptance.TestData) string { return fmt.Sprintf(` %s @@ -7440,6 +7270,7 @@ resource "azurerm_application_gateway" "test" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name + priority = 10 } } `, r.template(data), data.RandomInteger, data.RandomInteger) diff --git a/internal/services/network/network_interface_network_security_group_association_resource.go b/internal/services/network/network_interface_network_security_group_association_resource.go index 55c4412e64ed..13148458804f 100644 --- a/internal/services/network/network_interface_network_security_group_association_resource.go +++ b/internal/services/network/network_interface_network_security_group_association_resource.go @@ -6,13 +6,12 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/azuresdkhacks" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/azuresdkhacks" "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" diff --git a/internal/services/network/network_interface_network_security_group_association_resource_test.go b/internal/services/network/network_interface_network_security_group_association_resource_test.go index 261d9b7768df..6fe4f0591e9c 100644 --- a/internal/services/network/network_interface_network_security_group_association_resource_test.go +++ b/internal/services/network/network_interface_network_security_group_association_resource_test.go @@ -6,11 +6,10 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/azuresdkhacks" - "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/azuresdkhacks" "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" diff --git a/internal/services/network/network_interface_resource.go b/internal/services/network/network_interface_resource.go index 2e2cd8db8946..ed54d35b8866 100644 --- a/internal/services/network/network_interface_resource.go +++ b/internal/services/network/network_interface_resource.go @@ -5,10 +5,9 @@ import ( "log" "time" + "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/network/private_endpoint_resource.go b/internal/services/network/private_endpoint_resource.go index c2cfcfb5a999..ff406428168d 100644 --- a/internal/services/network/private_endpoint_resource.go +++ b/internal/services/network/private_endpoint_resource.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-sdk/resource-manager/privatedns/2018-09-01/privatezones" + "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -22,7 +23,6 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate" postgresqlParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/postgres/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/sdk/2020-05-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" diff --git a/internal/services/network/subnet_resource.go b/internal/services/network/subnet_resource.go index e20cd28fd89c..4b59b47d7608 100644 --- a/internal/services/network/subnet_resource.go +++ b/internal/services/network/subnet_resource.go @@ -120,6 +120,7 @@ func resourceSubnet() *pluginsdk.Resource { "Microsoft.Logic/integrationServiceEnvironments", "Microsoft.MachineLearningServices/workspaces", "Microsoft.Netapp/volumes", + "Microsoft.Network/dnsResolvers", "Microsoft.Network/managedResolvers", "Microsoft.PowerPlatform/vnetaccesslinks", "Microsoft.ServiceFabricMesh/networks", diff --git a/internal/services/network/virtual_network_gateway_resource.go b/internal/services/network/virtual_network_gateway_resource.go index 03fe08993c51..3a52544ed2c0 100644 --- a/internal/services/network/virtual_network_gateway_resource.go +++ b/internal/services/network/virtual_network_gateway_resource.go @@ -6,10 +6,9 @@ import ( "log" "time" + "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/network/virtual_network_resource.go b/internal/services/network/virtual_network_resource.go index e636e4ee1b6a..d29b8bd8500a 100644 --- a/internal/services/network/virtual_network_resource.go +++ b/internal/services/network/virtual_network_resource.go @@ -8,10 +8,9 @@ import ( "net/http" "time" + "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/policy/assignment_base_resource.go b/internal/services/policy/assignment_base_resource.go index 2f658da287ad..e6e742e158ad 100644 --- a/internal/services/policy/assignment_base_resource.go +++ b/internal/services/policy/assignment_base_resource.go @@ -212,7 +212,8 @@ func (br assignmentBaseResource) updateFunc() sdk.ResourceFunc { } if existing.Identity != nil { update.Identity = &policy.Identity{ - Type: existing.Identity.Type, + Type: existing.Identity.Type, + UserAssignedIdentities: existing.Identity.UserAssignedIdentities, } } diff --git a/internal/services/policy/assignment_subscription_resource_test.go b/internal/services/policy/assignment_subscription_resource_test.go index 13dc7ddd483b..84c69cd0d953 100644 --- a/internal/services/policy/assignment_subscription_resource_test.go +++ b/internal/services/policy/assignment_subscription_resource_test.go @@ -120,12 +120,16 @@ func TestAccSubscriptionPolicyAssignment_identity(t *testing.T) { }, data.ImportStep(), { - Config: r.userAssignedIdentity(data), + Config: r.userAssignedIdentity(data, ""), Check: acceptance.ComposeTestCheckFunc( check.That(data.ResourceName).ExistsInAzure(r), ), }, data.ImportStep(), + { + Config: r.userAssignedIdentity(data, "description"), + }, + data.ImportStep(), }) } @@ -627,7 +631,7 @@ resource "azurerm_subscription_policy_assignment" "test" { `, template, data.RandomInteger, data.Locations.Primary) } -func (r SubscriptionAssignmentTestResource) userAssignedIdentity(data acceptance.TestData) string { +func (r SubscriptionAssignmentTestResource) userAssignedIdentity(data acceptance.TestData, description string) string { template := r.template() return fmt.Sprintf(` provider "azurerm" { @@ -656,11 +660,12 @@ resource "azurerm_subscription_policy_assignment" "test" { subscription_id = data.azurerm_subscription.test.id policy_definition_id = data.azurerm_policy_set_definition.test.id location = %[3]q + description = "%[4]s" identity { type = "UserAssigned" identity_ids = [azurerm_user_assigned_identity.test.id] } } -`, template, data.RandomInteger, data.Locations.Primary) +`, template, data.RandomInteger, data.Locations.Primary, description) } diff --git a/internal/services/policy/client/client.go b/internal/services/policy/client/client.go index 5164a6f572fb..e4656fcb0212 100644 --- a/internal/services/policy/client/client.go +++ b/internal/services/policy/client/client.go @@ -2,9 +2,9 @@ package client import ( "github.com/Azure/azure-sdk-for-go/services/guestconfiguration/mgmt/2020-06-25/guestconfiguration" - "github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights" "github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2021-06-01-preview/policy" policyPreview "github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2021-06-01-preview/policy" + "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/internal/common" ) @@ -13,7 +13,7 @@ type Client struct { DefinitionsClient *policy.DefinitionsClient ExemptionsClient *policyPreview.ExemptionsClient SetDefinitionsClient *policy.SetDefinitionsClient - RemediationsClient *policyinsights.RemediationsClient + PolicyInsightsClient *policyinsights.PolicyInsightsClient GuestConfigurationAssignmentsClient *guestconfiguration.AssignmentsClient } @@ -30,8 +30,8 @@ func NewClient(o *common.ClientOptions) *Client { setDefinitionsClient := policy.NewSetDefinitionsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&setDefinitionsClient.Client, o.ResourceManagerAuthorizer) - remediationsClient := policyinsights.NewRemediationsClientWithBaseURI(o.ResourceManagerEndpoint) - o.ConfigureClient(&remediationsClient.Client, o.ResourceManagerAuthorizer) + policyInsightsClient := policyinsights.NewPolicyInsightsClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&policyInsightsClient.Client, o.ResourceManagerAuthorizer) guestConfigurationAssignmentsClient := guestconfiguration.NewAssignmentsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&guestConfigurationAssignmentsClient.Client, o.ResourceManagerAuthorizer) @@ -41,7 +41,7 @@ func NewClient(o *common.ClientOptions) *Client { DefinitionsClient: &definitionsClient, ExemptionsClient: &exemptionsClient, SetDefinitionsClient: &setDefinitionsClient, - RemediationsClient: &remediationsClient, + PolicyInsightsClient: &policyInsightsClient, GuestConfigurationAssignmentsClient: &guestConfigurationAssignmentsClient, } } diff --git a/internal/services/policy/remediation_management_group.go b/internal/services/policy/remediation_management_group.go index 0c9f14bd0bfc..7221236fbcdc 100644 --- a/internal/services/policy/remediation_management_group.go +++ b/internal/services/policy/remediation_management_group.go @@ -6,13 +6,12 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - - managmentGroupParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/managementgroup/parse" - - "github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights" + "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + managmentGroupParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/managementgroup/parse" managmentGroupValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/managementgroup/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/policy/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/policy/validate" @@ -85,10 +84,10 @@ func resourceArmManagementGroupPolicyRemediation() *pluginsdk.Resource { "resource_discovery_mode": { Type: pluginsdk.TypeString, Optional: true, - Default: string(policyinsights.ExistingNonCompliant), + Default: string(policyinsights.ResourceDiscoveryModeExistingNonCompliant), ValidateFunc: validation.StringInSlice([]string{ - string(policyinsights.ExistingNonCompliant), - string(policyinsights.ReEvaluateCompliance), + string(policyinsights.ResourceDiscoveryModeExistingNonCompliant), + string(policyinsights.ResourceDiscoveryModeReEvaluateCompliance), }, false), }, }, @@ -96,41 +95,41 @@ func resourceArmManagementGroupPolicyRemediation() *pluginsdk.Resource { } func resourceArmManagementGroupPolicyRemediationCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewResourcePolicyRemediationId(d.Get("management_group_id").(string), d.Get("name").(string)) - - managementGroupId, err := managmentGroupParse.ManagementGroupID(id.ResourceId) + managementID, err := managmentGroupParse.ManagementGroupID(d.Get("management_group_id").(string)) if err != nil { return err } + id := policyinsights.NewProviders2RemediationID(managementID.Name, d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.GetAtManagementGroup(ctx, managementGroupId.Name, id.Name) + existing, err := client.RemediationsGetAtManagementGroup(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id.ID(), err) } } - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_management_group_policy_remediation", *existing.ID) + if existing.Model != nil && existing.Model.Id != nil && *existing.Model.Id != "" { + return tf.ImportAsExistsError("azurerm_management_group_policy_remediation", *existing.Model.Id) } } parameters := policyinsights.Remediation{ - RemediationProperties: &policyinsights.RemediationProperties{ + Properties: &policyinsights.RemediationProperties{ Filters: &policyinsights.RemediationFilters{ Locations: utils.ExpandStringSlice(d.Get("location_filters").([]interface{})), }, - PolicyAssignmentID: utils.String(d.Get("policy_assignment_id").(string)), - PolicyDefinitionReferenceID: utils.String(d.Get("policy_definition_id").(string)), - ResourceDiscoveryMode: policyinsights.ResourceDiscoveryMode(d.Get("resource_discovery_mode").(string)), + PolicyAssignmentId: utils.String(d.Get("policy_assignment_id").(string)), + PolicyDefinitionReferenceId: utils.String(d.Get("policy_definition_id").(string)), }, } + mode := policyinsights.ResourceDiscoveryMode(d.Get("resource_discovery_mode").(string)) + parameters.Properties.ResourceDiscoveryMode = &mode - if _, err := client.CreateOrUpdateAtManagementGroup(ctx, managementGroupId.Name, id.Name, parameters); err != nil { + if _, err := client.RemediationsCreateOrUpdateAtManagementGroup(ctx, id, parameters); err != nil { return fmt.Errorf("creating/updating %s: %+v", id.ID(), err) } @@ -140,23 +139,18 @@ func resourceArmManagementGroupPolicyRemediationCreateUpdate(d *pluginsdk.Resour } func resourceArmManagementGroupPolicyRemediationRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.ResourcePolicyRemediationID(d.Id()) + id, err := policyinsights.ParseProviders2RemediationID(d.Id()) if err != nil { return fmt.Errorf("reading Policy Remediation: %+v", err) } - managementGroupId, err := managmentGroupParse.ManagementGroupID(id.ResourceId) - if err != nil { - return err - } - - resp, err := client.GetAtManagementGroup(ctx, managementGroupId.Name, id.Name) + resp, err := client.RemediationsGetAtManagementGroup(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[INFO] %s does not exist - removing from state", id.ID()) d.SetId("") return nil @@ -164,10 +158,11 @@ func resourceArmManagementGroupPolicyRemediationRead(d *pluginsdk.ResourceData, return fmt.Errorf("reading %s: %+v", id.ID(), err) } - d.Set("name", id.Name) - d.Set("management_group_id", id.ResourceId) + d.Set("name", id.RemediationName) + managementGroupID := managmentGroupParse.NewManagementGroupId(id.ManagementGroupId) + d.Set("management_group_id", managementGroupID.ID()) - if props := resp.RemediationProperties; props != nil { + if props := resp.Model.Properties; props != nil { locations := []interface{}{} if filters := props.Filters; filters != nil { locations = utils.FlattenStringSlice(filters.Locations) @@ -176,82 +171,64 @@ func resourceArmManagementGroupPolicyRemediationRead(d *pluginsdk.ResourceData, return fmt.Errorf("setting `location_filters`: %+v", err) } - d.Set("policy_assignment_id", props.PolicyAssignmentID) - d.Set("policy_definition_id", props.PolicyDefinitionReferenceID) - d.Set("resource_discovery_mode", string(props.ResourceDiscoveryMode)) + d.Set("policy_assignment_id", props.PolicyAssignmentId) + d.Set("policy_definition_id", props.PolicyDefinitionReferenceId) + d.Set("resource_discovery_mode", props.ResourceDiscoveryMode) } return nil } func resourceArmManagementGroupPolicyRemediationDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.ResourcePolicyRemediationID(d.Id()) - if err != nil { - return err - } - - managementGroupId, err := managmentGroupParse.ManagementGroupID(id.ResourceId) + id, err := policyinsights.ParseProviders2RemediationID(d.Id()) if err != nil { return err } // we have to cancel the remediation first before deleting it when the resource_discovery_mode is set to ReEvaluateCompliance // therefore we first retrieve the remediation to see if the resource_discovery_mode is switched to ReEvaluateCompliance - existing, err := client.GetAtManagementGroup(ctx, managementGroupId.Name, id.Name) + existing, err := client.RemediationsGetAtManagementGroup(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse) { return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - if existing.RemediationProperties != nil && existing.RemediationProperties.ResourceDiscoveryMode == policyinsights.ReEvaluateCompliance { - // Remediation can only be canceld when it is in "Evaluating" status, otherwise, API might raise error (e.g. canceling a "Completed" remediation returns 400). - if existing.RemediationProperties.ProvisioningState != nil && *existing.RemediationProperties.ProvisioningState == "Evaluating" { - log.Printf("[DEBUG] cancelling the remediation first before deleting it when `resource_discovery_mode` is set to `ReEvaluateCompliance`") - if _, err := client.CancelAtManagementGroup(ctx, managementGroupId.Name, id.Name); err != nil { - return fmt.Errorf("cancelling %s: %+v", id.ID(), err) - } - - log.Printf("[DEBUG] waiting for the %s to be canceled", id.ID()) - stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{"Cancelling"}, - Target: []string{ - "Succeeded", "Canceled", "Failed", - }, - Refresh: managementGroupPolicyRemediationCancellationRefreshFunc(ctx, client, *id, *managementGroupId), - MinTimeout: 10 * time.Second, - Timeout: d.Timeout(pluginsdk.TimeoutDelete), - } - - if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for %s to be canceled: %+v", id.ID(), err) - } - } + if err := waitRemediationToDelete(ctx, existing.Model.Properties, id.ID(), d.Timeout(pluginsdk.TimeoutDelete), + func() error { + _, err := client.RemediationsCancelAtManagementGroup(ctx, *id) + return err + }, + managementGroupPolicyRemediationCancellationRefreshFunc(ctx, client, *id), + ); err != nil { + return err } - _, err = client.DeleteAtManagementGroup(ctx, managementGroupId.Name, id.Name) + _, err = client.RemediationsDeleteAtManagementGroup(ctx, *id) return err } -func managementGroupPolicyRemediationCancellationRefreshFunc(ctx context.Context, client *policyinsights.RemediationsClient, id parse.ResourcePolicyRemediationId, managementGroupId managmentGroupParse.ManagementGroupId) pluginsdk.StateRefreshFunc { +func managementGroupPolicyRemediationCancellationRefreshFunc(ctx context.Context, + client *policyinsights.PolicyInsightsClient, id policyinsights.Providers2RemediationId) pluginsdk.StateRefreshFunc { + return func() (interface{}, string, error) { - resp, err := client.GetAtManagementGroup(ctx, managementGroupId.Name, id.Name) + resp, err := client.RemediationsGetAtManagementGroup(ctx, id) if err != nil { return nil, "", fmt.Errorf("issuing read request for %s: %+v", id.ID(), err) } - if resp.RemediationProperties == nil { + if resp.Model.Properties == nil { return nil, "", fmt.Errorf("`properties` was nil") } - if resp.RemediationProperties.ProvisioningState == nil { + if resp.Model.Properties.ProvisioningState == nil { return nil, "", fmt.Errorf("`properties.ProvisioningState` was nil") } - return resp, *resp.RemediationProperties.ProvisioningState, nil + return resp, *resp.Model.Properties.ProvisioningState, nil } } diff --git a/internal/services/policy/remediation_management_group_test.go b/internal/services/policy/remediation_management_group_test.go index 6b98ffe706cb..99a447864838 100644 --- a/internal/services/policy/remediation_management_group_test.go +++ b/internal/services/policy/remediation_management_group_test.go @@ -5,12 +5,11 @@ import ( "fmt" "testing" - managmentGroupParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/managementgroup/parse" - + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/policy/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -48,24 +47,20 @@ func TestAccAzureRMManagementGroupPolicyRemediation_complete(t *testing.T) { } func (r ManagementGroupPolicyRemediationResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.ResourcePolicyRemediationID(state.ID) - if err != nil { - return nil, err - } - managementGroupId, err := managmentGroupParse.ManagementGroupID(id.ResourceId) + id, err := policyinsights.ParseProviders2RemediationID(state.ID) if err != nil { return nil, err } - resp, err := client.Policy.RemediationsClient.GetAtManagementGroup(ctx, managementGroupId.Name, id.Name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + resp, err := client.Policy.PolicyInsightsClient.RemediationsGetAtManagementGroup(ctx, *id) + if err != nil || resp.Model == nil { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } return nil, fmt.Errorf("retrieving Policy Remediation %q: %+v", state.ID, err) } - return utils.Bool(resp.RemediationProperties != nil), nil + return utils.Bool(resp.Model.Properties != nil), nil } func (r ManagementGroupPolicyRemediationResource) template(data acceptance.TestData) string { diff --git a/internal/services/policy/remediation_resource.go b/internal/services/policy/remediation_resource.go index 810673e1726a..efe4bb667e29 100644 --- a/internal/services/policy/remediation_resource.go +++ b/internal/services/policy/remediation_resource.go @@ -6,11 +6,10 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - + "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" - - "github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/policy/parse" @@ -84,10 +83,10 @@ func resourceArmResourcePolicyRemediation() *pluginsdk.Resource { "resource_discovery_mode": { Type: pluginsdk.TypeString, Optional: true, - Default: string(policyinsights.ExistingNonCompliant), + Default: string(policyinsights.ResourceDiscoveryModeExistingNonCompliant), ValidateFunc: validation.StringInSlice([]string{ - string(policyinsights.ExistingNonCompliant), - string(policyinsights.ReEvaluateCompliance), + string(policyinsights.ResourceDiscoveryModeExistingNonCompliant), + string(policyinsights.ResourceDiscoveryModeReEvaluateCompliance), }, false), }, }, @@ -95,38 +94,39 @@ func resourceArmResourcePolicyRemediation() *pluginsdk.Resource { } func resourceArmResourcePolicyRemediationCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() resourceId := d.Get("resource_id").(string) - id := parse.NewResourcePolicyRemediationId(resourceId, d.Get("name").(string)) + id := policyinsights.NewScopedRemediationID(resourceId, d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.GetAtResource(ctx, id.ResourceId, id.Name) + existing, err := client.RemediationsGetAtResource(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id.ID(), err) } } - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_resource_policy_remediation", *existing.ID) + if existing.Model != nil && existing.Model.Id != nil && *existing.Model.Id != "" { + return tf.ImportAsExistsError("azurerm_resource_policy_remediation", *existing.Model.Id) } } parameters := policyinsights.Remediation{ - RemediationProperties: &policyinsights.RemediationProperties{ + Properties: &policyinsights.RemediationProperties{ Filters: &policyinsights.RemediationFilters{ Locations: utils.ExpandStringSlice(d.Get("location_filters").([]interface{})), }, - PolicyAssignmentID: utils.String(d.Get("policy_assignment_id").(string)), - PolicyDefinitionReferenceID: utils.String(d.Get("policy_definition_id").(string)), - ResourceDiscoveryMode: policyinsights.ResourceDiscoveryMode(d.Get("resource_discovery_mode").(string)), + PolicyAssignmentId: utils.String(d.Get("policy_assignment_id").(string)), + PolicyDefinitionReferenceId: utils.String(d.Get("policy_definition_id").(string)), }, } + mode := policyinsights.ResourceDiscoveryMode(d.Get("resource_discovery_mode").(string)) + parameters.Properties.ResourceDiscoveryMode = &mode - if _, err := client.CreateOrUpdateAtResource(ctx, id.ResourceId, id.Name, parameters); err != nil { + if _, err := client.RemediationsCreateOrUpdateAtResource(ctx, id, parameters); err != nil { return fmt.Errorf("creating/updating %s: %+v", id.ID(), err) } @@ -136,18 +136,17 @@ func resourceArmResourcePolicyRemediationCreateUpdate(d *pluginsdk.ResourceData, } func resourceArmResourcePolicyRemediationRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.ResourcePolicyRemediationID(d.Id()) + id, err := policyinsights.ParseScopedRemediationID(d.Id()) if err != nil { - return fmt.Errorf("reading Policy Remediation: %+v", err) + return fmt.Errorf("parsing Policy Scoped Remediation ID: %+v", err) } - - resp, err := client.GetAtResource(ctx, id.ResourceId, id.Name) + resp, err := client.RemediationsGetAtResource(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[INFO] %s does not exist - removing from state", id.ID()) d.SetId("") return nil @@ -155,10 +154,10 @@ func resourceArmResourcePolicyRemediationRead(d *pluginsdk.ResourceData, meta in return fmt.Errorf("reading %s: %+v", id.ID(), err) } - d.Set("name", id.Name) + d.Set("name", id.RemediationName) d.Set("resource_id", id.ResourceId) - if props := resp.RemediationProperties; props != nil { + if props := resp.Model.Properties; props != nil { locations := []interface{}{} if filters := props.Filters; filters != nil { locations = utils.FlattenStringSlice(filters.Locations) @@ -167,77 +166,104 @@ func resourceArmResourcePolicyRemediationRead(d *pluginsdk.ResourceData, meta in return fmt.Errorf("setting `location_filters`: %+v", err) } - d.Set("policy_assignment_id", props.PolicyAssignmentID) - d.Set("policy_definition_id", props.PolicyDefinitionReferenceID) - d.Set("resource_discovery_mode", string(props.ResourceDiscoveryMode)) + d.Set("policy_assignment_id", props.PolicyAssignmentId) + d.Set("policy_definition_id", props.PolicyDefinitionReferenceId) + d.Set("resource_discovery_mode", utils.NormalizeNilableString((*string)(props.ResourceDiscoveryMode))) + } return nil } func resourceArmResourcePolicyRemediationDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.ResourcePolicyRemediationID(d.Id()) + id, err := policyinsights.ParseScopedRemediationID(d.Id()) if err != nil { - return err + return fmt.Errorf("parsing Policy Scoped Remediation ID: %+v", err) } // we have to cancel the remediation first before deleting it when the resource_discovery_mode is set to ReEvaluateCompliance // therefore we first retrieve the remediation to see if the resource_discovery_mode is switched to ReEvaluateCompliance - existing, err := client.GetAtResource(ctx, id.ResourceId, id.Name) + existing, err := client.RemediationsGetAtResource(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse) { return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - if existing.RemediationProperties != nil && existing.RemediationProperties.ResourceDiscoveryMode == policyinsights.ReEvaluateCompliance { - // Remediation can only be canceld when it is in "Evaluating" status, otherwise, API might raise error (e.g. canceling a "Completed" remediation returns 400). - if existing.RemediationProperties.ProvisioningState != nil && *existing.RemediationProperties.ProvisioningState == "Evaluating" { - log.Printf("[DEBUG] cancelling the remediation first before deleting it when `resource_discovery_mode` is set to `ReEvaluateCompliance`") - if _, err := client.CancelAtResource(ctx, id.ResourceId, id.Name); err != nil { - return fmt.Errorf("cancelling %s: %+v", id.ID(), err) - } - - log.Printf("[DEBUG] waiting for the %s to be canceled", id.ID()) - stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{"Cancelling"}, - Target: []string{ - "Succeeded", "Canceled", "Failed", - }, - Refresh: resourcePolicyRemediationCancellationRefreshFunc(ctx, client, *id), - MinTimeout: 10 * time.Second, - Timeout: d.Timeout(pluginsdk.TimeoutDelete), - } - - if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for %s to be canceled: %+v", id.ID(), err) - } - } + if err := waitRemediationToDelete(ctx, + existing.Model.Properties, + id.ID(), + d.Timeout(pluginsdk.TimeoutDelete), + func() error { + _, err := client.RemediationsCancelAtResource(ctx, *id) + return err + }, + resourcePolicyRemediationCancellationRefreshFunc(ctx, client, *id), + ); err != nil { + return err } - _, err = client.DeleteAtResource(ctx, id.ResourceId, id.Name) + _, err = client.RemediationsDeleteAtResource(ctx, *id) return err } -func resourcePolicyRemediationCancellationRefreshFunc(ctx context.Context, client *policyinsights.RemediationsClient, id parse.ResourcePolicyRemediationId) pluginsdk.StateRefreshFunc { +func resourcePolicyRemediationCancellationRefreshFunc(ctx context.Context, client *policyinsights.PolicyInsightsClient, id policyinsights.ScopedRemediationId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - resp, err := client.GetAtResource(ctx, id.ResourceId, id.Name) + resp, err := client.RemediationsGetAtResource(ctx, id) if err != nil { return nil, "", fmt.Errorf("issuing read request for %s: %+v", id.ID(), err) } - if resp.RemediationProperties == nil { + if resp.Model.Properties == nil { return nil, "", fmt.Errorf("`properties` was nil") } - if resp.RemediationProperties.ProvisioningState == nil { + if resp.Model.Properties.ProvisioningState == nil { return nil, "", fmt.Errorf("`properties.ProvisioningState` was nil") } - return resp, *resp.RemediationProperties.ProvisioningState, nil + return resp, *resp.Model.Properties.ProvisioningState, nil + } +} + +// waitRemediationToDelete waits for the remediation to a status that allow to delete +func waitRemediationToDelete(ctx context.Context, + prop *policyinsights.RemediationProperties, + id string, + timeout time.Duration, + cancelFunc func() error, + refresh pluginsdk.StateRefreshFunc) error { + + if prop == nil { + return nil } + if mode := prop.ResourceDiscoveryMode; mode != nil && *mode == policyinsights.ResourceDiscoveryModeReEvaluateCompliance { + // Remediation can only be canceld when it is in "Evaluating" or "Accepted" status, otherwise, API might raise error (e.g. canceling a "Completed" remediation returns 400). + if state := prop.ProvisioningState; state != nil && (*state == "Evaluating" || *state == "Accepted") { + log.Printf("[DEBUG] cancelling the remediation first before deleting it when `resource_discovery_mode` is set to `ReEvaluateCompliance`") + if err := cancelFunc(); err != nil { + return fmt.Errorf("cancelling %s: %+v", id, err) + } + + log.Printf("[DEBUG] waiting for the %s to be canceled", id) + stateConf := &pluginsdk.StateChangeConf{ + Pending: []string{"Cancelling"}, + Target: []string{ + "Succeeded", "Canceled", "Failed", + }, + Refresh: refresh, + MinTimeout: 10 * time.Second, + Timeout: timeout, + } + + if _, err := stateConf.WaitForStateContext(ctx); err != nil { + return fmt.Errorf("waiting for %s to be canceled: %+v", id, err) + } + } + } + return nil } diff --git a/internal/services/policy/remediation_resource_group.go b/internal/services/policy/remediation_resource_group.go index e2d7646a78cc..799934922629 100644 --- a/internal/services/policy/remediation_resource_group.go +++ b/internal/services/policy/remediation_resource_group.go @@ -6,9 +6,9 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - - "github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights" + "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/policy/parse" @@ -84,10 +84,10 @@ func resourceArmResourceGroupPolicyRemediation() *pluginsdk.Resource { "resource_discovery_mode": { Type: pluginsdk.TypeString, Optional: true, - Default: string(policyinsights.ExistingNonCompliant), + Default: string(policyinsights.ResourceDiscoveryModeExistingNonCompliant), ValidateFunc: validation.StringInSlice([]string{ - string(policyinsights.ExistingNonCompliant), - string(policyinsights.ReEvaluateCompliance), + string(policyinsights.ResourceDiscoveryModeExistingNonCompliant), + string(policyinsights.ResourceDiscoveryModeReEvaluateCompliance), }, false), }, }, @@ -95,7 +95,7 @@ func resourceArmResourceGroupPolicyRemediation() *pluginsdk.Resource { } func resourceArmResourceGroupPolicyRemediationCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -104,32 +104,33 @@ func resourceArmResourceGroupPolicyRemediationCreateUpdate(d *pluginsdk.Resource return err } - id := parse.NewResourceGroupPolicyRemediationID(resourceGroupId.SubscriptionId, resourceGroupId.ResourceGroup, d.Get("name").(string)) + id := policyinsights.NewProviderRemediationID(resourceGroupId.SubscriptionId, resourceGroupId.ResourceGroup, d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.GetAtResourceGroup(ctx, id.SubscriptionId, id.ResourceGroup, id.RemediationName) + existing, err := client.RemediationsGetAtResourceGroup(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id.ID(), err) } } - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_resource_group_policy_remediation", *existing.ID) + if existing.Model != nil && existing.Model.Id != nil && *existing.Model.Id != "" { + return tf.ImportAsExistsError("azurerm_resource_group_policy_remediation", *existing.Model.Id) } } parameters := policyinsights.Remediation{ - RemediationProperties: &policyinsights.RemediationProperties{ + Properties: &policyinsights.RemediationProperties{ Filters: &policyinsights.RemediationFilters{ Locations: utils.ExpandStringSlice(d.Get("location_filters").([]interface{})), }, - PolicyAssignmentID: utils.String(d.Get("policy_assignment_id").(string)), - PolicyDefinitionReferenceID: utils.String(d.Get("policy_definition_id").(string)), - ResourceDiscoveryMode: policyinsights.ResourceDiscoveryMode(d.Get("resource_discovery_mode").(string)), + PolicyAssignmentId: utils.String(d.Get("policy_assignment_id").(string)), + PolicyDefinitionReferenceId: utils.String(d.Get("policy_definition_id").(string)), }, } + mode := policyinsights.ResourceDiscoveryMode(d.Get("resource_discovery_mode").(string)) + parameters.Properties.ResourceDiscoveryMode = &mode - if _, err = client.CreateOrUpdateAtResourceGroup(ctx, id.SubscriptionId, id.ResourceGroup, id.RemediationName, parameters); err != nil { + if _, err = client.RemediationsCreateOrUpdateAtResourceGroup(ctx, id, parameters); err != nil { return fmt.Errorf("creating/updating %s: %+v", id.ID(), err) } @@ -139,20 +140,20 @@ func resourceArmResourceGroupPolicyRemediationCreateUpdate(d *pluginsdk.Resource } func resourceArmResourceGroupPolicyRemediationRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.ResourceGroupPolicyRemediationID(d.Id()) + id, err := policyinsights.ParseProviderRemediationID(d.Id()) if err != nil { return fmt.Errorf("reading Policy Remediation: %+v", err) } - resourceGroupId := resourceParse.NewResourceGroupID(id.SubscriptionId, id.ResourceGroup) + resourceGroupId := resourceParse.NewResourceGroupID(id.SubscriptionId, id.ResourceGroupName) - resp, err := client.GetAtResourceGroup(ctx, id.SubscriptionId, id.ResourceGroup, id.RemediationName) + resp, err := client.RemediationsGetAtResourceGroup(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[INFO] %s does not exist - removing from state", id.ID()) d.SetId("") return nil @@ -163,7 +164,7 @@ func resourceArmResourceGroupPolicyRemediationRead(d *pluginsdk.ResourceData, me d.Set("name", id.RemediationName) d.Set("resource_group_id", resourceGroupId.ID()) - if props := resp.RemediationProperties; props != nil { + if props := resp.Model.Properties; props != nil { locations := []interface{}{} if filters := props.Filters; filters != nil { locations = utils.FlattenStringSlice(filters.Locations) @@ -172,77 +173,63 @@ func resourceArmResourceGroupPolicyRemediationRead(d *pluginsdk.ResourceData, me return fmt.Errorf("setting `location_filters`: %+v", err) } - d.Set("policy_assignment_id", props.PolicyAssignmentID) - d.Set("policy_definition_id", props.PolicyDefinitionReferenceID) - d.Set("resource_discovery_mode", string(props.ResourceDiscoveryMode)) + d.Set("policy_assignment_id", props.PolicyAssignmentId) + d.Set("policy_definition_id", props.PolicyDefinitionReferenceId) + d.Set("resource_discovery_mode", utils.NormalizeNilableString((*string)(props.ResourceDiscoveryMode))) + } return nil } func resourceArmResourceGroupPolicyRemediationDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.ResourceGroupPolicyRemediationID(d.Id()) + id, err := policyinsights.ParseProviderRemediationID(d.Id()) if err != nil { return err } // we have to cancel the remediation first before deleting it when the resource_discovery_mode is set to ReEvaluateCompliance // therefore we first retrieve the remediation to see if the resource_discovery_mode is switched to ReEvaluateCompliance - existing, err := client.GetAtResourceGroup(ctx, id.SubscriptionId, id.ResourceGroup, id.RemediationName) + existing, err := client.RemediationsGetAtResourceGroup(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse) { return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - if existing.RemediationProperties != nil && existing.RemediationProperties.ResourceDiscoveryMode == policyinsights.ReEvaluateCompliance { - // Remediation can only be canceld when it is in "Evaluating" status, otherwise, API might raise error (e.g. canceling a "Completed" remediation returns 400). - if existing.RemediationProperties.ProvisioningState != nil && *existing.RemediationProperties.ProvisioningState == "Evaluating" { - log.Printf("[DEBUG] cancelling the remediation first before deleting it when `resource_discovery_mode` is set to `ReEvaluateCompliance`") - if _, err := client.CancelAtResourceGroup(ctx, id.SubscriptionId, id.ResourceGroup, id.RemediationName); err != nil { - return fmt.Errorf("cancelling %s: %+v", id.ID(), err) - } - - log.Printf("[DEBUG] waiting for the %s to be canceled", id.ID()) - stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{"Cancelling"}, - Target: []string{ - "Succeeded", "Canceled", "Failed", - }, - Refresh: resourceGroupPolicyRemediationCancellationRefreshFunc(ctx, client, *id), - MinTimeout: 10 * time.Second, - Timeout: d.Timeout(pluginsdk.TimeoutDelete), - } + if err := waitRemediationToDelete(ctx, existing.Model.Properties, id.ID(), d.Timeout(pluginsdk.TimeoutDelete), + func() error { + _, err := client.RemediationsCancelAtResourceGroup(ctx, *id) + return err + }, + resourceGroupPolicyRemediationCancellationRefreshFunc(ctx, client, *id), + ); err != nil { - if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for %s to be canceled: %+v", id.ID(), err) - } - } } - _, err = client.DeleteAtResourceGroup(ctx, id.SubscriptionId, id.ResourceGroup, id.RemediationName) + _, err = client.RemediationsDeleteAtResourceGroup(ctx, *id) return err } -func resourceGroupPolicyRemediationCancellationRefreshFunc(ctx context.Context, client *policyinsights.RemediationsClient, id parse.ResourceGroupPolicyRemediationId) pluginsdk.StateRefreshFunc { +func resourceGroupPolicyRemediationCancellationRefreshFunc(ctx context.Context, client *policyinsights.PolicyInsightsClient, id policyinsights.ProviderRemediationId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - resp, err := client.GetAtResourceGroup(ctx, id.SubscriptionId, id.ResourceGroup, id.RemediationName) + resp, err := client.RemediationsGetAtResourceGroup(ctx, id) if err != nil { return nil, "", fmt.Errorf("issuing read request for %s: %+v", id.ID(), err) } - if resp.RemediationProperties == nil { + if resp.Model.Properties == nil { return nil, "", fmt.Errorf("`properties` was nil") } - if resp.RemediationProperties.ProvisioningState == nil { + if resp.Model.Properties.ProvisioningState == nil { return nil, "", fmt.Errorf("`properties.ProvisioningState` was nil") } - return resp, *resp.RemediationProperties.ProvisioningState, nil + return resp, *resp.Model.Properties.ProvisioningState, nil } } diff --git a/internal/services/policy/remediation_resource_group_test.go b/internal/services/policy/remediation_resource_group_test.go index 5365e58fdfb9..55c655a46424 100644 --- a/internal/services/policy/remediation_resource_group_test.go +++ b/internal/services/policy/remediation_resource_group_test.go @@ -5,10 +5,11 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/policy/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -46,20 +47,20 @@ func TestAccAzureRMResourceGroupPolicyRemediation_complete(t *testing.T) { } func (r ResourceGroupPolicyRemediationResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.ResourceGroupPolicyRemediationID(state.ID) + id, err := policyinsights.ParseProviderRemediationID(state.ID) if err != nil { return nil, err } - resp, err := client.Policy.RemediationsClient.GetAtResourceGroup(ctx, id.SubscriptionId, id.ResourceGroup, id.RemediationName) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + resp, err := client.Policy.PolicyInsightsClient.RemediationsGetAtResourceGroup(ctx, *id) + if err != nil || resp.Model == nil { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } return nil, fmt.Errorf("retrieving Policy Remediation %q: %+v", state.ID, err) } - return utils.Bool(resp.RemediationProperties != nil), nil + return utils.Bool(resp.Model.Properties != nil), nil } func (r ResourceGroupPolicyRemediationResource) template(data acceptance.TestData) string { diff --git a/internal/services/policy/remediation_resource_test.go b/internal/services/policy/remediation_resource_test.go index bb1ba61f1a33..14c1498a3d4e 100644 --- a/internal/services/policy/remediation_resource_test.go +++ b/internal/services/policy/remediation_resource_test.go @@ -5,10 +5,11 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/policy/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -46,20 +47,20 @@ func TestAccAzureRMResourcePolicyRemediation_complete(t *testing.T) { } func (r ResourcePolicyRemediationResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.ResourcePolicyRemediationID(state.ID) + id, err := policyinsights.ParseScopedRemediationID(state.ID) if err != nil { return nil, err } - resp, err := client.Policy.RemediationsClient.GetAtResource(ctx, id.ResourceId, id.Name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + resp, err := client.Policy.PolicyInsightsClient.RemediationsGetAtResource(ctx, *id) + if err != nil || resp.Model == nil { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } return nil, fmt.Errorf("retrieving Policy Remediation %q: %+v", state.ID, err) } - return utils.Bool(resp.RemediationProperties != nil), nil + return utils.Bool(resp.Model.Properties != nil), nil } func (r ResourcePolicyRemediationResource) template(data acceptance.TestData) string { diff --git a/internal/services/policy/remediation_subscription.go b/internal/services/policy/remediation_subscription.go index c6ff1726c13c..9ac266d7f89a 100644 --- a/internal/services/policy/remediation_subscription.go +++ b/internal/services/policy/remediation_subscription.go @@ -6,11 +6,10 @@ import ( "log" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" - - "github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/policy/parse" @@ -84,10 +83,10 @@ func resourceArmSubscriptionPolicyRemediation() *pluginsdk.Resource { "resource_discovery_mode": { Type: pluginsdk.TypeString, Optional: true, - Default: string(policyinsights.ExistingNonCompliant), + Default: string(policyinsights.ResourceDiscoveryModeExistingNonCompliant), ValidateFunc: validation.StringInSlice([]string{ - string(policyinsights.ExistingNonCompliant), - string(policyinsights.ReEvaluateCompliance), + string(policyinsights.ResourceDiscoveryModeExistingNonCompliant), + string(policyinsights.ResourceDiscoveryModeReEvaluateCompliance), }, false), }, }, @@ -95,7 +94,7 @@ func resourceArmSubscriptionPolicyRemediation() *pluginsdk.Resource { } func resourceArmSubscriptionPolicyRemediationCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -104,32 +103,33 @@ func resourceArmSubscriptionPolicyRemediationCreateUpdate(d *pluginsdk.ResourceD return err } - id := parse.NewSubscriptionPolicyRemediationID(subscriptionId.SubscriptionId, d.Get("name").(string)) + id := policyinsights.NewRemediationID(subscriptionId.SubscriptionId, d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.GetAtSubscription(ctx, id.SubscriptionId, id.RemediationName) + existing, err := client.RemediationsGetAtSubscription(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id.ID(), err) } } - if existing.ID != nil && *existing.ID != "" { - return tf.ImportAsExistsError("azurerm_subscription_policy_remediation", *existing.ID) + if existing.Model != nil && existing.Model.Id != nil && *existing.Model.Id != "" { + return tf.ImportAsExistsError("azurerm_subscription_policy_remediation", *existing.Model.Id) } } parameters := policyinsights.Remediation{ - RemediationProperties: &policyinsights.RemediationProperties{ + Properties: &policyinsights.RemediationProperties{ Filters: &policyinsights.RemediationFilters{ Locations: utils.ExpandStringSlice(d.Get("location_filters").([]interface{})), }, - PolicyAssignmentID: utils.String(d.Get("policy_assignment_id").(string)), - PolicyDefinitionReferenceID: utils.String(d.Get("policy_definition_id").(string)), - ResourceDiscoveryMode: policyinsights.ResourceDiscoveryMode(d.Get("resource_discovery_mode").(string)), + PolicyAssignmentId: utils.String(d.Get("policy_assignment_id").(string)), + PolicyDefinitionReferenceId: utils.String(d.Get("policy_definition_id").(string)), }, } + mode := policyinsights.ResourceDiscoveryMode(d.Get("resource_discovery_mode").(string)) + parameters.Properties.ResourceDiscoveryMode = &mode - if _, err = client.CreateOrUpdateAtSubscription(ctx, id.SubscriptionId, id.RemediationName, parameters); err != nil { + if _, err = client.RemediationsCreateOrUpdateAtSubscription(ctx, id, parameters); err != nil { return fmt.Errorf("creating/updating %s: %+v", id.ID(), err) } @@ -139,20 +139,20 @@ func resourceArmSubscriptionPolicyRemediationCreateUpdate(d *pluginsdk.ResourceD } func resourceArmSubscriptionPolicyRemediationRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SubscriptionPolicyRemediationID(d.Id()) + id, err := policyinsights.ParseRemediationID(d.Id()) if err != nil { return fmt.Errorf("reading Policy Remediation: %+v", err) } subscriptionId := commonids.NewSubscriptionID(id.SubscriptionId) - resp, err := client.GetAtSubscription(ctx, id.SubscriptionId, id.RemediationName) + resp, err := client.RemediationsGetAtSubscription(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { log.Printf("[INFO] %s does not exist - removing from state", id.ID()) d.SetId("") return nil @@ -163,7 +163,7 @@ func resourceArmSubscriptionPolicyRemediationRead(d *pluginsdk.ResourceData, met d.Set("name", id.RemediationName) d.Set("subscription_id", subscriptionId.ID()) - if props := resp.RemediationProperties; props != nil { + if props := resp.Model.Properties; props != nil { locations := []interface{}{} if filters := props.Filters; filters != nil { locations = utils.FlattenStringSlice(filters.Locations) @@ -172,77 +172,62 @@ func resourceArmSubscriptionPolicyRemediationRead(d *pluginsdk.ResourceData, met return fmt.Errorf("setting `location_filters`: %+v", err) } - d.Set("policy_assignment_id", props.PolicyAssignmentID) - d.Set("policy_definition_id", props.PolicyDefinitionReferenceID) - d.Set("resource_discovery_mode", string(props.ResourceDiscoveryMode)) + d.Set("policy_assignment_id", props.PolicyAssignmentId) + d.Set("policy_definition_id", props.PolicyDefinitionReferenceId) + d.Set("resource_discovery_mode", utils.NormalizeNilableString((*string)(props.ResourceDiscoveryMode))) } return nil } func resourceArmSubscriptionPolicyRemediationDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Policy.RemediationsClient + client := meta.(*clients.Client).Policy.PolicyInsightsClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SubscriptionPolicyRemediationID(d.Id()) + id, err := policyinsights.ParseRemediationID(d.Id()) if err != nil { return err } // we have to cancel the remediation first before deleting it when the resource_discovery_mode is set to ReEvaluateCompliance // therefore we first retrieve the remediation to see if the resource_discovery_mode is switched to ReEvaluateCompliance - existing, err := client.GetAtSubscription(ctx, id.SubscriptionId, id.RemediationName) + existing, err := client.RemediationsGetAtSubscription(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse) { return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - if existing.RemediationProperties != nil && existing.RemediationProperties.ResourceDiscoveryMode == policyinsights.ReEvaluateCompliance { - // Remediation can only be canceld when it is in "Evaluating" status, otherwise, API might raise error (e.g. canceling a "Completed" remediation returns 400). - if existing.RemediationProperties.ProvisioningState != nil && *existing.RemediationProperties.ProvisioningState == "Evaluating" { - log.Printf("[DEBUG] cancelling the remediation first before deleting it when `resource_discovery_mode` is set to `ReEvaluateCompliance`") - if _, err := client.CancelAtSubscription(ctx, id.SubscriptionId, id.RemediationName); err != nil { - return fmt.Errorf("cancelling %s: %+v", id.ID(), err) - } - - log.Printf("[DEBUG] waiting for the %s to be canceled", id.ID()) - stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{"Cancelling"}, - Target: []string{ - "Succeeded", "Canceled", "Failed", - }, - Refresh: subscriptionPolicyRemediationCancellationRefreshFunc(ctx, client, *id), - MinTimeout: 10 * time.Second, - Timeout: d.Timeout(pluginsdk.TimeoutDelete), - } - - if _, err := stateConf.WaitForStateContext(ctx); err != nil { - return fmt.Errorf("waiting for %s to be canceled: %+v", id.ID(), err) - } - } + if err := waitRemediationToDelete(ctx, existing.Model.Properties, id.ID(), d.Timeout(pluginsdk.TimeoutDelete), + func() error { + _, err := client.RemediationsCancelAtSubscription(ctx, *id) + return err + }, + subscriptionPolicyRemediationCancellationRefreshFunc(ctx, client, *id), + ); err != nil { + return err } - _, err = client.DeleteAtSubscription(ctx, id.SubscriptionId, id.RemediationName) + _, err = client.RemediationsDeleteAtSubscription(ctx, *id) return err } -func subscriptionPolicyRemediationCancellationRefreshFunc(ctx context.Context, client *policyinsights.RemediationsClient, id parse.SubscriptionPolicyRemediationId) pluginsdk.StateRefreshFunc { +func subscriptionPolicyRemediationCancellationRefreshFunc(ctx context.Context, client *policyinsights.PolicyInsightsClient, id policyinsights.RemediationId) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - resp, err := client.GetAtSubscription(ctx, id.SubscriptionId, id.RemediationName) + resp, err := client.RemediationsGetAtSubscription(ctx, id) if err != nil { return nil, "", fmt.Errorf("issuing read request for %s: %+v", id.ID(), err) } - if resp.RemediationProperties == nil { + if resp.Model.Properties == nil { return nil, "", fmt.Errorf("`properties` was nil") } - if resp.RemediationProperties.ProvisioningState == nil { + if resp.Model.Properties.ProvisioningState == nil { return nil, "", fmt.Errorf("`properties.ProvisioningState` was nil") } - return resp, *resp.RemediationProperties.ProvisioningState, nil + return resp, *resp.Model.Properties.ProvisioningState, nil } } diff --git a/internal/services/policy/remediation_subscription_test.go b/internal/services/policy/remediation_subscription_test.go index b449a298e7b8..0337874b5893 100644 --- a/internal/services/policy/remediation_subscription_test.go +++ b/internal/services/policy/remediation_subscription_test.go @@ -5,10 +5,11 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/policy/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -46,20 +47,20 @@ func TestAccAzureRMSubscriptionPolicyRemediation_complete(t *testing.T) { } func (r SubscriptionPolicyRemediationResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.SubscriptionPolicyRemediationID(state.ID) + id, err := policyinsights.ParseRemediationID(state.ID) if err != nil { return nil, err } - resp, err := client.Policy.RemediationsClient.GetAtSubscription(ctx, id.SubscriptionId, id.RemediationName) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + resp, err := client.Policy.PolicyInsightsClient.RemediationsGetAtSubscription(ctx, *id) + if err != nil || resp.Model == nil { + if response.WasNotFound(resp.HttpResponse) { return utils.Bool(false), nil } return nil, fmt.Errorf("retrieving Policy Remediation %q: %+v", state.ID, err) } - return utils.Bool(resp.RemediationProperties != nil), nil + return utils.Bool(resp.Model.Properties != nil), nil } func (r SubscriptionPolicyRemediationResource) template(data acceptance.TestData) string { diff --git a/internal/services/portal/client/client.go b/internal/services/portal/client/client.go index 9920b5461d86..3c86f1bf01de 100644 --- a/internal/services/portal/client/client.go +++ b/internal/services/portal/client/client.go @@ -1,7 +1,6 @@ package client import ( - "github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal" "github.com/hashicorp/go-azure-sdk/resource-manager/portal/2019-01-01-preview/dashboard" "github.com/hashicorp/go-azure-sdk/resource-manager/portal/2019-01-01-preview/tenantconfiguration" "github.com/hashicorp/terraform-provider-azurerm/internal/common" @@ -9,7 +8,6 @@ import ( type Client struct { DashboardsClient *dashboard.DashboardClient - LegacyDashboardsClient *portal.DashboardsClient TenantConfigurationsClient *tenantconfiguration.TenantConfigurationClient } @@ -17,15 +15,11 @@ func NewClient(o *common.ClientOptions) *Client { dashboardsClient := dashboard.NewDashboardClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&dashboardsClient.Client, o.ResourceManagerAuthorizer) - legacyDashboardsClient := portal.NewDashboardsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) - o.ConfigureClient(&legacyDashboardsClient.Client, o.ResourceManagerAuthorizer) - tenantConfigurationsClient := tenantconfiguration.NewTenantConfigurationClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&tenantConfigurationsClient.Client, o.ResourceManagerAuthorizer) return &Client{ DashboardsClient: &dashboardsClient, - LegacyDashboardsClient: &legacyDashboardsClient, TenantConfigurationsClient: &tenantConfigurationsClient, } } diff --git a/internal/services/portal/legacy_dashboard_resource.go b/internal/services/portal/legacy_dashboard_resource.go index 295d47a72ba3..dcfa8c63138e 100644 --- a/internal/services/portal/legacy_dashboard_resource.go +++ b/internal/services/portal/legacy_dashboard_resource.go @@ -6,15 +6,15 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" - "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/portal/2019-01-01-preview/dashboard" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/portal/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/portal/validate" - "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" @@ -48,9 +48,9 @@ func resourceLegacyDashboard() *pluginsdk.Resource { ForceNew: true, ValidateFunc: validate.DashboardName, }, - "resource_group_name": azure.SchemaResourceGroupName(), - "location": azure.SchemaLocation(), - "tags": tags.Schema(), + "resource_group_name": commonschema.ResourceGroupName(), + "location": commonschema.Location(), + "tags": commonschema.Tags(), "dashboard_properties": { Type: pluginsdk.TypeString, Optional: true, @@ -62,39 +62,39 @@ func resourceLegacyDashboard() *pluginsdk.Resource { } func resourceLegacyDashboardCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Portal.LegacyDashboardsClient + client := meta.(*clients.Client).Portal.DashboardsClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewDashboardID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := dashboard.NewDashboardID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, id.ResourceGroup, id.Name) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for the presence of an existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_dashboard", id.ID()) } } - dashboard := portal.Dashboard{ - Location: utils.String(location.Normalize(d.Get("location").(string))), + payload := dashboard.Dashboard{ + Location: location.Normalize(d.Get("location").(string)), Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } - var dashboardProperties portal.DashboardProperties + var dashboardProperties dashboard.DashboardProperties dashboardPropsRaw := d.Get("dashboard_properties").(string) if err := json.Unmarshal([]byte(dashboardPropsRaw), &dashboardProperties); err != nil { return fmt.Errorf("parsing JSON: %+v", err) } - dashboard.DashboardProperties = &dashboardProperties + payload.Properties = &dashboardProperties - if _, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.Name, dashboard); err != nil { + if _, err := client.CreateOrUpdate(ctx, id, payload); err != nil { return fmt.Errorf("creating/updating %s %+v", id, err) } @@ -103,54 +103,59 @@ func resourceLegacyDashboardCreateUpdate(d *pluginsdk.ResourceData, meta interfa } func resourceLegacyDashboardRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Portal.LegacyDashboardsClient + client := meta.(*clients.Client).Portal.DashboardsClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.DashboardID(d.Id()) + id, err := dashboard.ParseDashboardID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[DEBUG] Dashboard %q was not found in Resource Group %q - removing from state", id.Name, id.ResourceGroup) + if response.WasNotFound(resp.HttpResponse) { + log.Printf("[DEBUG] %q was not found - removing from state", *id) d.SetId("") return nil } - return fmt.Errorf("retrieving Dashboard %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %+v", *id, err) } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*resp.Location)) - } + d.Set("name", id.DashboardName) + d.Set("resource_group_name", id.ResourceGroupName) + + if model := resp.Model; model != nil { + d.Set("location", location.Normalize(model.Location)) + + props, jsonErr := json.Marshal(model.Properties) + if jsonErr != nil { + return fmt.Errorf("parsing JSON for Dashboard Properties: %+v", jsonErr) + } + d.Set("dashboard_properties", string(props)) - props, jsonErr := json.Marshal(resp.DashboardProperties) - if jsonErr != nil { - return fmt.Errorf("parsing JSON for Dashboard Properties: %+v", jsonErr) + if err := tags.FlattenAndSet(d, model.Tags); err != nil { + return err + } } - d.Set("dashboard_properties", string(props)) - return tags.FlattenAndSet(d, resp.Tags) + return nil } func resourceLegacyDashboardDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Portal.LegacyDashboardsClient + client := meta.(*clients.Client).Portal.DashboardsClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.DashboardID(d.Id()) + id, err := dashboard.ParseDashboardID(d.Id()) if err != nil { return err } - resp, err := client.Delete(ctx, id.ResourceGroup, id.Name) + resp, err := client.Delete(ctx, *id) if err != nil { - if !response.WasNotFound(resp.Response) { - return fmt.Errorf("deleting Dashboard %q (Resource Group %q): %+v", id.Name, id.Name, err) + if !response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("deleting %s: %+v", *id, err) } } diff --git a/internal/services/portal/legacy_dashboard_resource_test.go b/internal/services/portal/legacy_dashboard_resource_test.go index 4649d0e7d5e2..f78b6e826df4 100644 --- a/internal/services/portal/legacy_dashboard_resource_test.go +++ b/internal/services/portal/legacy_dashboard_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/portal/2019-01-01-preview/dashboard" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/portal/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -44,17 +44,17 @@ func TestAccLegacyDashboard_complete(t *testing.T) { } func (LegacyDashboardResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.DashboardID(state.ID) + id, err := dashboard.ParseDashboardID(state.ID) if err != nil { return nil, err } - resp, err := clients.Portal.LegacyDashboardsClient.Get(ctx, id.ResourceGroup, id.Name) + resp, err := clients.Portal.DashboardsClient.Get(ctx, *id) if err != nil { return nil, fmt.Errorf("retrieving %s: %v", id.String(), err) } - return utils.Bool(resp.DashboardProperties != nil), nil + return utils.Bool(resp.Model != nil), nil } func (LegacyDashboardResource) basic(data acceptance.TestData) string { diff --git a/internal/services/portal/portal_tenant_configuration_resource.go b/internal/services/portal/portal_tenant_configuration_resource.go index cf4d1c9ea792..1281fa1e6cd0 100644 --- a/internal/services/portal/portal_tenant_configuration_resource.go +++ b/internal/services/portal/portal_tenant_configuration_resource.go @@ -5,12 +5,11 @@ import ( "log" "time" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/portal/parse" - "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-sdk/resource-manager/portal/2019-01-01-preview/tenantconfiguration" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/portal/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" azSchema "github.com/hashicorp/terraform-provider-azurerm/internal/tf/schema" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" diff --git a/internal/services/portal/portal_tenant_configuration_resource_test.go b/internal/services/portal/portal_tenant_configuration_resource_test.go index 18018cfea151..f64cff093006 100644 --- a/internal/services/portal/portal_tenant_configuration_resource_test.go +++ b/internal/services/portal/portal_tenant_configuration_resource_test.go @@ -5,11 +5,10 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/portal/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/portal/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/postgres/postgresql_flexible_server_configuration_resource_test.go b/internal/services/postgres/postgresql_flexible_server_configuration_resource_test.go index 9e9761df6e50..58661d87c5c0 100644 --- a/internal/services/postgres/postgresql_flexible_server_configuration_resource_test.go +++ b/internal/services/postgres/postgresql_flexible_server_configuration_resource_test.go @@ -38,6 +38,29 @@ func TestAccFlexibleServerConfiguration_backslashQuote(t *testing.T) { }) } +func TestAccFlexibleServerConfiguration_azureExtensions(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_postgresql_flexible_server_configuration", "test") + r := PostgresqlFlexibleServerConfigurationResource{} + name := "azure.extensions" + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.basic(data, name, "CUBE,CITEXT,BTREE_GIST"), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + check.That(data.ResourceName).Key("name").HasValue(name), + check.That(data.ResourceName).Key("value").HasValue("CUBE,CITEXT,BTREE_GIST"), + ), + }, + data.ImportStep(), + { + Config: r.template(data), + Check: acceptance.ComposeTestCheckFunc( + data.CheckWithClientForResource(r.checkReset(name), "azurerm_postgresql_flexible_server.test"), + ), + }, + }) +} + func TestAccFlexibleServerConfiguration_pgbouncerEnabled(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_postgresql_flexible_server_configuration", "test") r := PostgresqlFlexibleServerConfigurationResource{} diff --git a/internal/services/resource/template_deployment_common.go b/internal/services/resource/template_deployment_common.go index b4ef6f83b55b..4aa6577e7ad8 100644 --- a/internal/services/resource/template_deployment_common.go +++ b/internal/services/resource/template_deployment_common.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "net/http" + "regexp" "strings" providers "github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/resources/mgmt/resources" @@ -182,6 +183,21 @@ func deleteItemsProvisionedByTemplate(ctx context.Context, client *client.Client log.Printf("[DEBUG] Deleting Nested Resource %q..", *nestedResource.ID) future, err := resourcesClient.DeleteByID(ctx, *nestedResource.ID, resourceProviderApiVersion) + + // NOTE: resourceProviderApiVersion is gotten from one of resource types of the provider. + // When the provider has multiple resource types, it may cause API version mismatched. + // For such error, try to get available API version from error code. Ugly but this seems sufficient for now + if err != nil && strings.Contains(err.Error(), `Code="NoRegisteredProviderFound"`) { + apiPat := regexp.MustCompile(`\d{4}-\d{2}-\d{2}(-preview)*`) + matches := apiPat.FindAllStringSubmatch(err.Error(), -1) + for _, match := range matches { + if resourceProviderApiVersion != match[0] { + future, err = resourcesClient.DeleteByID(ctx, *nestedResource.ID, match[0]) + break + } + } + } + if err != nil { if resp := future.Response(); resp != nil && resp.StatusCode == http.StatusNotFound { log.Printf("[DEBUG] Nested Resource %q has been deleted.. continuing..", *nestedResource.ID) diff --git a/internal/services/securitycenter/security_center_auto_provisioning_resource_test.go b/internal/services/securitycenter/security_center_auto_provisioning_resource_test.go index d26d6b13441a..74deaee7aaba 100644 --- a/internal/services/securitycenter/security_center_auto_provisioning_resource_test.go +++ b/internal/services/securitycenter/security_center_auto_provisioning_resource_test.go @@ -5,11 +5,10 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/securitycenter/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/securitycenter/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/securitycenter/security_center_server_vulnerability_assessment_resource.go b/internal/services/securitycenter/security_center_server_vulnerability_assessment_resource.go index 321826e013d9..b18b0331a4c3 100644 --- a/internal/services/securitycenter/security_center_server_vulnerability_assessment_resource.go +++ b/internal/services/securitycenter/security_center_server_vulnerability_assessment_resource.go @@ -6,9 +6,8 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/Azure/azure-sdk-for-go/services/preview/security/mgmt/v3.0/security" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/servicebus/client/client.go b/internal/services/servicebus/client/client.go index 056875696dac..e82bcbd8961c 100644 --- a/internal/services/servicebus/client/client.go +++ b/internal/services/servicebus/client/client.go @@ -1,44 +1,67 @@ package client import ( - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/internal/common" ) type Client struct { - QueuesClient *servicebus.QueuesClient - DisasterRecoveryConfigsClient *servicebus.DisasterRecoveryConfigsClient - NamespacesClient *servicebus.NamespacesClient - TopicsClient *servicebus.TopicsClient - SubscriptionsClient *servicebus.SubscriptionsClient - SubscriptionRulesClient *servicebus.RulesClient + DisasterRecoveryConfigsClient *disasterrecoveryconfigs.DisasterRecoveryConfigsClient + NamespacesAuthClient *namespacesauthorizationrule.NamespacesAuthorizationRuleClient + NamespacesClient *namespaces.NamespacesClient + QueuesAuthClient *queuesauthorizationrule.QueuesAuthorizationRuleClient + QueuesClient *queues.QueuesClient + SubscriptionsClient *subscriptions.SubscriptionsClient + SubscriptionRulesClient *rules.RulesClient + TopicsAuthClient *topicsauthorizationrule.TopicsAuthorizationRuleClient + TopicsClient *topics.TopicsClient } func NewClient(o *common.ClientOptions) *Client { - QueuesClient := servicebus.NewQueuesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) - o.ConfigureClient(&QueuesClient.Client, o.ResourceManagerAuthorizer) - - DisasterRecoveryConfigsClient := servicebus.NewDisasterRecoveryConfigsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + DisasterRecoveryConfigsClient := disasterrecoveryconfigs.NewDisasterRecoveryConfigsClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&DisasterRecoveryConfigsClient.Client, o.ResourceManagerAuthorizer) - NamespacesClient := servicebus.NewNamespacesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + NamespacesAuthClient := namespacesauthorizationrule.NewNamespacesAuthorizationRuleClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&NamespacesAuthClient.Client, o.ResourceManagerAuthorizer) + + NamespacesClient := namespaces.NewNamespacesClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&NamespacesClient.Client, o.ResourceManagerAuthorizer) - TopicsClient := servicebus.NewTopicsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) - o.ConfigureClient(&TopicsClient.Client, o.ResourceManagerAuthorizer) + QueuesAuthClient := queuesauthorizationrule.NewQueuesAuthorizationRuleClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&QueuesAuthClient.Client, o.ResourceManagerAuthorizer) - SubscriptionsClient := servicebus.NewSubscriptionsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + QueuesClient := queues.NewQueuesClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&QueuesClient.Client, o.ResourceManagerAuthorizer) + + SubscriptionsClient := subscriptions.NewSubscriptionsClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&SubscriptionsClient.Client, o.ResourceManagerAuthorizer) - SubscriptionRulesClient := servicebus.NewRulesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + SubscriptionRulesClient := rules.NewRulesClientWithBaseURI(o.ResourceManagerEndpoint) o.ConfigureClient(&SubscriptionRulesClient.Client, o.ResourceManagerAuthorizer) + TopicsAuthClient := topicsauthorizationrule.NewTopicsAuthorizationRuleClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&TopicsAuthClient.Client, o.ResourceManagerAuthorizer) + + TopicsClient := topics.NewTopicsClientWithBaseURI(o.ResourceManagerEndpoint) + o.ConfigureClient(&TopicsClient.Client, o.ResourceManagerAuthorizer) + return &Client{ - QueuesClient: &QueuesClient, DisasterRecoveryConfigsClient: &DisasterRecoveryConfigsClient, + NamespacesAuthClient: &NamespacesAuthClient, NamespacesClient: &NamespacesClient, - TopicsClient: &TopicsClient, + QueuesAuthClient: &QueuesAuthClient, + QueuesClient: &QueuesClient, SubscriptionsClient: &SubscriptionsClient, SubscriptionRulesClient: &SubscriptionRulesClient, + TopicsAuthClient: &TopicsAuthClient, + TopicsClient: &TopicsClient, } } diff --git a/internal/services/servicebus/internal.go b/internal/services/servicebus/internal.go index 22e15c42067f..f60d399a0553 100644 --- a/internal/services/servicebus/internal.go +++ b/internal/services/servicebus/internal.go @@ -7,40 +7,42 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) -func expandAuthorizationRuleRights(d *pluginsdk.ResourceData) *[]servicebus.AccessRights { - rights := make([]servicebus.AccessRights, 0) +func expandAuthorizationRuleRights(d *pluginsdk.ResourceData) *[]namespacesauthorizationrule.AccessRights { + rights := make([]namespacesauthorizationrule.AccessRights, 0) if d.Get("listen").(bool) { - rights = append(rights, servicebus.AccessRightsListen) + rights = append(rights, namespacesauthorizationrule.AccessRightsListen) } if d.Get("send").(bool) { - rights = append(rights, servicebus.AccessRightsSend) + rights = append(rights, namespacesauthorizationrule.AccessRightsSend) } if d.Get("manage").(bool) { - rights = append(rights, servicebus.AccessRightsManage) + rights = append(rights, namespacesauthorizationrule.AccessRightsManage) } return &rights } -func flattenAuthorizationRuleRights(rights *[]servicebus.AccessRights) (listen, send, manage bool) { +func flattenAuthorizationRuleRights(rights *[]namespacesauthorizationrule.AccessRights) (listen, send, manage bool) { // zero (initial) value for a bool in go is false if rights != nil { for _, right := range *rights { switch right { - case servicebus.AccessRightsListen: + case namespacesauthorizationrule.AccessRightsListen: listen = true - case servicebus.AccessRightsSend: + case namespacesauthorizationrule.AccessRightsSend: send = true - case servicebus.AccessRightsManage: + case namespacesauthorizationrule.AccessRightsManage: manage = true default: log.Printf("[DEBUG] Unknown Authorization Rule Right '%s'", right) @@ -116,45 +118,51 @@ func authorizationRuleCustomizeDiff(ctx context.Context, d *pluginsdk.ResourceDi return nil } -func waitForPairedNamespaceReplication(ctx context.Context, meta interface{}, resourceGroup, namespaceName string, timeout time.Duration) error { +func waitForPairedNamespaceReplication(ctx context.Context, meta interface{}, id namespaces.NamespaceId, timeout time.Duration) error { namespaceClient := meta.(*clients.Client).ServiceBus.NamespacesClient - namespace, err := namespaceClient.Get(ctx, resourceGroup, namespaceName) + resp, err := namespaceClient.Get(ctx, id) - if !strings.EqualFold(string(namespace.Sku.Name), "Premium") { - return err + if model := resp.Model; model != nil { + if !strings.EqualFold(string(model.Sku.Name), "Premium") { + return err + } } disasterRecoveryClient := meta.(*clients.Client).ServiceBus.DisasterRecoveryConfigsClient - disasterRecoveryResponse, err := disasterRecoveryClient.List(ctx, resourceGroup, namespaceName) - if disasterRecoveryResponse.Values() == nil { + disasterRecoveryNamespaceId := disasterrecoveryconfigs.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + disasterRecoveryResponse, err := disasterRecoveryClient.List(ctx, disasterRecoveryNamespaceId) + + if disasterRecoveryResponse.Model == nil { return err } - if len(disasterRecoveryResponse.Values()) != 1 { + if len(*disasterRecoveryResponse.Model) != 1 { return err } - aliasName := *disasterRecoveryResponse.Values()[0].Name + aliasName := (*disasterRecoveryResponse.Model)[0].Name + + disasterRecoveryConfigId := disasterrecoveryconfigs.NewDisasterRecoveryConfigID(disasterRecoveryNamespaceId.SubscriptionId, disasterRecoveryNamespaceId.ResourceGroupName, disasterRecoveryNamespaceId.NamespaceName, *aliasName) stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{string(servicebus.ProvisioningStateDRAccepted)}, - Target: []string{string(servicebus.ProvisioningStateDRSucceeded)}, + Pending: []string{string(disasterrecoveryconfigs.ProvisioningStateDRAccepted)}, + Target: []string{string(disasterrecoveryconfigs.ProvisioningStateDRSucceeded)}, MinTimeout: 30 * time.Second, Timeout: timeout, Refresh: func() (interface{}, string, error) { - read, err := disasterRecoveryClient.Get(ctx, resourceGroup, namespaceName, aliasName) + resp, err := disasterRecoveryClient.Get(ctx, disasterRecoveryConfigId) if err != nil { - return nil, "error", fmt.Errorf("wait read Service Bus Namespace Disaster Recovery Configs %q (Namespace %q / Resource Group %q): %v", aliasName, namespaceName, resourceGroup, err) + return nil, "error", fmt.Errorf("wait read for %s: %v", disasterRecoveryConfigId, err) } - if props := read.ArmDisasterRecoveryProperties; props != nil { - if props.ProvisioningState == servicebus.ProvisioningStateDRFailed { - return read, "failed", fmt.Errorf("replication for Service Bus Namespace Disaster Recovery Configs %q (Namespace %q / Resource Group %q) failed", aliasName, namespaceName, resourceGroup) + if model := resp.Model; model != nil { + if *model.Properties.ProvisioningState == disasterrecoveryconfigs.ProvisioningStateDRFailed { + return resp, "failed", fmt.Errorf("replication for %s failed", disasterRecoveryConfigId) } - return read, string(props.ProvisioningState), nil + return resp, string(*model.Properties.ProvisioningState), nil } - return read, "nil", fmt.Errorf("waiting for replication error Service Bus Namespace Disaster Recovery Configs %q (Namespace %q / Resource Group %q): provisioning state is nil", aliasName, namespaceName, resourceGroup) + return resp, "nil", fmt.Errorf("waiting for replication error for %s: provisioning state is nil", disasterRecoveryConfigId) }, } diff --git a/internal/services/servicebus/migration/namespace_network_rule_set.go b/internal/services/servicebus/migration/namespace_network_rule_set.go index 47cd705c7cb2..6985a1d00674 100644 --- a/internal/services/servicebus/migration/namespace_network_rule_set.go +++ b/internal/services/servicebus/migration/namespace_network_rule_set.go @@ -4,7 +4,7 @@ import ( "context" "strings" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) @@ -70,7 +70,7 @@ func (NamespaceNetworkRuleSetV0ToV1) UpgradeFunc() pluginsdk.StateUpgraderFunc { oldId = strings.TrimSuffix(oldId, "/networkrulesets/default") } - id, err := parse.NamespaceID(oldId) + id, err := namespaces.ParseNamespaceID(oldId) if err != nil { return nil, err } diff --git a/internal/services/servicebus/migration/subscription.go b/internal/services/servicebus/migration/subscription.go index 3ef85891f0e3..2931abf633a5 100644 --- a/internal/services/servicebus/migration/subscription.go +++ b/internal/services/servicebus/migration/subscription.go @@ -3,7 +3,7 @@ package migration import ( "context" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) @@ -91,7 +91,7 @@ func (ServiceBusSubscriptionV0ToV1) UpgradeFunc() pluginsdk.StateUpgraderFunc { return func(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) { oldId := rawState["id"].(string) - id, err := parse.SubscriptionID(oldId) + id, err := subscriptions.ParseSubscriptions2ID(oldId) if err != nil { return nil, err } diff --git a/internal/services/servicebus/servicebus_namespace_authorization_rule_data_source.go b/internal/services/servicebus/servicebus_namespace_authorization_rule_data_source.go index 019ef7714fa8..fafe01287535 100644 --- a/internal/services/servicebus/servicebus_namespace_authorization_rule_data_source.go +++ b/internal/services/servicebus/servicebus_namespace_authorization_rule_data_source.go @@ -4,14 +4,14 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourcegroups" - + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceServiceBusNamespaceAuthorizationRule() *pluginsdk.Resource { @@ -31,7 +31,7 @@ func dataSourceServiceBusNamespaceAuthorizationRule() *pluginsdk.Resource { "namespace_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validate.NamespaceID, + ValidateFunc: namespaces.ValidateNamespaceID, AtLeastOneOf: []string{"namespace_id", "resource_group_name", "namespace_name"}, }, @@ -89,7 +89,7 @@ func dataSourceServiceBusNamespaceAuthorizationRule() *pluginsdk.Resource { } func dataSourceServiceBusNamespaceAuthorizationRuleRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.NamespacesClient + client := meta.(*clients.Client).ServiceBus.NamespacesAuthClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -97,40 +97,42 @@ func dataSourceServiceBusNamespaceAuthorizationRuleRead(d *pluginsdk.ResourceDat var resourceGroup string var namespaceName string if v, ok := d.Get("namespace_id").(string); ok && v != "" { - namespaceId, err := parse.NamespaceID(v) + namespaceId, err := namespacesauthorizationrule.ParseNamespaceID(v) if err != nil { - return fmt.Errorf("parsing topic ID %q: %+v", v, err) + return err } - resourceGroup = namespaceId.ResourceGroup - namespaceName = namespaceId.Name + resourceGroup = namespaceId.ResourceGroupName + namespaceName = namespaceId.NamespaceName } else { resourceGroup = d.Get("resource_group_name").(string) namespaceName = d.Get("namespace_name").(string) } - name := d.Get("name").(string) - id := parse.NewNamespaceAuthorizationRuleID(subscriptionId, resourceGroup, namespaceName, name) + id := namespacesauthorizationrule.NewAuthorizationRuleID(subscriptionId, resourceGroup, namespaceName, d.Get("name").(string)) - resp, err := client.GetAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.AuthorizationRuleName) + resp, err := client.NamespacesGetAuthorizationRule(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } return fmt.Errorf("retrieving %s: %+v", id, err) } - keysResp, err := client.ListKeys(ctx, id.ResourceGroup, id.NamespaceName, id.AuthorizationRuleName) + keysResp, err := client.NamespacesListKeys(ctx, id) if err != nil { return fmt.Errorf("listing keys for %s: %+v", id, err) } + if model := keysResp.Model; model != nil { + d.Set("primary_key", model.PrimaryKey) + d.Set("primary_connection_string", model.PrimaryConnectionString) + d.Set("secondary_key", model.SecondaryKey) + d.Set("secondary_connection_string", model.SecondaryConnectionString) + d.Set("primary_connection_string_alias", model.AliasPrimaryConnectionString) + d.Set("secondary_connection_string_alias", model.AliasSecondaryConnectionString) + } + d.SetId(id.ID()) - d.Set("primary_key", keysResp.PrimaryKey) - d.Set("primary_connection_string", keysResp.PrimaryConnectionString) - d.Set("secondary_key", keysResp.SecondaryKey) - d.Set("secondary_connection_string", keysResp.SecondaryConnectionString) - d.Set("primary_connection_string_alias", keysResp.AliasPrimaryConnectionString) - d.Set("secondary_connection_string_alias", keysResp.AliasSecondaryConnectionString) return nil } diff --git a/internal/services/servicebus/servicebus_namespace_authorization_rule_resource.go b/internal/services/servicebus/servicebus_namespace_authorization_rule_resource.go index 974716bd9706..3696264ad25d 100644 --- a/internal/services/servicebus/servicebus_namespace_authorization_rule_resource.go +++ b/internal/services/servicebus/servicebus_namespace_authorization_rule_resource.go @@ -2,13 +2,13 @@ package servicebus import ( "fmt" - "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -23,7 +23,7 @@ func resourceServiceBusNamespaceAuthorizationRule() *pluginsdk.Resource { Delete: resourceServiceBusNamespaceAuthorizationRuleDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.NamespaceAuthorizationRuleID(id) + _, err := namespacesauthorizationrule.ParseAuthorizationRuleID(id) return err }), @@ -54,117 +54,122 @@ func resourceServiceBusNamespaceAuthorizationRuleSchema() map[string]*pluginsdk. Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.NamespaceID, + ValidateFunc: namespaces.ValidateNamespaceID, }, }) } func resourceServiceBusNamespaceAuthorizationRuleCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.NamespacesClient + client := meta.(*clients.Client).ServiceBus.NamespacesAuthClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - log.Printf("[INFO] preparing arguments for ServiceBus Namespace Authorization Rule create/update.") - - var resourceId parse.NamespaceAuthorizationRuleId - if namespaceIdLit := d.Get("namespace_id").(string); namespaceIdLit != "" { - namespaceId, _ := parse.NamespaceID(namespaceIdLit) - resourceId = parse.NewNamespaceAuthorizationRuleID(namespaceId.SubscriptionId, namespaceId.ResourceGroup, namespaceId.Name, d.Get("name").(string)) + namespaceAuthId, err := namespacesauthorizationrule.ParseNamespaceID(d.Get("namespace_id").(string)) + if err != nil { + return err } + id := namespacesauthorizationrule.NewAuthorizationRuleID(namespaceAuthId.SubscriptionId, namespaceAuthId.ResourceGroupName, namespaceAuthId.NamespaceName, d.Get("name").(string)) + if d.IsNewResource() { - existing, err := client.GetAuthorizationRule(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.AuthorizationRuleName) + existing, err := client.NamespacesGetAuthorizationRule(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing %s: %+v", resourceId, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - return tf.ImportAsExistsError("azurerm_servicebus_namespace_authorization_rule", resourceId.ID()) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_servicebus_namespace_authorization_rule", id.ID()) } } - parameters := servicebus.SBAuthorizationRule{ - Name: utils.String(resourceId.AuthorizationRuleName), - SBAuthorizationRuleProperties: &servicebus.SBAuthorizationRuleProperties{ - Rights: expandAuthorizationRuleRights(d), + parameters := namespacesauthorizationrule.SBAuthorizationRule{ + Name: utils.String(id.AuthorizationRuleName), + Properties: &namespacesauthorizationrule.SBAuthorizationRuleProperties{ + Rights: *expandAuthorizationRuleRights(d), }, } - if _, err := client.CreateOrUpdateAuthorizationRule(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.AuthorizationRuleName, parameters); err != nil { - return fmt.Errorf("creating/updating %s: %+v", resourceId, err) + if _, err := client.NamespacesCreateOrUpdateAuthorizationRule(ctx, id, parameters); err != nil { + return fmt.Errorf("creating/updating %s: %+v", id, err) } - d.SetId(resourceId.ID()) + d.SetId(id.ID()) - if err := waitForPairedNamespaceReplication(ctx, meta, resourceId.ResourceGroup, resourceId.NamespaceName, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { - return fmt.Errorf("waiting for replication to complete for Service Bus Namespace Disaster Recovery Configs (Namespace %q / Resource Group %q): %s", resourceId.NamespaceName, resourceId.ResourceGroup, err) + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + if err := waitForPairedNamespaceReplication(ctx, meta, namespaceId, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for replication to complete for %s: %+v", id, err) } return resourceServiceBusNamespaceAuthorizationRuleRead(d, meta) } func resourceServiceBusNamespaceAuthorizationRuleRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.NamespacesClient + client := meta.(*clients.Client).ServiceBus.NamespacesAuthClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceAuthorizationRuleID(d.Id()) + id, err := namespacesauthorizationrule.ParseAuthorizationRuleID(d.Id()) if err != nil { return err } - resp, err := client.GetAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.AuthorizationRuleName) + resp, err := client.NamespacesGetAuthorizationRule(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - keysResp, err := client.ListKeys(ctx, id.ResourceGroup, id.NamespaceName, id.AuthorizationRuleName) + d.Set("name", id.AuthorizationRuleName) + d.Set("namespace_id", namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName).ID()) + + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + listen, send, manage := flattenAuthorizationRuleRights(&props.Rights) + d.Set("manage", manage) + d.Set("listen", listen) + d.Set("send", send) + } + } + + keysResp, err := client.NamespacesListKeys(ctx, *id) if err != nil { return fmt.Errorf("listing keys for %s: %+v", id, err) } - d.Set("name", id.AuthorizationRuleName) - d.Set("namespace_id", parse.NewNamespaceID(id.SubscriptionId, id.ResourceGroup, id.NamespaceName).ID()) - - if properties := resp.SBAuthorizationRuleProperties; properties != nil { - listen, send, manage := flattenAuthorizationRuleRights(properties.Rights) - d.Set("manage", manage) - d.Set("listen", listen) - d.Set("send", send) + if keysModel := keysResp.Model; keysModel != nil { + d.Set("primary_key", keysModel.PrimaryKey) + d.Set("primary_connection_string", keysModel.PrimaryConnectionString) + d.Set("secondary_key", keysModel.SecondaryKey) + d.Set("secondary_connection_string", keysModel.SecondaryConnectionString) + d.Set("primary_connection_string_alias", keysModel.AliasPrimaryConnectionString) + d.Set("secondary_connection_string_alias", keysModel.AliasSecondaryConnectionString) } - d.Set("primary_key", keysResp.PrimaryKey) - d.Set("primary_connection_string", keysResp.PrimaryConnectionString) - d.Set("secondary_key", keysResp.SecondaryKey) - d.Set("secondary_connection_string", keysResp.SecondaryConnectionString) - d.Set("primary_connection_string_alias", keysResp.AliasPrimaryConnectionString) - d.Set("secondary_connection_string_alias", keysResp.AliasSecondaryConnectionString) - return nil } func resourceServiceBusNamespaceAuthorizationRuleDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.NamespacesClient + client := meta.(*clients.Client).ServiceBus.NamespacesAuthClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceAuthorizationRuleID(d.Id()) + id, err := namespacesauthorizationrule.ParseAuthorizationRuleID(d.Id()) if err != nil { return err } - if _, err = client.DeleteAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.AuthorizationRuleName); err != nil { + if _, err = client.NamespacesDeleteAuthorizationRule(ctx, *id); err != nil { return fmt.Errorf("deleting %s: %+v", id, err) } - if err := waitForPairedNamespaceReplication(ctx, meta, id.ResourceGroup, id.NamespaceName, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { - return fmt.Errorf("waiting for replication to complete for Service Bus Namespace Disaster Recovery Configs (Namespace %q / Resource Group %q): %s", id.NamespaceName, id.ResourceGroup, err) + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + if err := waitForPairedNamespaceReplication(ctx, meta, namespaceId, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for replication to complete for %s: %+v", *id, err) } return nil diff --git a/internal/services/servicebus/servicebus_namespace_authorization_rule_resource_test.go b/internal/services/servicebus/servicebus_namespace_authorization_rule_resource_test.go index 0ae55a0204b0..8e328afcb565 100644 --- a/internal/services/servicebus/servicebus_namespace_authorization_rule_resource_test.go +++ b/internal/services/servicebus/servicebus_namespace_authorization_rule_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -103,17 +103,17 @@ func TestAccServiceBusNamespaceAuthorizationRule_requiresImport(t *testing.T) { } func (t ServiceBusNamespaceAuthorizationRuleResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.NamespaceAuthorizationRuleID(state.ID) + id, err := namespacesauthorizationrule.ParseAuthorizationRuleID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.NamespacesClient.GetAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.AuthorizationRuleName) + resp, err := clients.ServiceBus.NamespacesAuthClient.NamespacesGetAuthorizationRule(ctx, *id) if err != nil { - return nil, fmt.Errorf("reading Service Bus Name Space Authorization Rule (%s): %+v", id.String(), err) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (ServiceBusNamespaceAuthorizationRuleResource) base(data acceptance.TestData, listen, send, manage bool) string { diff --git a/internal/services/servicebus/servicebus_namespace_data_source.go b/internal/services/servicebus/servicebus_namespace_data_source.go index 78d7af144721..115a53377a9e 100644 --- a/internal/services/servicebus/servicebus_namespace_data_source.go +++ b/internal/services/servicebus/servicebus_namespace_data_source.go @@ -5,14 +5,15 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceServiceBusNamespace() *pluginsdk.Resource { @@ -82,15 +83,15 @@ func dataSourceServiceBusNamespace() *pluginsdk.Resource { func dataSourceServiceBusNamespaceRead(d *pluginsdk.ResourceData, meta interface{}) error { client := meta.(*clients.Client).ServiceBus.NamespacesClient - clientStable := meta.(*clients.Client).ServiceBus.NamespacesClient + namespaceAuthClient := meta.(*clients.Client).ServiceBus.NamespacesAuthClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id := parse.NewNamespaceID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + id := namespaces.NewNamespaceID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + resp, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } @@ -98,25 +99,31 @@ func dataSourceServiceBusNamespaceRead(d *pluginsdk.ResourceData, meta interface } d.SetId(id.ID()) - d.Set("location", location.NormalizeNilable(resp.Location)) + if model := resp.Model; model != nil { + d.Set("location", location.Normalize(model.Location)) - if sku := resp.Sku; sku != nil { - d.Set("sku", string(sku.Name)) - d.Set("capacity", sku.Capacity) - } + if sku := model.Sku; sku != nil { + d.Set("sku", string(sku.Name)) + d.Set("capacity", sku.Capacity) + } - if properties := resp.SBNamespaceProperties; properties != nil { - d.Set("zone_redundant", properties.ZoneRedundant) + if props := model.Properties; props != nil { + d.Set("zone_redundant", props.ZoneRedundant) + } } - keys, err := clientStable.ListKeys(ctx, id.ResourceGroup, id.Name, serviceBusNamespaceDefaultAuthorizationRule) + authRuleId := namespacesauthorizationrule.NewAuthorizationRuleID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, serviceBusNamespaceDefaultAuthorizationRule) + + keys, err := namespaceAuthClient.NamespacesListKeys(ctx, authRuleId) if err != nil { log.Printf("[WARN] listing default keys for %s: %+v", id, err) } else { - d.Set("default_primary_connection_string", keys.PrimaryConnectionString) - d.Set("default_secondary_connection_string", keys.SecondaryConnectionString) - d.Set("default_primary_key", keys.PrimaryKey) - d.Set("default_secondary_key", keys.SecondaryKey) + if keysModel := keys.Model; keysModel != nil { + d.Set("default_primary_connection_string", keysModel.PrimaryConnectionString) + d.Set("default_secondary_connection_string", keysModel.SecondaryConnectionString) + d.Set("default_primary_key", keysModel.PrimaryKey) + d.Set("default_secondary_key", keysModel.SecondaryKey) + } } return nil diff --git a/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_data_source.go b/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_data_source.go index 74220e7a374b..0f1c0d071c3f 100644 --- a/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_data_source.go +++ b/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_data_source.go @@ -5,14 +5,14 @@ import ( "log" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourcegroups" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" - + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" + "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceServiceBusNamespaceDisasterRecoveryConfig() *pluginsdk.Resource { @@ -32,7 +32,7 @@ func dataSourceServiceBusNamespaceDisasterRecoveryConfig() *pluginsdk.Resource { "namespace_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validate.NamespaceID, + ValidateFunc: namespaces.ValidateNamespaceID, AtLeastOneOf: []string{"namespace_id", "resource_group_name", "namespace_name"}, }, @@ -91,42 +91,50 @@ func dataSourceServiceBusNamespaceDisasterRecoveryConfigRead(d *pluginsdk.Resour var resourceGroup string var namespaceName string if v, ok := d.Get("namespace_id").(string); ok && v != "" { - namespaceId, err := parse.NamespaceID(v) + namespaceId, err := disasterrecoveryconfigs.ParseNamespaceID(v) if err != nil { return fmt.Errorf("parsing topic ID %q: %+v", v, err) } - resourceGroup = namespaceId.ResourceGroup - namespaceName = namespaceId.Name + resourceGroup = namespaceId.ResourceGroupName + namespaceName = namespaceId.NamespaceName } else { resourceGroup = d.Get("resource_group_name").(string) namespaceName = d.Get("namespace_name").(string) } - name := d.Get("name").(string) - id := parse.NewNamespaceDisasterRecoveryConfigID(subscriptionId, resourceGroup, namespaceName, name) - resp, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName) + id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID(subscriptionId, resourceGroup, namespaceName, d.Get("name").(string)) + resp, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - d.Set("name", id.DisasterRecoveryConfigName) - d.Set("resource_group_name", id.ResourceGroup) + d.Set("name", id.Alias) + d.Set("resource_group_name", id.ResourceGroupName) d.Set("namespace_name", id.NamespaceName) - d.Set("partner_namespace_id", resp.ArmDisasterRecoveryProperties.PartnerNamespace) + + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + d.Set("partner_namespace_id", props.PartnerNamespace) + } + } + d.SetId(id.ID()) - keys, err := client.ListKeys(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName, serviceBusNamespaceDefaultAuthorizationRule) + authRuleId := disasterrecoveryconfigs.NewAuthorizationRuleID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, d.Get("name").(string)) + keys, err := client.ListKeys(ctx, authRuleId) if err != nil { log.Printf("[WARN] listing default keys for %s: %+v", id, err) } else { - d.Set("primary_connection_string_alias", keys.AliasPrimaryConnectionString) - d.Set("secondary_connection_string_alias", keys.AliasSecondaryConnectionString) - d.Set("default_primary_key", keys.PrimaryKey) - d.Set("default_secondary_key", keys.SecondaryKey) + if keysModel := keys.Model; keysModel != nil { + d.Set("primary_connection_string_alias", keysModel.AliasPrimaryConnectionString) + d.Set("secondary_connection_string_alias", keysModel.AliasSecondaryConnectionString) + d.Set("default_primary_key", keysModel.PrimaryKey) + d.Set("default_secondary_key", keysModel.SecondaryKey) + } } return nil } diff --git a/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_resource.go b/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_resource.go index 2982366c816d..2593ce4314f3 100644 --- a/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_resource.go +++ b/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_resource.go @@ -8,12 +8,12 @@ import ( "strconv" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" @@ -29,7 +29,7 @@ func resourceServiceBusNamespaceDisasterRecoveryConfig() *pluginsdk.Resource { Delete: resourceServiceBusNamespaceDisasterRecoveryConfigDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.NamespaceDisasterRecoveryConfigID(id) + _, err := disasterrecoveryconfigs.ParseDisasterRecoveryConfigID(id) return err }), @@ -91,34 +91,34 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigCreate(d *pluginsdk.Resour ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - namespaceId, err := parse.NamespaceID(d.Get("primary_namespace_id").(string)) + namespaceId, err := disasterrecoveryconfigs.ParseNamespaceID(d.Get("primary_namespace_id").(string)) if err != nil { return err } partnerNamespaceId := d.Get("partner_namespace_id").(string) - id := parse.NewNamespaceDisasterRecoveryConfigID(namespaceId.SubscriptionId, namespaceId.ResourceGroup, namespaceId.Name, d.Get("name").(string)) + id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID(namespaceId.SubscriptionId, namespaceId.ResourceGroupName, namespaceId.NamespaceName, d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return tf.ImportAsExistsError("azurerm_servicebus_namespace_disaster_recovery_config", id.ID()) } } - parameters := servicebus.ArmDisasterRecovery{ - ArmDisasterRecoveryProperties: &servicebus.ArmDisasterRecoveryProperties{ + parameters := disasterrecoveryconfigs.ArmDisasterRecovery{ + Properties: &disasterrecoveryconfigs.ArmDisasterRecoveryProperties{ PartnerNamespace: utils.String(partnerNamespaceId), }, } - if _, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName, parameters); err != nil { + if _, err := client.CreateOrUpdate(ctx, id, parameters); err != nil { return fmt.Errorf("creating/updating %s: %+v", id, err) } @@ -135,7 +135,7 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigUpdate(d *pluginsdk.Resour ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceDisasterRecoveryConfigID(d.State().ID) + id, err := disasterrecoveryconfigs.ParseDisasterRecoveryConfigID(d.State().ID) if err != nil { return err } @@ -144,7 +144,7 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigUpdate(d *pluginsdk.Resour defer locks.UnlockByName(id.NamespaceName, serviceBusNamespaceResourceName) if d.HasChange("partner_namespace_id") { - if _, err := client.BreakPairing(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName); err != nil { + if _, err := client.BreakPairing(ctx, *id); err != nil { return fmt.Errorf("breaking the pairing for %s: %+v", *id, err) } if err := resourceServiceBusNamespaceDisasterRecoveryConfigWaitForState(ctx, client, *id); err != nil { @@ -152,13 +152,13 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigUpdate(d *pluginsdk.Resour } } - parameters := servicebus.ArmDisasterRecovery{ - ArmDisasterRecoveryProperties: &servicebus.ArmDisasterRecoveryProperties{ + parameters := disasterrecoveryconfigs.ArmDisasterRecovery{ + Properties: &disasterrecoveryconfigs.ArmDisasterRecoveryProperties{ PartnerNamespace: utils.String(d.Get("partner_namespace_id").(string)), }, } - if _, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName, parameters); err != nil { + if _, err := client.CreateOrUpdate(ctx, *id, parameters); err != nil { return fmt.Errorf("creating/updating %s: %+v", *id, err) } if err := resourceServiceBusNamespaceDisasterRecoveryConfigWaitForState(ctx, client, *id); err != nil { @@ -173,38 +173,44 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigRead(d *pluginsdk.Resource ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceDisasterRecoveryConfigID(d.Id()) + id, err := disasterrecoveryconfigs.ParseDisasterRecoveryConfigID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - primaryId := parse.NewNamespaceID(id.SubscriptionId, id.ResourceGroup, id.NamespaceName) + primaryId := disasterrecoveryconfigs.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) - d.Set("name", id.DisasterRecoveryConfigName) + d.Set("name", id.Alias) d.Set("primary_namespace_id", primaryId.ID()) - if props := resp.ArmDisasterRecoveryProperties; props != nil { - d.Set("partner_namespace_id", props.PartnerNamespace) + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + d.Set("partner_namespace_id", props.PartnerNamespace) + } } - keys, err := client.ListKeys(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName, serviceBusNamespaceDefaultAuthorizationRule) + authRuleId := disasterrecoveryconfigs.NewAuthorizationRuleID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.Alias) + + keys, err := client.ListKeys(ctx, authRuleId) if err != nil { log.Printf("[WARN] listing default keys for %s: %+v", id, err) } else { - d.Set("primary_connection_string_alias", keys.AliasPrimaryConnectionString) - d.Set("secondary_connection_string_alias", keys.AliasSecondaryConnectionString) - d.Set("default_primary_key", keys.PrimaryKey) - d.Set("default_secondary_key", keys.SecondaryKey) + if keysModel := keys.Model; keysModel != nil { + d.Set("primary_connection_string_alias", keysModel.AliasPrimaryConnectionString) + d.Set("secondary_connection_string_alias", keysModel.AliasSecondaryConnectionString) + d.Set("default_primary_key", keysModel.PrimaryKey) + d.Set("default_secondary_key", keysModel.SecondaryKey) + } } return nil @@ -215,17 +221,17 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigDelete(d *pluginsdk.Resour ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceDisasterRecoveryConfigID(d.Id()) + id, err := disasterrecoveryconfigs.ParseDisasterRecoveryConfigID(d.Id()) if err != nil { return err } - breakPair, err := client.BreakPairing(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName) + breakPair, err := client.BreakPairing(ctx, *id) if err != nil { return fmt.Errorf("breaking pairing %s: %+v", id, err) } - if breakPair.StatusCode != http.StatusOK { + if breakPair.HttpResponse.StatusCode != http.StatusOK { return fmt.Errorf("breaking pairing for %s: %+v", *id, err) } @@ -233,7 +239,7 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigDelete(d *pluginsdk.Resour return fmt.Errorf("waiting for the pairing to break for %s: %+v", *id, err) } - if _, err := client.Delete(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName); err != nil { + if _, err := client.Delete(ctx, *id); err != nil { return fmt.Errorf("deleting %s: %+v", *id, err) } @@ -244,15 +250,15 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigDelete(d *pluginsdk.Resour MinTimeout: 30 * time.Second, Timeout: d.Timeout(pluginsdk.TimeoutDelete), Refresh: func() (interface{}, string, error) { - resp, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return resp, strconv.Itoa(resp.StatusCode), nil + if response.WasNotFound(resp.HttpResponse) { + return resp, strconv.Itoa(resp.HttpResponse.StatusCode), nil } return nil, "nil", fmt.Errorf("retrieving %s: %+v", *id, err) } - return resp, strconv.Itoa(resp.StatusCode), nil + return resp, strconv.Itoa(resp.HttpResponse.StatusCode), nil }, } @@ -260,6 +266,7 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigDelete(d *pluginsdk.Resour return fmt.Errorf("waiting the deletion of %s: %v", *id, err) } + namespaceId := disasterrecoveryconfigs.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) // it can take some time for the name to become available again // this is mainly here to enable updating the resource in place nameFreeWait := &pluginsdk.StateChangeConf{ @@ -268,12 +275,18 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigDelete(d *pluginsdk.Resour MinTimeout: 30 * time.Second, Timeout: d.Timeout(pluginsdk.TimeoutDelete), Refresh: func() (interface{}, string, error) { - resp, err := client.CheckNameAvailabilityMethod(ctx, id.ResourceGroup, id.NamespaceName, servicebus.CheckNameAvailability{Name: utils.String(id.DisasterRecoveryConfigName)}) + resp, err := client.CheckNameAvailability(ctx, namespaceId, disasterrecoveryconfigs.CheckNameAvailability{Name: id.Alias}) if err != nil { return resp, "Error", fmt.Errorf("checking for the status of %s: %+v", *id, err) } - return resp, string(resp.Reason), nil + reason := "" + if model := resp.Model; model != nil { + if v := model.Reason; v != nil { + reason = string(*v) + } + } + return resp, reason, nil }, } @@ -284,30 +297,32 @@ func resourceServiceBusNamespaceDisasterRecoveryConfigDelete(d *pluginsdk.Resour return nil } -func resourceServiceBusNamespaceDisasterRecoveryConfigWaitForState(ctx context.Context, client *servicebus.DisasterRecoveryConfigsClient, id parse.NamespaceDisasterRecoveryConfigId) error { +func resourceServiceBusNamespaceDisasterRecoveryConfigWaitForState(ctx context.Context, client *disasterrecoveryconfigs.DisasterRecoveryConfigsClient, id disasterrecoveryconfigs.DisasterRecoveryConfigId) error { deadline, ok := ctx.Deadline() if !ok { return fmt.Errorf("context had no deadline") } stateConf := &pluginsdk.StateChangeConf{ - Pending: []string{string(servicebus.ProvisioningStateDRAccepted)}, - Target: []string{string(servicebus.ProvisioningStateDRSucceeded)}, + Pending: []string{string(disasterrecoveryconfigs.ProvisioningStateDRAccepted)}, + Target: []string{string(disasterrecoveryconfigs.ProvisioningStateDRSucceeded)}, MinTimeout: 30 * time.Second, Timeout: time.Until(deadline), Refresh: func() (interface{}, string, error) { - read, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName) + resp, err := client.Get(ctx, id) if err != nil { return nil, "error", fmt.Errorf("retrieving %s: %+v", id, err) } - if props := read.ArmDisasterRecoveryProperties; props != nil { - if props.ProvisioningState == servicebus.ProvisioningStateDRFailed { - return read, "failed", fmt.Errorf("replication Failed for %s: %+v", id, err) + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + if *props.ProvisioningState == disasterrecoveryconfigs.ProvisioningStateDRFailed { + return resp, "failed", fmt.Errorf("replication Failed for %s: %+v", id, err) + } + return resp, string(*props.ProvisioningState), nil } - return read, string(props.ProvisioningState), nil } - return read, "nil", fmt.Errorf("waiting on replication of %s: %+v", id, err) + return resp, "nil", fmt.Errorf("waiting on replication of %s: %+v", id, err) }, } diff --git a/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_test.go b/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_test.go index 48f4503b2586..5953ef7781ea 100644 --- a/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_test.go +++ b/internal/services/servicebus/servicebus_namespace_disaster_recovery_config_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -30,17 +30,17 @@ func TestAccAzureRMServiceBusNamespacePairing_basic(t *testing.T) { } func (t ServiceBusNamespaceDisasterRecoveryConfigResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.NamespaceDisasterRecoveryConfigID(state.ID) + id, err := disasterrecoveryconfigs.ParseDisasterRecoveryConfigID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.DisasterRecoveryConfigsClient.Get(ctx, id.ResourceGroup, id.NamespaceName, id.DisasterRecoveryConfigName) + resp, err := clients.ServiceBus.DisasterRecoveryConfigsClient.Get(ctx, *id) if err != nil { - return nil, fmt.Errorf("reading Service Bus NameSpace (%s): %+v", id.String(), err) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (ServiceBusNamespaceDisasterRecoveryConfigResource) basic(data acceptance.TestData) string { diff --git a/internal/services/servicebus/servicebus_namespace_network_rule_set_resource.go b/internal/services/servicebus/servicebus_namespace_network_rule_set_resource.go index 110d31510532..6e6c19d481a5 100644 --- a/internal/services/servicebus/servicebus_namespace_network_rule_set_resource.go +++ b/internal/services/servicebus/servicebus_namespace_network_rule_set_resource.go @@ -6,13 +6,12 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" validateNetwork "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/set" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" @@ -29,7 +28,7 @@ func resourceServiceBusNamespaceNetworkRuleSet() *pluginsdk.Resource { Delete: resourceServiceBusNamespaceNetworkRuleSetDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.NamespaceID(id) + _, err := namespaces.ParseNamespaceID(id) return err }), @@ -56,16 +55,16 @@ func resourceServicebusNamespaceNetworkRuleSetSchema() map[string]*pluginsdk.Sch Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.NamespaceID, + ValidateFunc: namespaces.ValidateNamespaceID, }, "default_action": { Type: pluginsdk.TypeString, Optional: true, - Default: string(servicebus.DefaultActionAllow), + Default: string(namespaces.DefaultActionAllow), ValidateFunc: validation.StringInSlice([]string{ - string(servicebus.DefaultActionAllow), - string(servicebus.DefaultActionDeny), + string(namespaces.DefaultActionAllow), + string(namespaces.DefaultActionDeny), }, false), }, @@ -118,27 +117,29 @@ func resourceServiceBusNamespaceNetworkRuleSetCreateUpdate(d *pluginsdk.Resource ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceID(d.Get("namespace_id").(string)) + id, err := namespaces.ParseNamespaceID(d.Get("namespace_id").(string)) if err != nil { return err } if d.IsNewResource() { - existing, err := client.GetNetworkRuleSet(ctx, id.ResourceGroup, id.Name) + existing, err := client.GetNetworkRuleSet(ctx, *id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("checking for the presence of existing %s: %+v", id, err) } } // This resource is unique to the corresponding service bus namespace. // It will be created automatically along with the namespace, therefore we check whether this resource is identical to a "deleted" one - if !CheckNetworkRuleNullified(existing) { - return tf.ImportAsExistsError("azurerm_servicebus_namespace_network_rule_set", id.ID()) + if model := existing.Model; model != nil { + if !CheckNetworkRuleNullified(*model) { + return tf.ImportAsExistsError("azurerm_servicebus_namespace_network_rule_set", id.ID()) + } } } - defaultAction := servicebus.DefaultAction(d.Get("default_action").(string)) + defaultAction := namespaces.DefaultAction(d.Get("default_action").(string)) vnetRule := expandServiceBusNamespaceVirtualNetworkRules(d.Get("network_rules").(*pluginsdk.Set).List()) ipRule := expandServiceBusNamespaceIPRules(d.Get("ip_rules").(*pluginsdk.Set).List()) publicNetworkAcc := "Disabled" @@ -147,21 +148,23 @@ func resourceServiceBusNamespaceNetworkRuleSetCreateUpdate(d *pluginsdk.Resource } // API doesn't accept "Deny" to be set for "default_action" if no "ip_rules" or "network_rules" is defined and returns no error message to the user - if defaultAction == servicebus.DefaultActionDeny && vnetRule == nil && ipRule == nil { + if defaultAction == namespaces.DefaultActionDeny && vnetRule == nil && ipRule == nil { return fmt.Errorf(" The default action of %s can only be set to `Allow` if no `ip_rules` or `network_rules` is set", id) } - parameters := servicebus.NetworkRuleSet{ - NetworkRuleSetProperties: &servicebus.NetworkRuleSetProperties{ - DefaultAction: defaultAction, + publicNetworkAccess := namespaces.PublicNetworkAccessFlag(publicNetworkAcc) + + parameters := namespaces.NetworkRuleSet{ + Properties: &namespaces.NetworkRuleSetProperties{ + DefaultAction: &defaultAction, VirtualNetworkRules: vnetRule, - IPRules: ipRule, - PublicNetworkAccess: servicebus.PublicNetworkAccessFlag(publicNetworkAcc), + IpRules: ipRule, + PublicNetworkAccess: &publicNetworkAccess, TrustedServiceAccessEnabled: utils.Bool(d.Get("trusted_services_allowed").(bool)), }, } - if _, err := client.CreateOrUpdateNetworkRuleSet(ctx, id.ResourceGroup, id.Name, parameters); err != nil { + if _, err := client.CreateOrUpdateNetworkRuleSet(ctx, *id, parameters); err != nil { return fmt.Errorf("creating/updating %s: %+v", id, err) } @@ -174,15 +177,15 @@ func resourceServiceBusNamespaceNetworkRuleSetRead(d *pluginsdk.ResourceData, me ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceID(d.Id()) + id, err := namespaces.ParseNamespaceID(d.Id()) if err != nil { return err } - resp, err := client.GetNetworkRuleSet(ctx, id.ResourceGroup, id.Name) + resp, err := client.GetNetworkRuleSet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[INFO] Service Bus Namespace Network Rule Set %q does not exist - removing from state", d.Id()) + if response.WasNotFound(resp.HttpResponse) { + log.Printf("%s was not found - removing from state", d.Id()) d.SetId("") return nil } @@ -190,17 +193,28 @@ func resourceServiceBusNamespaceNetworkRuleSetRead(d *pluginsdk.ResourceData, me } d.Set("namespace_id", id.ID()) - if props := resp.NetworkRuleSetProperties; props != nil { - d.Set("default_action", string(props.DefaultAction)) - d.Set("trusted_services_allowed", props.TrustedServiceAccessEnabled) - d.Set("public_network_access_enabled", strings.EqualFold(string(props.PublicNetworkAccess), "Enabled")) - if err := d.Set("network_rules", pluginsdk.NewSet(networkRuleHash, flattenServiceBusNamespaceVirtualNetworkRules(props.VirtualNetworkRules))); err != nil { - return fmt.Errorf("failed to set `network_rules`: %+v", err) - } + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + defaultAction := "" + if v := props.DefaultAction; v != nil { + defaultAction = string(*v) + } + d.Set("default_action", defaultAction) + d.Set("trusted_services_allowed", props.TrustedServiceAccessEnabled) + publicNetworkAccess := "Enabled" + if v := props.PublicNetworkAccess; v != nil { + publicNetworkAccess = string(*v) + } + d.Set("public_network_access_enabled", strings.EqualFold(publicNetworkAccess, "Enabled")) - if err := d.Set("ip_rules", flattenServiceBusNamespaceIPRules(props.IPRules)); err != nil { - return fmt.Errorf("failed to set `ip_rules`: %+v", err) + if err := d.Set("network_rules", pluginsdk.NewSet(networkRuleHash, flattenServiceBusNamespaceVirtualNetworkRules(props.VirtualNetworkRules))); err != nil { + return fmt.Errorf("failed to set `network_rules`: %+v", err) + } + + if err := d.Set("ip_rules", flattenServiceBusNamespaceIPRules(props.IpRules)); err != nil { + return fmt.Errorf("failed to set `ip_rules`: %+v", err) + } } } @@ -212,7 +226,7 @@ func resourceServiceBusNamespaceNetworkRuleSetDelete(d *pluginsdk.ResourceData, ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceID(d.Id()) + id, err := namespaces.ParseNamespaceID(d.Id()) if err != nil { return err } @@ -220,30 +234,31 @@ func resourceServiceBusNamespaceNetworkRuleSetDelete(d *pluginsdk.ResourceData, // A network rule is unique to a namespace, this rule cannot be deleted. // Therefore we here are just disabling it by setting the default_action to allow and remove all its rules and masks - parameters := servicebus.NetworkRuleSet{ - NetworkRuleSetProperties: &servicebus.NetworkRuleSetProperties{ - DefaultAction: servicebus.DefaultActionAllow, + defaultAction := namespaces.DefaultActionAllow + parameters := namespaces.NetworkRuleSet{ + Properties: &namespaces.NetworkRuleSetProperties{ + DefaultAction: &defaultAction, }, } - if _, err := client.CreateOrUpdateNetworkRuleSet(ctx, id.ResourceGroup, id.Name, parameters); err != nil { + if _, err := client.CreateOrUpdateNetworkRuleSet(ctx, *id, parameters); err != nil { return fmt.Errorf("deleting %s: %+v", *id, err) } return nil } -func expandServiceBusNamespaceVirtualNetworkRules(input []interface{}) *[]servicebus.NWRuleSetVirtualNetworkRules { +func expandServiceBusNamespaceVirtualNetworkRules(input []interface{}) *[]namespaces.NWRuleSetVirtualNetworkRules { if len(input) == 0 { return nil } - result := make([]servicebus.NWRuleSetVirtualNetworkRules, 0) + result := make([]namespaces.NWRuleSetVirtualNetworkRules, 0) for _, v := range input { raw := v.(map[string]interface{}) - result = append(result, servicebus.NWRuleSetVirtualNetworkRules{ - Subnet: &servicebus.Subnet{ - ID: utils.String(raw["subnet_id"].(string)), + result = append(result, namespaces.NWRuleSetVirtualNetworkRules{ + Subnet: &namespaces.Subnet{ + Id: raw["subnet_id"].(string), }, IgnoreMissingVnetServiceEndpoint: utils.Bool(raw["ignore_missing_vnet_service_endpoint"].(bool)), }) @@ -252,7 +267,7 @@ func expandServiceBusNamespaceVirtualNetworkRules(input []interface{}) *[]servic return &result } -func flattenServiceBusNamespaceVirtualNetworkRules(input *[]servicebus.NWRuleSetVirtualNetworkRules) []interface{} { +func flattenServiceBusNamespaceVirtualNetworkRules(input *[]namespaces.NWRuleSetVirtualNetworkRules) []interface{} { result := make([]interface{}, 0) if input == nil { return result @@ -260,8 +275,8 @@ func flattenServiceBusNamespaceVirtualNetworkRules(input *[]servicebus.NWRuleSet for _, v := range *input { subnetId := "" - if v.Subnet != nil && v.Subnet.ID != nil { - subnetId = *v.Subnet.ID + if v.Subnet != nil && v.Subnet.Id != "" { + subnetId = v.Subnet.Id } ignore := false @@ -278,31 +293,32 @@ func flattenServiceBusNamespaceVirtualNetworkRules(input *[]servicebus.NWRuleSet return result } -func expandServiceBusNamespaceIPRules(input []interface{}) *[]servicebus.NWRuleSetIPRules { +func expandServiceBusNamespaceIPRules(input []interface{}) *[]namespaces.NWRuleSetIpRules { if len(input) == 0 { return nil } - result := make([]servicebus.NWRuleSetIPRules, 0) + action := namespaces.NetworkRuleIPActionAllow + result := make([]namespaces.NWRuleSetIpRules, 0) for _, v := range input { - result = append(result, servicebus.NWRuleSetIPRules{ - IPMask: utils.String(v.(string)), - Action: servicebus.NetworkRuleIPActionAllow, + result = append(result, namespaces.NWRuleSetIpRules{ + IpMask: utils.String(v.(string)), + Action: &action, }) } return &result } -func flattenServiceBusNamespaceIPRules(input *[]servicebus.NWRuleSetIPRules) []interface{} { +func flattenServiceBusNamespaceIPRules(input *[]namespaces.NWRuleSetIpRules) []interface{} { result := make([]interface{}, 0) if input == nil || len(*input) == 0 { return result } for _, v := range *input { - if v.IPMask != nil { - result = append(result, *v.IPMask) + if v.IpMask != nil { + result = append(result, *v.IpMask) } } @@ -317,21 +333,24 @@ func networkRuleHash(input interface{}) int { return set.HashStringIgnoreCase(v["subnet_id"]) } -func CheckNetworkRuleNullified(resp servicebus.NetworkRuleSet) bool { - if resp.ID == nil || *resp.ID == "" { - return true - } - if resp.NetworkRuleSetProperties == nil { +func CheckNetworkRuleNullified(resp namespaces.NetworkRuleSet) bool { + if resp.Id == nil || *resp.Id == "" { return true } - if resp.DefaultAction != servicebus.DefaultActionAllow { - return false - } - if resp.VirtualNetworkRules != nil && len(*resp.VirtualNetworkRules) > 0 { - return false - } - if resp.IPRules != nil && len(*resp.IPRules) > 0 { - return false + + if props := resp.Properties; props != nil { + if *props.DefaultAction != namespaces.DefaultActionAllow { + return false + } + + if props.VirtualNetworkRules != nil && len(*props.VirtualNetworkRules) > 0 { + return false + } + + if props.IpRules != nil && len(*props.IpRules) > 0 { + return false + } } + return true } diff --git a/internal/services/servicebus/servicebus_namespace_network_rule_set_resource_test.go b/internal/services/servicebus/servicebus_namespace_network_rule_set_resource_test.go index 5a424eb2c481..c4a2226ab3ec 100644 --- a/internal/services/servicebus/servicebus_namespace_network_rule_set_resource_test.go +++ b/internal/services/servicebus/servicebus_namespace_network_rule_set_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -91,17 +91,17 @@ func TestAccServiceBusNamespaceNetworkRule_requiresImport(t *testing.T) { } func (t ServiceBusNamespaceNetworkRuleSetResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.NamespaceID(state.ID) + id, err := namespaces.ParseNamespaceID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.NamespacesClient.GetNetworkRuleSet(ctx, id.ResourceGroup, id.Name) + resp, err := clients.ServiceBus.NamespacesClient.GetNetworkRuleSet(ctx, *id) if err != nil { return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (r ServiceBusNamespaceNetworkRuleSetResource) basic(data acceptance.TestData) string { diff --git a/internal/services/servicebus/servicebus_namespace_resource.go b/internal/services/servicebus/servicebus_namespace_resource.go index 619952454e60..88accc246d96 100644 --- a/internal/services/servicebus/servicebus_namespace_resource.go +++ b/internal/services/servicebus/servicebus_namespace_resource.go @@ -7,19 +7,20 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" keyVaultParse "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/parse" keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tags" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" @@ -43,7 +44,7 @@ func resourceServiceBusNamespace() *pluginsdk.Resource { Delete: resourceServiceBusNamespaceDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.NamespaceID(id) + _, err := namespaces.ParseNamespaceID(id) return err }), @@ -77,9 +78,9 @@ func resourceServiceBusNamespace() *pluginsdk.Resource { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(servicebus.SkuNameBasic), - string(servicebus.SkuNameStandard), - string(servicebus.SkuNamePremium), + string(namespaces.SkuNameBasic), + string(namespaces.SkuNameStandard), + string(namespaces.SkuNamePremium), }, false), }, @@ -164,7 +165,7 @@ func resourceServiceBusNamespace() *pluginsdk.Resource { oldSku, newSku := diff.GetChange("sku") if diff.HasChange("sku") { - if strings.EqualFold(newSku.(string), string(servicebus.SkuNamePremium)) || strings.EqualFold(oldSku.(string), string(servicebus.SkuNamePremium)) { + if strings.EqualFold(newSku.(string), string(namespaces.SkuNamePremium)) || strings.EqualFold(oldSku.(string), string(namespaces.SkuNamePremium)) { log.Printf("[DEBUG] cannot migrate a namespace from or to Premium SKU") diff.ForceNew("sku") } @@ -186,130 +187,134 @@ func resourceServiceBusNamespaceCreateUpdate(d *pluginsdk.ResourceData, meta int sku := d.Get("sku").(string) t := d.Get("tags").(map[string]interface{}) - resourceId := parse.NewNamespaceID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) + id := namespaces.NewNamespaceID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string)) if d.IsNewResource() { - existing, err := client.Get(ctx, resourceId.ResourceGroup, resourceId.Name) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing %s: %+v", resourceId, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - return tf.ImportAsExistsError("azurerm_servicebus_namespace", resourceId.ID()) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_servicebus_namespace", id.ID()) } } - identity, err := expandServiceBusNamespaceIdentity(d.Get("identity").([]interface{})) + identity, err := expandSystemAndUserAssignedMap(d.Get("identity").([]interface{})) if err != nil { return fmt.Errorf("expanding `identity`: %+v", err) } - parameters := servicebus.SBNamespace{ - Location: &location, + s := namespaces.SkuTier(sku) + parameters := namespaces.SBNamespace{ + Location: location, Identity: identity, - Sku: &servicebus.SBSku{ - Name: servicebus.SkuName(sku), - Tier: servicebus.SkuTier(sku), + Sku: &namespaces.SBSku{ + Name: namespaces.SkuName(sku), + Tier: &s, }, - SBNamespaceProperties: &servicebus.SBNamespaceProperties{ + Properties: &namespaces.SBNamespaceProperties{ ZoneRedundant: utils.Bool(d.Get("zone_redundant").(bool)), Encryption: expandServiceBusNamespaceEncryption(d.Get("customer_managed_key").([]interface{})), DisableLocalAuth: utils.Bool(!d.Get("local_auth_enabled").(bool)), }, - Tags: tags.Expand(t), + Tags: expandTags(t), } if capacity := d.Get("capacity"); capacity != nil { - if !strings.EqualFold(sku, string(servicebus.SkuNamePremium)) && capacity.(int) > 0 { + if !strings.EqualFold(sku, string(namespaces.SkuNamePremium)) && capacity.(int) > 0 { return fmt.Errorf("Service Bus SKU %q only supports `capacity` of 0", sku) } - if strings.EqualFold(sku, string(servicebus.SkuNamePremium)) && capacity.(int) == 0 { + if strings.EqualFold(sku, string(namespaces.SkuNamePremium)) && capacity.(int) == 0 { return fmt.Errorf("Service Bus SKU %q only supports `capacity` of 1, 2, 4, 8 or 16", sku) } - parameters.Sku.Capacity = utils.Int32(int32(capacity.(int))) + parameters.Sku.Capacity = utils.Int64(int64(capacity.(int))) } - future, err := client.CreateOrUpdate(ctx, resourceId.ResourceGroup, resourceId.Name, parameters) - if err != nil { - return fmt.Errorf("creating/updating %s: %+v", resourceId, err) - } - - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("waiting for create/update of %s: %+v", resourceId, err) + if err := client.CreateOrUpdateThenPoll(ctx, id, parameters); err != nil { + return fmt.Errorf("creating/updating %s: %+v", id, err) } - d.SetId(resourceId.ID()) + d.SetId(id.ID()) return resourceServiceBusNamespaceRead(d, meta) } func resourceServiceBusNamespaceRead(d *pluginsdk.ResourceData, meta interface{}) error { client := meta.(*clients.Client).ServiceBus.NamespacesClient - clientStable := meta.(*clients.Client).ServiceBus.NamespacesClient + namespaceAuthClient := meta.(*clients.Client).ServiceBus.NamespacesAuthClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceID(d.Id()) + id, err := namespaces.ParseNamespaceID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.Name) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - d.Set("name", id.Name) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("location", location.NormalizeNilable(resp.Location)) + d.Set("name", id.NamespaceName) + d.Set("resource_group_name", id.ResourceGroupName) - identity, err := flattenServiceBusNamespaceIdentity(resp.Identity) - if err != nil { - return fmt.Errorf("flattening `identity`: %+v", err) - } - if err := d.Set("identity", identity); err != nil { - return fmt.Errorf("setting `identity`: %+v", err) - } + if model := resp.Model; model != nil { + d.Set("location", location.Normalize(model.Location)) - if sku := resp.Sku; sku != nil { - skuName := "" - // the Azure API is inconsistent here, so rewrite this into the casing we expect - for _, v := range servicebus.PossibleSkuNameValues() { - if strings.EqualFold(string(v), string(sku.Name)) { - skuName = string(v) - } + d.Set("tags", flattenTags(model.Tags)) + + identity, err := identity.FlattenSystemAndUserAssignedMap(model.Identity) + if err != nil { + return fmt.Errorf("flattening `identity`: %+v", err) + } + if err := d.Set("identity", identity); err != nil { + return fmt.Errorf("setting `identity`: %+v", err) } - d.Set("sku", skuName) - d.Set("capacity", sku.Capacity) - } - if properties := resp.SBNamespaceProperties; properties != nil { - d.Set("zone_redundant", properties.ZoneRedundant) - if customerManagedKey, err := flattenServiceBusNamespaceEncryption(properties.Encryption); err == nil { - d.Set("customer_managed_key", customerManagedKey) + if sku := model.Sku; sku != nil { + skuName := "" + // the Azure API is inconsistent here, so rewrite this into the casing we expect + for _, v := range namespaces.PossibleValuesForSkuName() { + if strings.EqualFold(v, string(sku.Name)) { + skuName = v + } + } + d.Set("sku", skuName) + d.Set("capacity", sku.Capacity) } - localAuthEnabled := true - if properties.DisableLocalAuth != nil { - localAuthEnabled = !*properties.DisableLocalAuth + + if props := model.Properties; model != nil { + d.Set("zone_redundant", props.ZoneRedundant) + if customerManagedKey, err := flattenServiceBusNamespaceEncryption(props.Encryption); err == nil { + d.Set("customer_managed_key", customerManagedKey) + } + localAuthEnabled := true + if props.DisableLocalAuth != nil { + localAuthEnabled = !*props.DisableLocalAuth + } + d.Set("local_auth_enabled", localAuthEnabled) } - d.Set("local_auth_enabled", localAuthEnabled) } - keys, err := clientStable.ListKeys(ctx, id.ResourceGroup, id.Name, serviceBusNamespaceDefaultAuthorizationRule) + authRuleId := namespacesauthorizationrule.NewAuthorizationRuleID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, serviceBusNamespaceDefaultAuthorizationRule) + + keys, err := namespaceAuthClient.NamespacesListKeys(ctx, authRuleId) if err != nil { log.Printf("[WARN] listing default keys for %s: %+v", id, err) } else { - d.Set("default_primary_connection_string", keys.PrimaryConnectionString) - d.Set("default_secondary_connection_string", keys.SecondaryConnectionString) - d.Set("default_primary_key", keys.PrimaryKey) - d.Set("default_secondary_key", keys.SecondaryKey) + if keysModel := keys.Model; keysModel != nil { + d.Set("default_primary_connection_string", keysModel.PrimaryConnectionString) + d.Set("default_secondary_connection_string", keysModel.SecondaryConnectionString) + d.Set("default_primary_key", keysModel.PrimaryKey) + d.Set("default_secondary_key", keysModel.SecondaryKey) + } } - - return tags.FlattenAndSet(d, resp.Tags) + return nil } func resourceServiceBusNamespaceDelete(d *pluginsdk.ResourceData, meta interface{}) error { @@ -317,94 +322,42 @@ func resourceServiceBusNamespaceDelete(d *pluginsdk.ResourceData, meta interface ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.NamespaceID(d.Id()) + id, err := namespaces.ParseNamespaceID(d.Id()) if err != nil { return err } - future, err := client.Delete(ctx, id.ResourceGroup, id.Name) - if err != nil { + if err := client.DeleteThenPoll(ctx, *id); err != nil { return fmt.Errorf("deleting %s: %+v", id, err) } - if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - if !response.WasNotFound(future.Response()) { - return fmt.Errorf("waiting for deletion of %s: %+v", id, err) - } - } - return nil } -func expandServiceBusNamespaceIdentity(input []interface{}) (*servicebus.Identity, error) { - expanded, err := identity.ExpandSystemAndUserAssignedMap(input) - if err != nil { - return nil, err - } - - out := servicebus.Identity{ - Type: servicebus.ManagedServiceIdentityType(string(expanded.Type)), - } - - if len(expanded.IdentityIds) > 0 { - out.UserAssignedIdentities = map[string]*servicebus.UserAssignedIdentity{} - for id := range expanded.IdentityIds { - out.UserAssignedIdentities[id] = &servicebus.UserAssignedIdentity{ - // intentionally empty - } - } - } - return &out, nil -} - -func expandServiceBusNamespaceEncryption(input []interface{}) *servicebus.Encryption { +func expandServiceBusNamespaceEncryption(input []interface{}) *namespaces.Encryption { if len(input) == 0 || input[0] == nil { return nil } v := input[0].(map[string]interface{}) keyId, _ := keyVaultParse.ParseOptionallyVersionedNestedItemID(v["key_vault_key_id"].(string)) - return &servicebus.Encryption{ - KeyVaultProperties: &[]servicebus.KeyVaultProperties{ + keySource := namespaces.KeySourceMicrosoftPointKeyVault + return &namespaces.Encryption{ + KeyVaultProperties: &[]namespaces.KeyVaultProperties{ { KeyName: utils.String(keyId.Name), KeyVersion: utils.String(keyId.Version), - KeyVaultURI: utils.String(keyId.KeyVaultBaseUrl), - Identity: &servicebus.UserAssignedIdentityProperties{ + KeyVaultUri: utils.String(keyId.KeyVaultBaseUrl), + Identity: &namespaces.UserAssignedIdentityProperties{ UserAssignedIdentity: utils.String(v["identity_id"].(string)), }, }, }, - KeySource: servicebus.KeySourceMicrosoftKeyVault, + KeySource: &keySource, RequireInfrastructureEncryption: utils.Bool(v["infrastructure_encryption_enabled"].(bool)), } } -func flattenServiceBusNamespaceIdentity(input *servicebus.Identity) (*[]interface{}, error) { - var transform *identity.SystemAndUserAssignedMap - - if input != nil { - transform = &identity.SystemAndUserAssignedMap{ - Type: identity.Type(string(input.Type)), - IdentityIds: make(map[string]identity.UserAssignedIdentityDetails), - } - if input.PrincipalID != nil { - transform.PrincipalId = *input.PrincipalID - } - if input.TenantID != nil { - transform.TenantId = *input.TenantID - } - for k, v := range input.UserAssignedIdentities { - transform.IdentityIds[k] = identity.UserAssignedIdentityDetails{ - ClientId: v.ClientID, - PrincipalId: v.PrincipalID, - } - } - } - - return identity.FlattenSystemAndUserAssignedMap(transform) -} - -func flattenServiceBusNamespaceEncryption(encryption *servicebus.Encryption) ([]interface{}, error) { +func flattenServiceBusNamespaceEncryption(encryption *namespaces.Encryption) ([]interface{}, error) { if encryption == nil { return []interface{}{}, nil } @@ -413,7 +366,7 @@ func flattenServiceBusNamespaceEncryption(encryption *servicebus.Encryption) ([] var identityId string if keyVaultProperties := encryption.KeyVaultProperties; keyVaultProperties != nil && len(*keyVaultProperties) != 0 { props := (*keyVaultProperties)[0] - keyVaultKeyId, err := keyVaultParse.NewNestedItemID(*props.KeyVaultURI, "keys", *props.KeyName, *props.KeyVersion) + keyVaultKeyId, err := keyVaultParse.NewNestedItemID(*props.KeyVaultUri, "keys", *props.KeyName, *props.KeyVersion) if err != nil { return nil, fmt.Errorf("parsing `key_vault_key_id`: %+v", err) } @@ -431,3 +384,44 @@ func flattenServiceBusNamespaceEncryption(encryption *servicebus.Encryption) ([] }, }, nil } + +func expandSystemAndUserAssignedMap(input []interface{}) (*identity.SystemAndUserAssignedMap, error) { + identityType := identity.TypeNone + identityIds := make(map[string]identity.UserAssignedIdentityDetails, 0) + + if len(input) > 0 { + raw := input[0].(map[string]interface{}) + typeRaw := raw["type"].(string) + if typeRaw == string(identity.TypeSystemAssigned) { + identityType = identity.TypeSystemAssigned + } + if typeRaw == string(identity.TypeSystemAssignedUserAssigned) { + identityType = identity.TypeSystemAssignedUserAssigned + } + if typeRaw == string(identity.TypeUserAssigned) { + identityType = identity.TypeUserAssigned + } + + identityIdsRaw := raw["identity_ids"].(*schema.Set).List() + for _, v := range identityIdsRaw { + identityIds[v.(string)] = identity.UserAssignedIdentityDetails{ + // intentionally empty since the expand shouldn't send these values + } + } + } + + if len(identityIds) > 0 && (identityType != identity.TypeSystemAssignedUserAssigned && identityType != identity.TypeUserAssigned) { + return nil, fmt.Errorf("`identity_ids` can only be specified when `type` is set to %q or %q", string(identity.TypeSystemAssignedUserAssigned), string(identity.TypeUserAssigned)) + } + + if len(identityIds) == 0 { + return &identity.SystemAndUserAssignedMap{ + Type: identityType, + }, nil + } + + return &identity.SystemAndUserAssignedMap{ + Type: identityType, + IdentityIds: identityIds, + }, nil +} diff --git a/internal/services/servicebus/servicebus_namespace_resource_test.go b/internal/services/servicebus/servicebus_namespace_resource_test.go index e4255698ad5f..6b910a30931d 100644 --- a/internal/services/servicebus/servicebus_namespace_resource_test.go +++ b/internal/services/servicebus/servicebus_namespace_resource_test.go @@ -6,10 +6,10 @@ import ( "regexp" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -207,17 +207,17 @@ func TestAccAzureRMServiceBusNamespace_customerManagedKey(t *testing.T) { } func (t ServiceBusNamespaceResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.NamespaceID(state.ID) + id, err := namespaces.ParseNamespaceID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.NamespacesClient.Get(ctx, id.ResourceGroup, id.Name) + resp, err := clients.ServiceBus.NamespacesClient.Get(ctx, *id) if err != nil { return nil, fmt.Errorf("reading Service Bus NameSpace (%s): %+v", id.String(), err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (ServiceBusNamespaceResource) basic(data acceptance.TestData) string { diff --git a/internal/services/servicebus/servicebus_queue_authorization_rule_data_source.go b/internal/services/servicebus/servicebus_queue_authorization_rule_data_source.go index a36230acbecd..31cb5bfeca97 100644 --- a/internal/services/servicebus/servicebus_queue_authorization_rule_data_source.go +++ b/internal/services/servicebus/servicebus_queue_authorization_rule_data_source.go @@ -4,14 +4,14 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourcegroups" - + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceServiceBusQueueAuthorizationRule() *pluginsdk.Resource { @@ -32,7 +32,7 @@ func dataSourceServiceBusQueueAuthorizationRule() *pluginsdk.Resource { "queue_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validate.QueueID, + ValidateFunc: queues.ValidateQueueID, AtLeastOneOf: []string{"queue_id", "resource_group_name", "namespace_name", "queue_name"}, }, @@ -112,7 +112,7 @@ func dataSourceServiceBusQueueAuthorizationRule() *pluginsdk.Resource { } func dataSourceServiceBusQueueAuthorizationRuleRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.QueuesClient + client := meta.(*clients.Client).ServiceBus.QueuesAuthClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -121,53 +121,57 @@ func dataSourceServiceBusQueueAuthorizationRuleRead(d *pluginsdk.ResourceData, m var nsName string var queueName string if v, ok := d.Get("queue_id").(string); ok && v != "" { - queueId, err := parse.QueueID(v) + queueId, err := queuesauthorizationrule.ParseQueueID(v) if err != nil { return fmt.Errorf("parsing topic ID %q: %+v", v, err) } - rgName = queueId.ResourceGroup + rgName = queueId.ResourceGroupName nsName = queueId.NamespaceName - queueName = queueId.Name + queueName = queueId.QueueName } else { rgName = d.Get("resource_group_name").(string) nsName = d.Get("namespace_name").(string) queueName = d.Get("queue_name").(string) } - id := parse.NewQueueAuthorizationRuleID(subscriptionId, rgName, nsName, queueName, d.Get("name").(string)) - resp, err := client.GetAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.QueueName, id.AuthorizationRuleName) + id := queuesauthorizationrule.NewQueueAuthorizationRuleID(subscriptionId, rgName, nsName, queueName, d.Get("name").(string)) + resp, err := client.QueuesGetAuthorizationRule(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } return fmt.Errorf("retrieving %s: %+v", id, err) } - keysResp, err := client.ListKeys(ctx, id.ResourceGroup, id.NamespaceName, id.QueueName, id.AuthorizationRuleName) - if err != nil { - return fmt.Errorf("listing keys for %s: %+v", id, err) - } - d.SetId(id.ID()) d.Set("name", id.AuthorizationRuleName) d.Set("queue_name", id.QueueName) d.Set("namespace_name", id.NamespaceName) - d.Set("resource_group_name", id.ResourceGroup) - d.Set("queue_id", parse.NewQueueID(id.SubscriptionId, id.ResourceGroup, id.NamespaceName, id.QueueName).ID()) - - if properties := resp.SBAuthorizationRuleProperties; properties != nil { - listen, send, manage := flattenAuthorizationRuleRights(properties.Rights) - d.Set("listen", listen) - d.Set("send", send) - d.Set("manage", manage) + d.Set("resource_group_name", id.ResourceGroupName) + d.Set("queue_id", queuesauthorizationrule.NewQueueID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.QueueName).ID()) + + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + listen, send, manage := flattenQueueAuthorizationRuleRights(&props.Rights) + d.Set("manage", manage) + d.Set("listen", listen) + d.Set("send", send) + } } - d.Set("primary_key", keysResp.PrimaryKey) - d.Set("primary_connection_string", keysResp.PrimaryConnectionString) - d.Set("secondary_key", keysResp.SecondaryKey) - d.Set("secondary_connection_string", keysResp.SecondaryConnectionString) - d.Set("primary_connection_string_alias", keysResp.AliasPrimaryConnectionString) - d.Set("secondary_connection_string_alias", keysResp.AliasSecondaryConnectionString) + keysResp, err := client.QueuesListKeys(ctx, id) + if err != nil { + return fmt.Errorf("listing keys for %s: %+v", id, err) + } + + if keysModel := keysResp.Model; keysModel != nil { + d.Set("primary_key", keysModel.PrimaryKey) + d.Set("primary_connection_string", keysModel.PrimaryConnectionString) + d.Set("secondary_key", keysModel.SecondaryKey) + d.Set("secondary_connection_string", keysModel.SecondaryConnectionString) + d.Set("primary_connection_string_alias", keysModel.AliasPrimaryConnectionString) + d.Set("secondary_connection_string_alias", keysModel.AliasSecondaryConnectionString) + } return nil } diff --git a/internal/services/servicebus/servicebus_queue_authorization_rule_resource.go b/internal/services/servicebus/servicebus_queue_authorization_rule_resource.go index 9004ea433a48..f8291ea0ca10 100644 --- a/internal/services/servicebus/servicebus_queue_authorization_rule_resource.go +++ b/internal/services/servicebus/servicebus_queue_authorization_rule_resource.go @@ -5,10 +5,12 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -23,7 +25,7 @@ func resourceServiceBusQueueAuthorizationRule() *pluginsdk.Resource { Delete: resourceServiceBusQueueAuthorizationRuleDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.QueueAuthorizationRuleID(id) + _, err := queuesauthorizationrule.ParseQueueAuthorizationRuleID(id) return err }), @@ -54,70 +56,69 @@ func resourceServiceBusqueueAuthorizationRuleSchema() map[string]*pluginsdk.Sche Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.QueueID, + ValidateFunc: queues.ValidateQueueID, }, }) } func resourceServiceBusQueueAuthorizationRuleCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.QueuesClient + client := meta.(*clients.Client).ServiceBus.QueuesAuthClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - log.Printf("[INFO] preparing arguments for ServiceBus Queue Authorization Rule creation.") - - var resourceId parse.QueueAuthorizationRuleId - if queueIdLit := d.Get("queue_id").(string); queueIdLit != "" { - queueId, _ := parse.QueueID(queueIdLit) - resourceId = parse.NewQueueAuthorizationRuleID(queueId.SubscriptionId, queueId.ResourceGroup, queueId.NamespaceName, queueId.Name, d.Get("name").(string)) + queueId, err := queuesauthorizationrule.ParseQueueID(d.Get("queue_id").(string)) + if err != nil { + return err } + id := queuesauthorizationrule.NewQueueAuthorizationRuleID(queueId.SubscriptionId, queueId.ResourceGroupName, queueId.NamespaceName, queueId.QueueName, d.Get("name").(string)) + if d.IsNewResource() { - existing, err := client.GetAuthorizationRule(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.QueueName, resourceId.AuthorizationRuleName) + existing, err := client.QueuesGetAuthorizationRule(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing %s: %+v", resourceId, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - return tf.ImportAsExistsError("azurerm_servicebus_queue_authorization_rule", resourceId.ID()) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_servicebus_queue_authorization_rule", id.ID()) } } - parameters := servicebus.SBAuthorizationRule{ - Name: utils.String(resourceId.AuthorizationRuleName), - SBAuthorizationRuleProperties: &servicebus.SBAuthorizationRuleProperties{ - Rights: expandAuthorizationRuleRights(d), + parameters := queuesauthorizationrule.SBAuthorizationRule{ + Name: utils.String(id.AuthorizationRuleName), + Properties: &queuesauthorizationrule.SBAuthorizationRuleProperties{ + Rights: *expandQueueAuthorizationRuleRights(d), }, } - if _, err := client.CreateOrUpdateAuthorizationRule(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.QueueName, resourceId.AuthorizationRuleName, parameters); err != nil { - return fmt.Errorf("creating/updating %s: %+v", resourceId, err) + if _, err := client.QueuesCreateOrUpdateAuthorizationRule(ctx, id, parameters); err != nil { + return fmt.Errorf("creating/updating %s: %+v", id, err) } - d.SetId(resourceId.ID()) - - if err := waitForPairedNamespaceReplication(ctx, meta, resourceId.ResourceGroup, resourceId.NamespaceName, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { - return fmt.Errorf("waiting for replication to complete for Service Bus Namespace Disaster Recovery Configs (Namespace %q / Resource Group %q): %s", resourceId.NamespaceName, resourceId.ResourceGroup, err) + d.SetId(id.ID()) + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + if err := waitForPairedNamespaceReplication(ctx, meta, namespaceId, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for replication to complete for %s: %+v", id, err) } return resourceServiceBusQueueAuthorizationRuleRead(d, meta) } func resourceServiceBusQueueAuthorizationRuleRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.QueuesClient + client := meta.(*clients.Client).ServiceBus.QueuesAuthClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.QueueAuthorizationRuleID(d.Id()) + id, err := queuesauthorizationrule.ParseQueueAuthorizationRuleID(d.Id()) if err != nil { return err } - resp, err := client.GetAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.QueueName, id.AuthorizationRuleName) + resp, err := client.QueuesGetAuthorizationRule(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } @@ -125,48 +126,92 @@ func resourceServiceBusQueueAuthorizationRuleRead(d *pluginsdk.ResourceData, met return fmt.Errorf("retrieving %s: %+v", id, err) } - keysResp, err := client.ListKeys(ctx, id.ResourceGroup, id.NamespaceName, id.QueueName, id.AuthorizationRuleName) + d.Set("name", id.AuthorizationRuleName) + d.Set("queue_id", queuesauthorizationrule.NewQueueID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.QueueName).ID()) + + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + listen, send, manage := flattenQueueAuthorizationRuleRights(&props.Rights) + d.Set("manage", manage) + d.Set("listen", listen) + d.Set("send", send) + } + } + + keysResp, err := client.QueuesListKeys(ctx, *id) if err != nil { return fmt.Errorf("listing keys for %s: %+v", id, err) } - d.Set("name", id.AuthorizationRuleName) - d.Set("queue_id", parse.NewQueueID(id.SubscriptionId, id.ResourceGroup, id.NamespaceName, id.QueueName).ID()) - - if properties := resp.SBAuthorizationRuleProperties; properties != nil { - listen, send, manage := flattenAuthorizationRuleRights(properties.Rights) - d.Set("manage", manage) - d.Set("listen", listen) - d.Set("send", send) + if keysModel := keysResp.Model; keysModel != nil { + d.Set("primary_key", keysModel.PrimaryKey) + d.Set("primary_connection_string", keysModel.PrimaryConnectionString) + d.Set("secondary_key", keysModel.SecondaryKey) + d.Set("secondary_connection_string", keysModel.SecondaryConnectionString) + d.Set("primary_connection_string_alias", keysModel.AliasPrimaryConnectionString) + d.Set("secondary_connection_string_alias", keysModel.AliasSecondaryConnectionString) } - d.Set("primary_key", keysResp.PrimaryKey) - d.Set("primary_connection_string", keysResp.PrimaryConnectionString) - d.Set("secondary_key", keysResp.SecondaryKey) - d.Set("secondary_connection_string", keysResp.SecondaryConnectionString) - d.Set("primary_connection_string_alias", keysResp.AliasPrimaryConnectionString) - d.Set("secondary_connection_string_alias", keysResp.AliasSecondaryConnectionString) - return nil } func resourceServiceBusQueueAuthorizationRuleDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.QueuesClient + client := meta.(*clients.Client).ServiceBus.QueuesAuthClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.QueueAuthorizationRuleID(d.Id()) + id, err := queuesauthorizationrule.ParseQueueAuthorizationRuleID(d.Id()) if err != nil { return err } - if _, err = client.DeleteAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.QueueName, id.AuthorizationRuleName); err != nil { + if _, err = client.QueuesDeleteAuthorizationRule(ctx, *id); err != nil { return fmt.Errorf("deleting %s: %+v", id, err) } - if err := waitForPairedNamespaceReplication(ctx, meta, id.ResourceGroup, id.NamespaceName, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { - return fmt.Errorf("waiting for replication to complete for Service Bus Namespace Disaster Recovery Configs (Namespace %q / Resource Group %q): %s", id.NamespaceName, id.ResourceGroup, err) + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + if err := waitForPairedNamespaceReplication(ctx, meta, namespaceId, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for replication to complete for %s: %+v", *id, err) } return nil } + +func expandQueueAuthorizationRuleRights(d *pluginsdk.ResourceData) *[]queuesauthorizationrule.AccessRights { + rights := make([]queuesauthorizationrule.AccessRights, 0) + + if d.Get("listen").(bool) { + rights = append(rights, queuesauthorizationrule.AccessRightsListen) + } + + if d.Get("send").(bool) { + rights = append(rights, queuesauthorizationrule.AccessRightsSend) + } + + if d.Get("manage").(bool) { + rights = append(rights, queuesauthorizationrule.AccessRightsManage) + } + + return &rights +} + +func flattenQueueAuthorizationRuleRights(rights *[]queuesauthorizationrule.AccessRights) (listen, send, manage bool) { + // zero (initial) value for a bool in go is false + + if rights != nil { + for _, right := range *rights { + switch right { + case queuesauthorizationrule.AccessRightsListen: + listen = true + case queuesauthorizationrule.AccessRightsSend: + send = true + case queuesauthorizationrule.AccessRightsManage: + manage = true + default: + log.Printf("[DEBUG] Unknown Authorization Rule Right '%s'", right) + } + } + } + + return listen, send, manage +} diff --git a/internal/services/servicebus/servicebus_queue_authorization_rule_resource_test.go b/internal/services/servicebus/servicebus_queue_authorization_rule_resource_test.go index 3f3b4e22ec31..3bccc722d906 100644 --- a/internal/services/servicebus/servicebus_queue_authorization_rule_resource_test.go +++ b/internal/services/servicebus/servicebus_queue_authorization_rule_resource_test.go @@ -6,10 +6,10 @@ import ( "strconv" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -135,17 +135,17 @@ func TestAccServiceBusQueueAuthorizationRule_withAliasConnectionString(t *testin } func (t ServiceBusQueueAuthorizationRuleResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.QueueAuthorizationRuleID(state.ID) + id, err := queuesauthorizationrule.ParseQueueAuthorizationRuleID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.QueuesClient.GetAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.QueueName, id.AuthorizationRuleName) + resp, err := clients.ServiceBus.QueuesAuthClient.QueuesGetAuthorizationRule(ctx, *id) if err != nil { - return nil, fmt.Errorf("reading Service Bus NameSpace Queue Authorization Rule (%s): %+v", id.String(), err) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (ServiceBusQueueAuthorizationRuleResource) base(data acceptance.TestData, listen, send, manage bool) string { diff --git a/internal/services/servicebus/servicebus_queue_data_source.go b/internal/services/servicebus/servicebus_queue_data_source.go index b90bc5b3a9bb..1372bce0ce03 100644 --- a/internal/services/servicebus/servicebus_queue_data_source.go +++ b/internal/services/servicebus/servicebus_queue_data_source.go @@ -4,16 +4,15 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourcegroups" - - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" azValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceServiceBusQueue() *pluginsdk.Resource { @@ -34,7 +33,7 @@ func dataSourceServiceBusQueue() *pluginsdk.Resource { "namespace_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validate.NamespaceID, + ValidateFunc: namespaces.ValidateNamespaceID, AtLeastOneOf: []string{"namespace_id", "resource_group_name", "namespace_name"}, }, @@ -136,71 +135,62 @@ func dataSourceServiceBusQueue() *pluginsdk.Resource { func dataSourceServiceBusQueueRead(d *pluginsdk.ResourceData, meta interface{}) error { client := meta.(*clients.Client).ServiceBus.QueuesClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) - subscriptionId := meta.(*clients.Client).Account.SubscriptionId defer cancel() - name := d.Get("name").(string) - - var resourceGroup string - var namespaceName string - if v, ok := d.Get("namespace_id").(string); ok && v != "" { - namespaceId, err := parse.NamespaceID(v) - if err != nil { - return fmt.Errorf("parsing topic ID %q: %+v", v, err) - } - resourceGroup = namespaceId.ResourceGroup - namespaceName = namespaceId.Name - } else { - resourceGroup = d.Get("resource_group_name").(string) - namespaceName = d.Get("namespace_name").(string) + namespaceId, err := namespaces.ParseNamespaceID(d.Get("namespace_id").(string)) + if err != nil { + return err } - id := parse.NewQueueID(subscriptionId, resourceGroup, namespaceName, name) - resp, err := client.Get(ctx, resourceGroup, namespaceName, name) + id := queues.NewQueueID(namespaceId.SubscriptionId, namespaceId.ResourceGroupName, namespaceId.NamespaceName, d.Get("name").(string)) + + resp, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Service Bus Queue %q was not found in Resource Group %q Namespace %q", name, resourceGroup, namespaceName) + if response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("%s was not found", id) } - return fmt.Errorf("making Read request on Azure Service Bus Queue %q in Resource Group %q Namespace %q: %v", name, resourceGroup, namespaceName, err) + return fmt.Errorf("retrieving %s: %v", id, err) } d.SetId(id.ID()) - if props := resp.SBQueueProperties; props != nil { - d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) - d.Set("dead_lettering_on_message_expiration", props.DeadLetteringOnMessageExpiration) - d.Set("default_message_ttl", props.DefaultMessageTimeToLive) - d.Set("duplicate_detection_history_time_window", props.DuplicateDetectionHistoryTimeWindow) - d.Set("enable_batched_operations", props.EnableBatchedOperations) - d.Set("enable_express", props.EnableExpress) - d.Set("enable_partitioning", props.EnablePartitioning) - d.Set("forward_dead_lettered_messages_to", props.ForwardDeadLetteredMessagesTo) - d.Set("forward_to", props.ForwardTo) - d.Set("lock_duration", props.LockDuration) - d.Set("max_delivery_count", props.MaxDeliveryCount) - d.Set("requires_duplicate_detection", props.RequiresDuplicateDetection) - d.Set("requires_session", props.RequiresSession) - d.Set("status", props.Status) - - if apiMaxSizeInMegabytes := props.MaxSizeInMegabytes; apiMaxSizeInMegabytes != nil { - maxSizeInMegabytes := int(*apiMaxSizeInMegabytes) - - // If the queue is NOT in a premium namespace (ie. it is Basic or Standard) and partitioning is enabled - // then the max size returned by the API will be 16 times greater than the value set. - if *props.EnablePartitioning { - namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient - namespace, err := namespacesClient.Get(ctx, resourceGroup, namespaceName) - if err != nil { - return err + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) + d.Set("dead_lettering_on_message_expiration", props.DeadLetteringOnMessageExpiration) + d.Set("default_message_ttl", props.DefaultMessageTimeToLive) + d.Set("duplicate_detection_history_time_window", props.DuplicateDetectionHistoryTimeWindow) + d.Set("enable_batched_operations", props.EnableBatchedOperations) + d.Set("enable_express", props.EnableExpress) + d.Set("enable_partitioning", props.EnablePartitioning) + d.Set("forward_dead_lettered_messages_to", props.ForwardDeadLetteredMessagesTo) + d.Set("forward_to", props.ForwardTo) + d.Set("lock_duration", props.LockDuration) + d.Set("max_delivery_count", props.MaxDeliveryCount) + d.Set("requires_duplicate_detection", props.RequiresDuplicateDetection) + d.Set("requires_session", props.RequiresSession) + d.Set("status", props.Status) + + if apiMaxSizeInMegabytes := props.MaxSizeInMegabytes; apiMaxSizeInMegabytes != nil { + maxSizeInMegabytes := int(*apiMaxSizeInMegabytes) + + // If the queue is NOT in a premium namespace (ie. it is Basic or Standard) and partitioning is enabled + // then the max size returned by the API will be 16 times greater than the value set. + if *props.EnablePartitioning { + namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient + namespace, err := namespacesClient.Get(ctx, *namespaceId) + if err != nil { + return err + } + + if nsModel := namespace.Model; nsModel != nil && nsModel.Sku.Name != namespaces.SkuNamePremium { + const partitionCount = 16 + maxSizeInMegabytes = int(*apiMaxSizeInMegabytes / partitionCount) + } } - if namespace.Sku.Name != servicebus.SkuNamePremium { - const partitionCount = 16 - maxSizeInMegabytes = int(*apiMaxSizeInMegabytes / partitionCount) - } + d.Set("max_size_in_megabytes", maxSizeInMegabytes) } - - d.Set("max_size_in_megabytes", maxSizeInMegabytes) } } diff --git a/internal/services/servicebus/servicebus_queue_resource.go b/internal/services/servicebus/servicebus_queue_resource.go index 11b4f5cf883e..a64a94ada41b 100644 --- a/internal/services/servicebus/servicebus_queue_resource.go +++ b/internal/services/servicebus/servicebus_queue_resource.go @@ -2,14 +2,14 @@ package servicebus import ( "fmt" - "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" azValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" @@ -25,7 +25,7 @@ func resourceServiceBusQueue() *pluginsdk.Resource { Delete: resourceServiceBusQueueDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.QueueID(id) + _, err := queues.ParseQueueID(id) return err }), @@ -54,7 +54,7 @@ func resourceServicebusQueueSchema() map[string]*pluginsdk.Schema { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: azValidate.NamespaceID, + ValidateFunc: namespaces.ValidateNamespaceID, }, // Optional @@ -163,16 +163,16 @@ func resourceServicebusQueueSchema() map[string]*pluginsdk.Schema { "status": { Type: pluginsdk.TypeString, Optional: true, - Default: string(servicebus.EntityStatusActive), + Default: string(queues.EntityStatusActive), ValidateFunc: validation.StringInSlice([]string{ - string(servicebus.EntityStatusActive), - string(servicebus.EntityStatusCreating), - string(servicebus.EntityStatusDeleting), - string(servicebus.EntityStatusDisabled), - string(servicebus.EntityStatusReceiveDisabled), - string(servicebus.EntityStatusRenaming), - string(servicebus.EntityStatusSendDisabled), - string(servicebus.EntityStatusUnknown), + string(queues.EntityStatusActive), + string(queues.EntityStatusCreating), + string(queues.EntityStatusDeleting), + string(queues.EntityStatusDisabled), + string(queues.EntityStatusReceiveDisabled), + string(queues.EntityStatusRenaming), + string(queues.EntityStatusSendDisabled), + string(queues.EntityStatusUnknown), }, false), }, } @@ -182,103 +182,120 @@ func resourceServiceBusQueueCreateUpdate(d *pluginsdk.ResourceData, meta interfa client := meta.(*clients.Client).ServiceBus.QueuesClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - log.Printf("[INFO] preparing arguments for ServiceBus Queue creation/update.") - var resourceId parse.QueueId - if namespaceIdLit := d.Get("namespace_id").(string); namespaceIdLit != "" { - namespaceId, _ := parse.NamespaceID(namespaceIdLit) - resourceId = parse.NewQueueID(namespaceId.SubscriptionId, namespaceId.ResourceGroup, namespaceId.Name, d.Get("name").(string)) + namespaceId, err := namespaces.ParseNamespaceID(d.Get("namespace_id").(string)) + if err != nil { + return err } - deadLetteringOnMessageExpiration := d.Get("dead_lettering_on_message_expiration").(bool) - enableBatchedOperations := d.Get("enable_batched_operations").(bool) - enableExpress := d.Get("enable_express").(bool) - enablePartitioning := d.Get("enable_partitioning").(bool) - maxDeliveryCount := int32(d.Get("max_delivery_count").(int)) - maxSizeInMegabytes := int32(d.Get("max_size_in_megabytes").(int)) - requiresDuplicateDetection := d.Get("requires_duplicate_detection").(bool) - requiresSession := d.Get("requires_session").(bool) - status := servicebus.EntityStatus(d.Get("status").(string)) + id := queues.NewQueueID(namespaceId.SubscriptionId, namespaceId.ResourceGroupName, namespaceId.NamespaceName, d.Get("name").(string)) + + isPartitioningEnabled := false + if d.HasChange("enable_partitioning") { + existingQueue, err := client.Get(ctx, id) + if err != nil { + if !response.WasNotFound(existingQueue.HttpResponse) { + return fmt.Errorf("retrieving %s: %+v", id, err) + } + } + + if model := existingQueue.Model; model != nil { + if props := model.Properties; props != nil { + if model.Id != nil && props.EnablePartitioning != nil && *props.EnablePartitioning { + isPartitioningEnabled = true + } + } + } + } if d.IsNewResource() { - existing, err := client.Get(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.Name) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of %s: %+v", resourceId, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - return tf.ImportAsExistsError("azurerm_servicebus_queue", resourceId.ID()) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_servicebus_queue", id.ID()) } } - parameters := servicebus.SBQueue{ - Name: utils.String(resourceId.Name), - SBQueueProperties: &servicebus.SBQueueProperties{ - DeadLetteringOnMessageExpiration: &deadLetteringOnMessageExpiration, - EnableBatchedOperations: &enableBatchedOperations, - EnableExpress: &enableExpress, - EnablePartitioning: &enablePartitioning, - MaxDeliveryCount: &maxDeliveryCount, - MaxSizeInMegabytes: &maxSizeInMegabytes, - RequiresDuplicateDetection: &requiresDuplicateDetection, - RequiresSession: &requiresSession, - Status: status, + status := queues.EntityStatus(d.Get("status").(string)) + parameters := queues.SBQueue{ + Name: utils.String(id.QueueName), + Properties: &queues.SBQueueProperties{ + DeadLetteringOnMessageExpiration: utils.Bool(d.Get("dead_lettering_on_message_expiration").(bool)), + EnableBatchedOperations: utils.Bool(d.Get("enable_batched_operations").(bool)), + EnableExpress: utils.Bool(d.Get("enable_express").(bool)), + EnablePartitioning: utils.Bool(d.Get("enable_partitioning").(bool)), + MaxDeliveryCount: utils.Int64(int64(d.Get("max_delivery_count").(int))), + MaxSizeInMegabytes: utils.Int64(int64(d.Get("max_size_in_megabytes").(int))), + RequiresDuplicateDetection: utils.Bool(d.Get("requires_duplicate_detection").(bool)), + RequiresSession: utils.Bool(d.Get("requires_session").(bool)), + Status: &status, }, } if autoDeleteOnIdle := d.Get("auto_delete_on_idle").(string); autoDeleteOnIdle != "" { - parameters.SBQueueProperties.AutoDeleteOnIdle = &autoDeleteOnIdle + parameters.Properties.AutoDeleteOnIdle = &autoDeleteOnIdle } if defaultMessageTTL := d.Get("default_message_ttl").(string); defaultMessageTTL != "" { - parameters.SBQueueProperties.DefaultMessageTimeToLive = &defaultMessageTTL + parameters.Properties.DefaultMessageTimeToLive = &defaultMessageTTL } if duplicateDetectionHistoryTimeWindow := d.Get("duplicate_detection_history_time_window").(string); duplicateDetectionHistoryTimeWindow != "" { - parameters.SBQueueProperties.DuplicateDetectionHistoryTimeWindow = &duplicateDetectionHistoryTimeWindow + parameters.Properties.DuplicateDetectionHistoryTimeWindow = &duplicateDetectionHistoryTimeWindow } if forwardDeadLetteredMessagesTo := d.Get("forward_dead_lettered_messages_to").(string); forwardDeadLetteredMessagesTo != "" { - parameters.SBQueueProperties.ForwardDeadLetteredMessagesTo = &forwardDeadLetteredMessagesTo + parameters.Properties.ForwardDeadLetteredMessagesTo = &forwardDeadLetteredMessagesTo } if forwardTo := d.Get("forward_to").(string); forwardTo != "" { - parameters.SBQueueProperties.ForwardTo = &forwardTo + parameters.Properties.ForwardTo = &forwardTo } if lockDuration := d.Get("lock_duration").(string); lockDuration != "" { - parameters.SBQueueProperties.LockDuration = &lockDuration + parameters.Properties.LockDuration = &lockDuration } // We need to retrieve the namespace because Premium namespace works differently from Basic and Standard, // so it needs different rules applied to it. namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient - namespace, err := namespacesClient.Get(ctx, resourceId.ResourceGroup, resourceId.NamespaceName) + namespace, err := namespacesClient.Get(ctx, *namespaceId) if err != nil { - return fmt.Errorf("retrieving ServiceBus Namespace %q (Resource Group %q): %+v", resourceId.NamespaceName, resourceId.ResourceGroup, err) + return fmt.Errorf("retrieving %s: %+v", *namespaceId, err) } + var sku namespaces.SkuName + if nsModel := namespace.Model; nsModel != nil { + sku = nsModel.Sku.Name + } // Enforce Premium namespace to have Express Entities disabled in Terraform since they are not supported for // Premium SKU. - if namespace.Sku.Name == servicebus.SkuNamePremium && d.Get("enable_express").(bool) { - return fmt.Errorf("ServiceBus Queue %q does not support Express Entities in Premium SKU and must be disabled", resourceId.Name) + if sku == namespaces.SkuNamePremium && d.Get("enable_express").(bool) { + return fmt.Errorf("%s does not support Express Entities in Premium SKU and must be disabled", id) + } + + if sku == namespaces.SkuNamePremium && d.Get("enable_partitioning").(bool) && !isPartitioningEnabled { + return fmt.Errorf("partitioning Entities is not supported in Premium SKU and must be disabled") } // output of `max_message_size_in_kilobytes` is also set in non-Premium namespaces, with a value of 256 if v, ok := d.GetOk("max_message_size_in_kilobytes"); ok && v.(int) != 256 { - if namespace.Sku.Name != servicebus.SkuNamePremium { - return fmt.Errorf("ServiceBus Queue %q does not support input on `max_message_size_in_kilobytes` in %s SKU and should be removed", resourceId.Name, namespace.Sku.Name) + if sku != namespaces.SkuNamePremium { + return fmt.Errorf("%s does not support input on `max_message_size_in_kilobytes` in %s SKU and should be removed", id, sku) } - parameters.SBQueueProperties.MaxMessageSizeInKilobytes = utils.Int64(int64(v.(int))) + parameters.Properties.MaxMessageSizeInKilobytes = utils.Int64(int64(v.(int))) } - if _, err = client.CreateOrUpdate(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.Name, parameters); err != nil { + if _, err = client.CreateOrUpdate(ctx, id, parameters); err != nil { return err } - d.SetId(resourceId.ID()) + d.SetId(id.ID()) return resourceServiceBusQueueRead(d, meta) } @@ -287,62 +304,65 @@ func resourceServiceBusQueueRead(d *pluginsdk.ResourceData, meta interface{}) er ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.QueueID(d.Id()) + id, err := queues.ParseQueueID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.Name) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - d.Set("name", id.Name) - d.Set("namespace_id", parse.NewNamespaceID(id.SubscriptionId, id.ResourceGroup, id.NamespaceName).ID()) - - if props := resp.SBQueueProperties; props != nil { - d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) - d.Set("dead_lettering_on_message_expiration", props.DeadLetteringOnMessageExpiration) - d.Set("default_message_ttl", props.DefaultMessageTimeToLive) - d.Set("duplicate_detection_history_time_window", props.DuplicateDetectionHistoryTimeWindow) - d.Set("enable_batched_operations", props.EnableBatchedOperations) - d.Set("enable_express", props.EnableExpress) - d.Set("enable_partitioning", props.EnablePartitioning) - d.Set("forward_dead_lettered_messages_to", props.ForwardDeadLetteredMessagesTo) - d.Set("forward_to", props.ForwardTo) - d.Set("lock_duration", props.LockDuration) - d.Set("max_delivery_count", props.MaxDeliveryCount) - d.Set("max_message_size_in_kilobytes", props.MaxMessageSizeInKilobytes) - d.Set("requires_duplicate_detection", props.RequiresDuplicateDetection) - d.Set("requires_session", props.RequiresSession) - d.Set("status", props.Status) - - if apiMaxSizeInMegabytes := props.MaxSizeInMegabytes; apiMaxSizeInMegabytes != nil { - maxSizeInMegabytes := int(*apiMaxSizeInMegabytes) - - // If the queue is NOT in a premium namespace (ie. it is Basic or Standard) and partitioning is enabled - // then the max size returned by the API will be 16 times greater than the value set. - if *props.EnablePartitioning { - namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient - namespace, err := namespacesClient.Get(ctx, id.ResourceGroup, id.NamespaceName) - if err != nil { - return err + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + + d.Set("name", id.QueueName) + d.Set("namespace_id", namespaceId.ID()) + + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) + d.Set("dead_lettering_on_message_expiration", props.DeadLetteringOnMessageExpiration) + d.Set("default_message_ttl", props.DefaultMessageTimeToLive) + d.Set("duplicate_detection_history_time_window", props.DuplicateDetectionHistoryTimeWindow) + d.Set("enable_batched_operations", props.EnableBatchedOperations) + d.Set("enable_express", props.EnableExpress) + d.Set("enable_partitioning", props.EnablePartitioning) + d.Set("forward_dead_lettered_messages_to", props.ForwardDeadLetteredMessagesTo) + d.Set("forward_to", props.ForwardTo) + d.Set("lock_duration", props.LockDuration) + d.Set("max_delivery_count", props.MaxDeliveryCount) + d.Set("max_message_size_in_kilobytes", props.MaxMessageSizeInKilobytes) + d.Set("requires_duplicate_detection", props.RequiresDuplicateDetection) + d.Set("requires_session", props.RequiresSession) + d.Set("status", props.Status) + + if apiMaxSizeInMegabytes := props.MaxSizeInMegabytes; apiMaxSizeInMegabytes != nil { + maxSizeInMegabytes := int(*apiMaxSizeInMegabytes) + + // If the queue is NOT in a premium namespace (ie. it is Basic or Standard) and partitioning is enabled + // then the max size returned by the API will be 16 times greater than the value set. + if *props.EnablePartitioning { + namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient + namespace, err := namespacesClient.Get(ctx, namespaceId) + if err != nil { + return err + } + + if nsModel := namespace.Model; nsModel != nil && nsModel.Sku.Name != namespaces.SkuNamePremium { + const partitionCount = 16 + maxSizeInMegabytes = int(*apiMaxSizeInMegabytes / partitionCount) + } } - if namespace.Sku.Name != servicebus.SkuNamePremium { - const partitionCount = 16 - maxSizeInMegabytes = int(*apiMaxSizeInMegabytes / partitionCount) - } + d.Set("max_size_in_megabytes", maxSizeInMegabytes) } - - d.Set("max_size_in_megabytes", maxSizeInMegabytes) } } - return nil } @@ -351,14 +371,14 @@ func resourceServiceBusQueueDelete(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.QueueID(d.Id()) + id, err := queues.ParseQueueID(d.Id()) if err != nil { return err } - resp, err := client.Delete(ctx, id.ResourceGroup, id.NamespaceName, id.Name) + resp, err := client.Delete(ctx, *id) if err != nil { - if !utils.ResponseWasNotFound(resp) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("deleting %s: %+v", id, err) } } diff --git a/internal/services/servicebus/servicebus_queue_resource_test.go b/internal/services/servicebus/servicebus_queue_resource_test.go index 1b12460e0f34..c8ea871c522f 100644 --- a/internal/services/servicebus/servicebus_queue_resource_test.go +++ b/internal/services/servicebus/servicebus_queue_resource_test.go @@ -3,12 +3,13 @@ package servicebus_test import ( "context" "fmt" + "regexp" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -59,6 +60,7 @@ func TestAccServiceBusQueue_update(t *testing.T) { check.That(data.ResourceName).Key("enable_batched_operations").HasValue("true"), ), }, + data.ImportStep(), { Config: r.update(data), Check: acceptance.ComposeTestCheckFunc( @@ -123,6 +125,17 @@ func TestAccServiceBusQueue_defaultEnablePartitioningPremium(t *testing.T) { }) } +func TestAccServiceBusQueue_enablePartitioningForPremiumError(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_servicebus_queue", "test") + r := ServiceBusQueueResource{} + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.enablePartitioningForPremiumError(data), + ExpectError: regexp.MustCompile("partitioning Entities is not supported in Premium SKU and must be disabled"), + }, + }) +} + func TestAccServiceBusQueue_enableDuplicateDetection(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_servicebus_queue", "test") r := ServiceBusQueueResource{} @@ -354,17 +367,17 @@ func TestAccServiceBusQueue_status(t *testing.T) { } func (t ServiceBusQueueResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.QueueID(state.ID) + id, err := queues.ParseQueueID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.QueuesClient.Get(ctx, id.ResourceGroup, id.NamespaceName, id.Name) + resp, err := clients.ServiceBus.QueuesClient.Get(ctx, *id) if err != nil { - return nil, fmt.Errorf("reading Service Bus NameSpace Queue (%s): %+v", id.String(), err) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (ServiceBusQueueResource) basic(data acceptance.TestData) string { @@ -433,6 +446,33 @@ resource "azurerm_servicebus_queue" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) } +func (ServiceBusQueueResource) enablePartitioningForPremiumError(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_servicebus_namespace" "test" { + name = "acctestservicebusnamespace-%d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + sku = "Premium" + capacity = 1 +} + +resource "azurerm_servicebus_queue" "test" { + name = "acctestservicebusqueue-%d" + namespace_id = azurerm_servicebus_namespace.test.id + enable_partitioning = true +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) +} + func (ServiceBusQueueResource) update(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/servicebus/servicebus_subscription_data_source.go b/internal/services/servicebus/servicebus_subscription_data_source.go index 9fc5667917bc..a0cd61b0236b 100644 --- a/internal/services/servicebus/servicebus_subscription_data_source.go +++ b/internal/services/servicebus/servicebus_subscription_data_source.go @@ -4,13 +4,14 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourcegroups" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceServiceBusSubscription() *pluginsdk.Resource { @@ -30,7 +31,7 @@ func dataSourceServiceBusSubscription() *pluginsdk.Resource { "topic_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validate.TopicID, + ValidateFunc: topics.ValidateTopicID, AtLeastOneOf: []string{"topic_id", "resource_group_name", "namespace_name", "topic_name"}, }, @@ -119,23 +120,23 @@ func dataSourceServiceBusSubscriptionRead(d *pluginsdk.ResourceData, meta interf var nsName string var topicName string if v, ok := d.Get("topic_id").(string); ok && v != "" { - topicId, err := parse.TopicID(v) + topicId, err := subscriptions.ParseTopicID(v) if err != nil { return fmt.Errorf("parsing topic ID %q: %+v", v, err) } - rgName = topicId.ResourceGroup + rgName = topicId.ResourceGroupName nsName = topicId.NamespaceName - topicName = topicId.Name + topicName = topicId.TopicName } else { rgName = d.Get("resource_group_name").(string) nsName = d.Get("namespace_name").(string) topicName = d.Get("topic_name").(string) } - id := parse.NewSubscriptionID(subscriptionId, rgName, nsName, topicName, d.Get("name").(string)) - existing, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.Name) + id := subscriptions.NewSubscriptions2ID(subscriptionId, rgName, nsName, topicName, d.Get("name").(string)) + existing, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse) { return fmt.Errorf("%s was not found", id) } @@ -144,23 +145,25 @@ func dataSourceServiceBusSubscriptionRead(d *pluginsdk.ResourceData, meta interf d.SetId(id.ID()) - if props := existing.SBSubscriptionProperties; props != nil { - d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) - d.Set("default_message_ttl", props.DefaultMessageTimeToLive) - d.Set("lock_duration", props.LockDuration) - d.Set("dead_lettering_on_message_expiration", props.DeadLetteringOnMessageExpiration) - d.Set("dead_lettering_on_filter_evaluation_error", props.DeadLetteringOnFilterEvaluationExceptions) - d.Set("enable_batched_operations", props.EnableBatchedOperations) - d.Set("requires_session", props.RequiresSession) - d.Set("forward_dead_lettered_messages_to", props.ForwardDeadLetteredMessagesTo) - d.Set("forward_to", props.ForwardTo) - - maxDeliveryCount := 0 - if props.MaxDeliveryCount != nil { - maxDeliveryCount = int(*props.MaxDeliveryCount) + if model := existing.Model; model != nil { + if props := model.Properties; props != nil { + d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) + d.Set("default_message_ttl", props.DefaultMessageTimeToLive) + d.Set("lock_duration", props.LockDuration) + d.Set("dead_lettering_on_message_expiration", props.DeadLetteringOnMessageExpiration) + d.Set("dead_lettering_on_filter_evaluation_error", props.DeadLetteringOnFilterEvaluationExceptions) + d.Set("enable_batched_operations", props.EnableBatchedOperations) + d.Set("requires_session", props.RequiresSession) + d.Set("forward_dead_lettered_messages_to", props.ForwardDeadLetteredMessagesTo) + d.Set("forward_to", props.ForwardTo) + + maxDeliveryCount := 0 + if props.MaxDeliveryCount != nil { + maxDeliveryCount = int(*props.MaxDeliveryCount) + } + + d.Set("max_delivery_count", maxDeliveryCount) } - - d.Set("max_delivery_count", maxDeliveryCount) } return nil diff --git a/internal/services/servicebus/servicebus_subscription_resource.go b/internal/services/servicebus/servicebus_subscription_resource.go index ed1f7cba05f7..1bdbf1504d6e 100644 --- a/internal/services/servicebus/servicebus_subscription_resource.go +++ b/internal/services/servicebus/servicebus_subscription_resource.go @@ -5,11 +5,12 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" @@ -30,7 +31,7 @@ func resourceServiceBusSubscription() *pluginsdk.Resource { }), Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.SubscriptionID(id) + _, err := subscriptions.ParseSubscriptions2ID(id) return err }), @@ -59,7 +60,7 @@ func resourceServicebusSubscriptionSchema() map[string]*pluginsdk.Schema { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.TopicID, + ValidateFunc: topics.ValidateTopicID, }, "auto_delete_on_idle": { @@ -122,11 +123,11 @@ func resourceServicebusSubscriptionSchema() map[string]*pluginsdk.Schema { "status": { Type: pluginsdk.TypeString, Optional: true, - Default: string(servicebus.EntityStatusActive), + Default: string(subscriptions.EntityStatusActive), ValidateFunc: validation.StringInSlice([]string{ - string(servicebus.EntityStatusActive), - string(servicebus.EntityStatusDisabled), - string(servicebus.EntityStatusReceiveDisabled), + string(subscriptions.EntityStatusActive), + string(subscriptions.EntityStatusDisabled), + string(subscriptions.EntityStatusReceiveDisabled), }, false), }, } @@ -138,61 +139,62 @@ func resourceServiceBusSubscriptionCreateUpdate(d *pluginsdk.ResourceData, meta defer cancel() log.Printf("[INFO] preparing arguments for ServiceBus Subscription creation.") - var resourceId parse.SubscriptionId + var id subscriptions.Subscriptions2Id if topicIdLit := d.Get("topic_id").(string); topicIdLit != "" { - topicId, _ := parse.TopicID(topicIdLit) - resourceId = parse.NewSubscriptionID(topicId.SubscriptionId, topicId.ResourceGroup, topicId.NamespaceName, topicId.Name, d.Get("name").(string)) + topicId, _ := subscriptions.ParseTopicID(topicIdLit) + id = subscriptions.NewSubscriptions2ID(topicId.SubscriptionId, topicId.ResourceGroupName, topicId.NamespaceName, topicId.TopicName, d.Get("name").(string)) } if d.IsNewResource() { - existing, err := client.Get(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.TopicName, resourceId.Name) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing %s: %+v", resourceId, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - return tf.ImportAsExistsError("azurerm_servicebus_subscription", resourceId.ID()) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_servicebus_subscription", id.ID()) } } - parameters := servicebus.SBSubscription{ - SBSubscriptionProperties: &servicebus.SBSubscriptionProperties{ + status := subscriptions.EntityStatus(d.Get("status").(string)) + parameters := subscriptions.SBSubscription{ + Properties: &subscriptions.SBSubscriptionProperties{ DeadLetteringOnMessageExpiration: utils.Bool(d.Get("dead_lettering_on_message_expiration").(bool)), DeadLetteringOnFilterEvaluationExceptions: utils.Bool(d.Get("dead_lettering_on_filter_evaluation_error").(bool)), EnableBatchedOperations: utils.Bool(d.Get("enable_batched_operations").(bool)), - MaxDeliveryCount: utils.Int32(int32(d.Get("max_delivery_count").(int))), + MaxDeliveryCount: utils.Int64(int64(d.Get("max_delivery_count").(int))), RequiresSession: utils.Bool(d.Get("requires_session").(bool)), - Status: servicebus.EntityStatus(d.Get("status").(string)), + Status: &status, }, } if autoDeleteOnIdle := d.Get("auto_delete_on_idle").(string); autoDeleteOnIdle != "" { - parameters.SBSubscriptionProperties.AutoDeleteOnIdle = &autoDeleteOnIdle + parameters.Properties.AutoDeleteOnIdle = &autoDeleteOnIdle } if lockDuration := d.Get("lock_duration").(string); lockDuration != "" { - parameters.SBSubscriptionProperties.LockDuration = &lockDuration + parameters.Properties.LockDuration = &lockDuration } if forwardTo := d.Get("forward_to").(string); forwardTo != "" { - parameters.SBSubscriptionProperties.ForwardTo = &forwardTo + parameters.Properties.ForwardTo = &forwardTo } if forwardDeadLetteredMessagesTo := d.Get("forward_dead_lettered_messages_to").(string); forwardDeadLetteredMessagesTo != "" { - parameters.SBSubscriptionProperties.ForwardDeadLetteredMessagesTo = &forwardDeadLetteredMessagesTo + parameters.Properties.ForwardDeadLetteredMessagesTo = &forwardDeadLetteredMessagesTo } if defaultMessageTtl := d.Get("default_message_ttl").(string); defaultMessageTtl != "" { - parameters.DefaultMessageTimeToLive = &defaultMessageTtl + parameters.Properties.DefaultMessageTimeToLive = &defaultMessageTtl } - if _, err := client.CreateOrUpdate(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.TopicName, resourceId.Name, parameters); err != nil { - return fmt.Errorf("creating/updating %s: %v", resourceId, err) + if _, err := client.CreateOrUpdate(ctx, id, parameters); err != nil { + return fmt.Errorf("creating/updating %s: %v", id, err) } - d.SetId(resourceId.ID()) + d.SetId(id.ID()) return resourceServiceBusSubscriptionRead(d, meta) } @@ -201,37 +203,39 @@ func resourceServiceBusSubscriptionRead(d *pluginsdk.ResourceData, meta interfac ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SubscriptionID(d.Id()) + id, err := subscriptions.ParseSubscriptions2ID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.Name) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - d.Set("name", id.Name) - d.Set("topic_id", parse.NewTopicID(id.SubscriptionId, id.ResourceGroup, id.NamespaceName, id.TopicName).ID()) - - if props := resp.SBSubscriptionProperties; props != nil { - d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) - d.Set("default_message_ttl", props.DefaultMessageTimeToLive) - d.Set("lock_duration", props.LockDuration) - d.Set("dead_lettering_on_message_expiration", props.DeadLetteringOnMessageExpiration) - d.Set("dead_lettering_on_filter_evaluation_error", props.DeadLetteringOnFilterEvaluationExceptions) - d.Set("enable_batched_operations", props.EnableBatchedOperations) - d.Set("requires_session", props.RequiresSession) - d.Set("forward_to", props.ForwardTo) - d.Set("forward_dead_lettered_messages_to", props.ForwardDeadLetteredMessagesTo) - d.Set("status", utils.String(string(props.Status))) - - if count := props.MaxDeliveryCount; count != nil { - d.Set("max_delivery_count", int(*count)) + d.Set("name", id.SubscriptionName) + d.Set("topic_id", subscriptions.NewTopicID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName).ID()) + + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) + d.Set("default_message_ttl", props.DefaultMessageTimeToLive) + d.Set("lock_duration", props.LockDuration) + d.Set("dead_lettering_on_message_expiration", props.DeadLetteringOnMessageExpiration) + d.Set("dead_lettering_on_filter_evaluation_error", props.DeadLetteringOnFilterEvaluationExceptions) + d.Set("enable_batched_operations", props.EnableBatchedOperations) + d.Set("requires_session", props.RequiresSession) + d.Set("forward_to", props.ForwardTo) + d.Set("forward_dead_lettered_messages_to", props.ForwardDeadLetteredMessagesTo) + d.Set("status", utils.String(string(*props.Status))) + + if count := props.MaxDeliveryCount; count != nil { + d.Set("max_delivery_count", int(*count)) + } } } @@ -243,12 +247,12 @@ func resourceServiceBusSubscriptionDelete(d *pluginsdk.ResourceData, meta interf ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SubscriptionID(d.Id()) + id, err := subscriptions.ParseSubscriptions2ID(d.Id()) if err != nil { return err } - if _, err = client.Delete(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.Name); err != nil { + if _, err = client.Delete(ctx, *id); err != nil { return fmt.Errorf("deleting %s: %+v", id, err) } diff --git a/internal/services/servicebus/servicebus_subscription_resource_test.go b/internal/services/servicebus/servicebus_subscription_resource_test.go index 56f4a6e7bf7d..1128d776389a 100644 --- a/internal/services/servicebus/servicebus_subscription_resource_test.go +++ b/internal/services/servicebus/servicebus_subscription_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -219,17 +219,17 @@ func TestAccServiceBusSubscription_status(t *testing.T) { } func (t ServiceBusSubscriptionResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.SubscriptionID(state.ID) + id, err := subscriptions.ParseSubscriptions2ID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.SubscriptionsClient.Get(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.Name) + resp, err := clients.ServiceBus.SubscriptionsClient.Get(ctx, *id) if err != nil { - return nil, fmt.Errorf("reading Service Bus NameSpace Subscription (%s): %+v", id.String(), err) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } const testAccServiceBusSubscription_tfTemplate = ` diff --git a/internal/services/servicebus/servicebus_subscription_rule_resource.go b/internal/services/servicebus/servicebus_subscription_rule_resource.go index 24835ba35e04..129527787491 100644 --- a/internal/services/servicebus/servicebus_subscription_rule_resource.go +++ b/internal/services/servicebus/servicebus_subscription_rule_resource.go @@ -5,11 +5,11 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress" @@ -26,7 +26,7 @@ func resourceServiceBusSubscriptionRule() *pluginsdk.Resource { Delete: resourceServiceBusSubscriptionRuleDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.SubscriptionRuleID(id) + _, err := rules.ParseRuleID(id) return err }), @@ -55,7 +55,7 @@ func resourceServicebusSubscriptionRuleSchema() map[string]*pluginsdk.Schema { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.SubscriptionID, + ValidateFunc: subscriptions.ValidateSubscriptions2ID, DiffSuppressFunc: suppress.CaseDifference, }, @@ -63,8 +63,8 @@ func resourceServicebusSubscriptionRuleSchema() map[string]*pluginsdk.Schema { Type: pluginsdk.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(servicebus.FilterTypeSQLFilter), - string(servicebus.FilterTypeCorrelationFilter), + string(subscriptions.FilterTypeSqlFilter), + string(subscriptions.FilterTypeCorrelationFilter), }, false), }, @@ -178,108 +178,117 @@ func resourceServicebusSubscriptionRuleSchema() map[string]*pluginsdk.Schema { func resourceServiceBusSubscriptionRuleCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { client := meta.(*clients.Client).ServiceBus.SubscriptionRulesClient + subscriptionClient := meta.(*clients.Client).ServiceBus.SubscriptionsClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() log.Printf("[INFO] preparing arguments for Azure Service Bus Subscription Rule creation.") filterType := d.Get("filter_type").(string) - var resourceId parse.SubscriptionRuleId + var id subscriptions.RuleId if subscriptionIdLit := d.Get("subscription_id").(string); subscriptionIdLit != "" { - subscriptionId, _ := parse.SubscriptionID(subscriptionIdLit) - resourceId = parse.NewSubscriptionRuleID(subscriptionId.SubscriptionId, - subscriptionId.ResourceGroup, + subscriptionId, _ := rules.ParseSubscriptions2ID(subscriptionIdLit) + id = subscriptions.NewRuleID(subscriptionId.SubscriptionId, + subscriptionId.ResourceGroupName, subscriptionId.NamespaceName, subscriptionId.TopicName, - subscriptionId.Name, + subscriptionId.SubscriptionName, d.Get("name").(string), ) } if d.IsNewResource() { - existing, err := client.Get(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.TopicName, resourceId.SubscriptionName, resourceId.RuleName) + existing, err := subscriptionClient.RulesGet(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing %s: %+v", resourceId, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - return tf.ImportAsExistsError("azurerm_servicebus_subscription_rule", resourceId.ID()) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_servicebus_subscription_rule", id.ID()) } } - rule := servicebus.Rule{ - Ruleproperties: &servicebus.Ruleproperties{ - FilterType: servicebus.FilterType(filterType), + filter := rules.FilterType(filterType) + rule := rules.Rule{ + Properties: &rules.Ruleproperties{ + FilterType: &filter, }, } if action := d.Get("action").(string); action != "" { - rule.Ruleproperties.Action = &servicebus.Action{ - SQLExpression: &action, + rule.Properties.Action = &rules.Action{ + SqlExpression: &action, } } - if rule.Ruleproperties.FilterType == servicebus.FilterTypeCorrelationFilter { + if *rule.Properties.FilterType == rules.FilterTypeCorrelationFilter { correlationFilter, err := expandAzureRmServiceBusCorrelationFilter(d) if err != nil { return fmt.Errorf("expanding `correlation_filter`: %+v", err) } - rule.Ruleproperties.CorrelationFilter = correlationFilter + rule.Properties.CorrelationFilter = correlationFilter } - if rule.Ruleproperties.FilterType == servicebus.FilterTypeSQLFilter { + if *rule.Properties.FilterType == rules.FilterTypeSqlFilter { sqlFilter := d.Get("sql_filter").(string) - rule.Ruleproperties.SQLFilter = &servicebus.SQLFilter{ - SQLExpression: &sqlFilter, + rule.Properties.SqlFilter = &rules.SqlFilter{ + SqlExpression: &sqlFilter, } } - if _, err := client.CreateOrUpdate(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.TopicName, resourceId.SubscriptionName, resourceId.RuleName, rule); err != nil { - return fmt.Errorf("creating/updating %s: %+v", resourceId, err) + // switch this around so that the rule id from subscription is generated for the get method + ruleId, err := rules.ParseRuleID(id.ID()) + if err != nil { + return err + } + if _, err := client.CreateOrUpdate(ctx, *ruleId, rule); err != nil { + return fmt.Errorf("creating/updating %s: %+v", id, err) } - d.SetId(resourceId.ID()) + d.SetId(id.ID()) return resourceServiceBusSubscriptionRuleRead(d, meta) } func resourceServiceBusSubscriptionRuleRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.SubscriptionRulesClient + client := meta.(*clients.Client).ServiceBus.SubscriptionsClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SubscriptionRuleID(d.Id()) + id, err := subscriptions.ParseRuleID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.SubscriptionName, id.RuleName) + resp, err := client.RulesGet(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - d.Set("subscription_id", parse.NewSubscriptionID(id.SubscriptionId, id.ResourceGroup, id.NamespaceName, id.TopicName, id.SubscriptionName).ID()) + d.Set("subscription_id", subscriptions.NewSubscriptions2ID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName, id.SubscriptionName).ID()) d.Set("name", id.RuleName) - if properties := resp.Ruleproperties; properties != nil { - d.Set("filter_type", properties.FilterType) + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + d.Set("filter_type", props.FilterType) - if properties.Action != nil { - d.Set("action", properties.Action.SQLExpression) - } + if props.Action != nil { + d.Set("action", props.Action.SqlExpression) + } - if properties.SQLFilter != nil { - d.Set("sql_filter", properties.SQLFilter.SQLExpression) - } + if props.SqlFilter != nil { + d.Set("sql_filter", props.SqlFilter.SqlExpression) + } - if err := d.Set("correlation_filter", flattenAzureRmServiceBusCorrelationFilter(properties.CorrelationFilter)); err != nil { - return fmt.Errorf("setting `correlation_filter`: %+v", err) + if err := d.Set("correlation_filter", flattenAzureRmServiceBusCorrelationFilter(props.CorrelationFilter)); err != nil { + return fmt.Errorf("setting `correlation_filter`: %+v", err) + } } } @@ -291,14 +300,14 @@ func resourceServiceBusSubscriptionRuleDelete(d *pluginsdk.ResourceData, meta in ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.SubscriptionRuleID(d.Id()) + id, err := rules.ParseRuleID(d.Id()) if err != nil { return err } - resp, err := client.Delete(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.SubscriptionName, id.RuleName) + resp, err := client.Delete(ctx, *id) if err != nil { - if !response.WasNotFound(resp.Response) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("deleting %s: %+v", id, err) } } @@ -306,7 +315,7 @@ func resourceServiceBusSubscriptionRuleDelete(d *pluginsdk.ResourceData, meta in return nil } -func expandAzureRmServiceBusCorrelationFilter(d *pluginsdk.ResourceData) (*servicebus.CorrelationFilter, error) { +func expandAzureRmServiceBusCorrelationFilter(d *pluginsdk.ResourceData) (*rules.CorrelationFilter, error) { configs := d.Get("correlation_filter").([]interface{}) if len(configs) == 0 { return nil, fmt.Errorf("`correlation_filter` is required when `filter_type` is set to `CorrelationFilter`") @@ -322,20 +331,21 @@ func expandAzureRmServiceBusCorrelationFilter(d *pluginsdk.ResourceData) (*servi replyToSessionID := config["reply_to_session_id"].(string) sessionID := config["session_id"].(string) to := config["to"].(string) - properties := utils.ExpandMapStringPtrString(config["properties"].(map[string]interface{})) - if contentType == "" && correlationID == "" && label == "" && messageID == "" && replyTo == "" && replyToSessionID == "" && sessionID == "" && to == "" && len(properties) == 0 { - return nil, fmt.Errorf("At least one property must be set in the `correlation_filter` block") + properties := expandProperties(config["properties"].(map[string]interface{})) + + if contentType == "" && correlationID == "" && label == "" && messageID == "" && replyTo == "" && replyToSessionID == "" && sessionID == "" && to == "" && len(*properties) == 0 { + return nil, fmt.Errorf("at least one property must be set in the `correlation_filter` block") } - correlationFilter := servicebus.CorrelationFilter{} + correlationFilter := rules.CorrelationFilter{} if correlationID != "" { - correlationFilter.CorrelationID = utils.String(correlationID) + correlationFilter.CorrelationId = utils.String(correlationID) } if messageID != "" { - correlationFilter.MessageID = utils.String(messageID) + correlationFilter.MessageId = utils.String(messageID) } if to != "" { @@ -351,37 +361,37 @@ func expandAzureRmServiceBusCorrelationFilter(d *pluginsdk.ResourceData) (*servi } if sessionID != "" { - correlationFilter.SessionID = utils.String(sessionID) + correlationFilter.SessionId = utils.String(sessionID) } if replyToSessionID != "" { - correlationFilter.ReplyToSessionID = utils.String(replyToSessionID) + correlationFilter.ReplyToSessionId = utils.String(replyToSessionID) } if contentType != "" { correlationFilter.ContentType = utils.String(contentType) } - if len(properties) > 0 { + if len(*properties) > 0 { correlationFilter.Properties = properties } return &correlationFilter, nil } -func flattenAzureRmServiceBusCorrelationFilter(input *servicebus.CorrelationFilter) []interface{} { +func flattenAzureRmServiceBusCorrelationFilter(input *subscriptions.CorrelationFilter) []interface{} { if input == nil { return []interface{}{} } filter := make(map[string]interface{}) - if input.CorrelationID != nil { - filter["correlation_id"] = *input.CorrelationID + if input.CorrelationId != nil { + filter["correlation_id"] = *input.CorrelationId } - if input.MessageID != nil { - filter["message_id"] = *input.MessageID + if input.MessageId != nil { + filter["message_id"] = *input.MessageId } if input.To != nil { @@ -396,12 +406,12 @@ func flattenAzureRmServiceBusCorrelationFilter(input *servicebus.CorrelationFilt filter["label"] = *input.Label } - if input.SessionID != nil { - filter["session_id"] = *input.SessionID + if input.SessionId != nil { + filter["session_id"] = *input.SessionId } - if input.ReplyToSessionID != nil { - filter["reply_to_session_id"] = *input.ReplyToSessionID + if input.ReplyToSessionId != nil { + filter["reply_to_session_id"] = *input.ReplyToSessionId } if input.ContentType != nil { @@ -409,8 +419,28 @@ func flattenAzureRmServiceBusCorrelationFilter(input *servicebus.CorrelationFilt } if input.Properties != nil { - filter["properties"] = utils.FlattenMapStringPtrString(input.Properties) + filter["properties"] = flattenProperties(input.Properties) } return []interface{}{filter} } + +func expandProperties(input map[string]interface{}) *map[string]string { + output := make(map[string]string) + for k, v := range input { + output[k] = v.(string) + } + return &output +} + +func flattenProperties(input *map[string]string) map[string]*string { + output := make(map[string]*string) + + if input != nil { + for k, v := range *input { + output[k] = utils.String(v) + } + } + + return output +} diff --git a/internal/services/servicebus/servicebus_subscription_rule_resource_test.go b/internal/services/servicebus/servicebus_subscription_rule_resource_test.go index 644466858b6a..d2ac989b31f8 100644 --- a/internal/services/servicebus/servicebus_subscription_rule_resource_test.go +++ b/internal/services/servicebus/servicebus_subscription_rule_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -153,17 +153,17 @@ func TestAccServiceBusSubscriptionRule_updateSqlFilterToCorrelationFilter(t *tes } func (t ServiceBusSubscriptionRuleResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.SubscriptionRuleID(state.ID) + id, err := subscriptions.ParseRuleID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.SubscriptionRulesClient.Get(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.SubscriptionName, id.RuleName) + resp, err := clients.ServiceBus.SubscriptionsClient.RulesGet(ctx, *id) if err != nil { - return nil, fmt.Errorf("reading Service Bus NameSpace Subscription Rule (%s): %+v", id.String(), err) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (r ServiceBusSubscriptionRuleResource) basicSqlFilter(data acceptance.TestData) string { diff --git a/internal/services/servicebus/servicebus_topic_authorization_rule_data_source.go b/internal/services/servicebus/servicebus_topic_authorization_rule_data_source.go index dd3ab2fb5437..584094358a5c 100644 --- a/internal/services/servicebus/servicebus_topic_authorization_rule_data_source.go +++ b/internal/services/servicebus/servicebus_topic_authorization_rule_data_source.go @@ -4,14 +4,15 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourcegroups" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceServiceBusTopicAuthorizationRule() *pluginsdk.Resource { @@ -32,7 +33,7 @@ func dataSourceServiceBusTopicAuthorizationRule() *pluginsdk.Resource { "topic_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validate.TopicID, + ValidateFunc: topics.ValidateTopicID, AtLeastOneOf: []string{"topic_id", "resource_group_name", "namespace_name", "queue_name"}, }, @@ -119,7 +120,7 @@ func dataSourceServiceBusTopicAuthorizationRule() *pluginsdk.Resource { } func dataSourceServiceBusTopicAuthorizationRuleRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.TopicsClient + client := meta.(*clients.Client).ServiceBus.TopicsAuthClient subscriptionId := meta.(*clients.Client).Account.SubscriptionId ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -128,29 +129,29 @@ func dataSourceServiceBusTopicAuthorizationRuleRead(d *pluginsdk.ResourceData, m var nsName string var topicName string if v, ok := d.Get("topic_id").(string); ok && v != "" { - topicId, err := parse.TopicID(v) + topicId, err := topicsauthorizationrule.ParseTopicID(v) if err != nil { return fmt.Errorf("parsing topic ID %q: %+v", v, err) } - rgName = topicId.ResourceGroup + rgName = topicId.ResourceGroupName nsName = topicId.NamespaceName - topicName = topicId.Name + topicName = topicId.TopicName } else { rgName = d.Get("resource_group_name").(string) nsName = d.Get("namespace_name").(string) topicName = d.Get("topic_name").(string) } - id := parse.NewTopicAuthorizationRuleID(subscriptionId, rgName, nsName, topicName, d.Get("name").(string)) - resp, err := client.GetAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.AuthorizationRuleName) + id := topicsauthorizationrule.NewTopicAuthorizationRuleID(subscriptionId, rgName, nsName, topicName, d.Get("name").(string)) + resp, err := client.TopicsGetAuthorizationRule(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("%s was not found", id) } return fmt.Errorf("retrieving %s: %+v", id, err) } - keysResp, err := client.ListKeys(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.AuthorizationRuleName) + keysResp, err := client.TopicsListKeys(ctx, id) if err != nil { return fmt.Errorf("listing keys for %s: %+v", id, err) } @@ -159,21 +160,25 @@ func dataSourceServiceBusTopicAuthorizationRuleRead(d *pluginsdk.ResourceData, m d.Set("name", id.AuthorizationRuleName) d.Set("topic_name", id.TopicName) d.Set("namespace_name", id.NamespaceName) - d.Set("resource_group_name", id.ResourceGroup) - - if properties := resp.SBAuthorizationRuleProperties; properties != nil { - listen, send, manage := flattenAuthorizationRuleRights(properties.Rights) - d.Set("listen", listen) - d.Set("send", send) - d.Set("manage", manage) + d.Set("resource_group_name", id.ResourceGroupName) + + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + listen, send, manage := flattenTopicAuthorizationRuleRights(&props.Rights) + d.Set("listen", listen) + d.Set("send", send) + d.Set("manage", manage) + } } - d.Set("primary_key", keysResp.PrimaryKey) - d.Set("primary_connection_string", keysResp.PrimaryConnectionString) - d.Set("secondary_key", keysResp.SecondaryKey) - d.Set("secondary_connection_string", keysResp.SecondaryConnectionString) - d.Set("primary_connection_string_alias", keysResp.AliasPrimaryConnectionString) - d.Set("secondary_connection_string_alias", keysResp.AliasSecondaryConnectionString) + if model := keysResp.Model; model != nil { + d.Set("primary_key", model.PrimaryKey) + d.Set("primary_connection_string", model.PrimaryConnectionString) + d.Set("secondary_key", model.SecondaryKey) + d.Set("secondary_connection_string", model.SecondaryConnectionString) + d.Set("primary_connection_string_alias", model.AliasPrimaryConnectionString) + d.Set("secondary_connection_string_alias", model.AliasSecondaryConnectionString) + } return nil } diff --git a/internal/services/servicebus/servicebus_topic_authorization_rule_resource.go b/internal/services/servicebus/servicebus_topic_authorization_rule_resource.go index 0b246eb5a342..bd66957eaa06 100644 --- a/internal/services/servicebus/servicebus_topic_authorization_rule_resource.go +++ b/internal/services/servicebus/servicebus_topic_authorization_rule_resource.go @@ -5,10 +5,12 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -23,7 +25,7 @@ func resourceServiceBusTopicAuthorizationRule() *pluginsdk.Resource { Delete: resourceServiceBusTopicAuthorizationRuleDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.TopicAuthorizationRuleID(id) + _, err := topicsauthorizationrule.ParseTopicAuthorizationRuleID(id) return err }), @@ -54,69 +56,73 @@ func resourceServiceBusTopicAuthorizationRuleSchema() map[string]*pluginsdk.Sche Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.TopicID, + ValidateFunc: topics.ValidateTopicID, }, } } func resourceServiceBusTopicAuthorizationRuleCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.TopicsClient + client := meta.(*clients.Client).ServiceBus.TopicsAuthClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() log.Printf("[INFO] preparing arguments for AzureRM ServiceBus Topic Authorization Rule creation.") - var resourceId parse.TopicAuthorizationRuleId + var id topicsauthorizationrule.TopicAuthorizationRuleId if topicIdLit := d.Get("topic_id").(string); topicIdLit != "" { - topicId, _ := parse.TopicID(topicIdLit) - resourceId = parse.NewTopicAuthorizationRuleID(topicId.SubscriptionId, topicId.ResourceGroup, topicId.NamespaceName, topicId.Name, d.Get("name").(string)) + topicId, err := topicsauthorizationrule.ParseTopicID(topicIdLit) + if err != nil { + return err + } + id = topicsauthorizationrule.NewTopicAuthorizationRuleID(topicId.SubscriptionId, topicId.ResourceGroupName, topicId.NamespaceName, topicId.TopicName, d.Get("name").(string)) } if d.IsNewResource() { - existing, err := client.GetAuthorizationRule(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.TopicName, resourceId.AuthorizationRuleName) + existing, err := client.TopicsGetAuthorizationRule(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing %s: %+v", resourceId, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - return tf.ImportAsExistsError("azurerm_servicebus_topic_authorization_rule", resourceId.ID()) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_servicebus_topic_authorization_rule", id.ID()) } } - parameters := servicebus.SBAuthorizationRule{ - Name: utils.String(resourceId.AuthorizationRuleName), - SBAuthorizationRuleProperties: &servicebus.SBAuthorizationRuleProperties{ - Rights: expandAuthorizationRuleRights(d), + parameters := topicsauthorizationrule.SBAuthorizationRule{ + Name: utils.String(id.AuthorizationRuleName), + Properties: &topicsauthorizationrule.SBAuthorizationRuleProperties{ + Rights: *expandTopicAuthorizationRuleRights(d), }, } - if _, err := client.CreateOrUpdateAuthorizationRule(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.TopicName, resourceId.AuthorizationRuleName, parameters); err != nil { - return fmt.Errorf("creating/updating %s: %+v", resourceId, err) + if _, err := client.TopicsCreateOrUpdateAuthorizationRule(ctx, id, parameters); err != nil { + return fmt.Errorf("creating/updating %s: %+v", id, err) } - d.SetId(resourceId.ID()) + d.SetId(id.ID()) - if err := waitForPairedNamespaceReplication(ctx, meta, resourceId.ResourceGroup, resourceId.NamespaceName, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { - return fmt.Errorf("waiting for replication to complete for Service Bus Namespace Disaster Recovery Configs (Namespace %q / Resource Group %q): %s", resourceId.NamespaceName, resourceId.ResourceGroup, err) + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + if err := waitForPairedNamespaceReplication(ctx, meta, namespaceId, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for replication to complete for %s: %+v", id, err) } return resourceServiceBusTopicAuthorizationRuleRead(d, meta) } func resourceServiceBusTopicAuthorizationRuleRead(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.TopicsClient + client := meta.(*clients.Client).ServiceBus.TopicsAuthClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.TopicAuthorizationRuleID(d.Id()) + id, err := topicsauthorizationrule.ParseTopicAuthorizationRuleID(d.Id()) if err != nil { return err } - resp, err := client.GetAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.AuthorizationRuleName) + resp, err := client.TopicsGetAuthorizationRule(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } @@ -124,47 +130,90 @@ func resourceServiceBusTopicAuthorizationRuleRead(d *pluginsdk.ResourceData, met } d.Set("name", id.AuthorizationRuleName) - d.Set("topic_id", parse.NewTopicID(id.SubscriptionId, id.ResourceGroup, id.NamespaceName, id.TopicName).ID()) - - if properties := resp.SBAuthorizationRuleProperties; properties != nil { - listen, send, manage := flattenAuthorizationRuleRights(properties.Rights) - d.Set("listen", listen) - d.Set("send", send) - d.Set("manage", manage) + d.Set("topic_id", topicsauthorizationrule.NewTopicID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName).ID()) + + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + listen, send, manage := flattenTopicAuthorizationRuleRights(&props.Rights) + d.Set("listen", listen) + d.Set("send", send) + d.Set("manage", manage) + } } - keysResp, err := client.ListKeys(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.AuthorizationRuleName) + keysResp, err := client.TopicsListKeys(ctx, *id) if err != nil { return fmt.Errorf("listing keys for %s: %+v", id, err) } - d.Set("primary_key", keysResp.PrimaryKey) - d.Set("primary_connection_string", keysResp.PrimaryConnectionString) - d.Set("secondary_key", keysResp.SecondaryKey) - d.Set("secondary_connection_string", keysResp.SecondaryConnectionString) - d.Set("primary_connection_string_alias", keysResp.AliasPrimaryConnectionString) - d.Set("secondary_connection_string_alias", keysResp.AliasSecondaryConnectionString) + if model := keysResp.Model; model != nil { + d.Set("primary_key", model.PrimaryKey) + d.Set("primary_connection_string", model.PrimaryConnectionString) + d.Set("secondary_key", model.SecondaryKey) + d.Set("secondary_connection_string", model.SecondaryConnectionString) + d.Set("primary_connection_string_alias", model.AliasPrimaryConnectionString) + d.Set("secondary_connection_string_alias", model.AliasSecondaryConnectionString) + } return nil } func resourceServiceBusTopicAuthorizationRuleDelete(d *pluginsdk.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).ServiceBus.TopicsClient + client := meta.(*clients.Client).ServiceBus.TopicsAuthClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.TopicAuthorizationRuleID(d.Id()) + id, err := topicsauthorizationrule.ParseTopicAuthorizationRuleID(d.Id()) if err != nil { return err } - if _, err = client.DeleteAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.AuthorizationRuleName); err != nil { + if _, err = client.TopicsDeleteAuthorizationRule(ctx, *id); err != nil { return fmt.Errorf("deleting %s: %+v", id, err) } - if err := waitForPairedNamespaceReplication(ctx, meta, id.ResourceGroup, id.NamespaceName, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { - return fmt.Errorf("waiting for replication to complete for Service Bus Namespace Disaster Recovery Configs (Namespace %q / Resource Group %q): %s", id.NamespaceName, id.ResourceGroup, err) + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + + if err := waitForPairedNamespaceReplication(ctx, meta, namespaceId, d.Timeout(pluginsdk.TimeoutUpdate)); err != nil { + return fmt.Errorf("waiting for replication to complete for Service Bus Namespace Disaster Recovery Configs (Namespace %q / Resource Group %q): %s", id.NamespaceName, id.ResourceGroupName, err) } return nil } + +func expandTopicAuthorizationRuleRights(d *pluginsdk.ResourceData) *[]topicsauthorizationrule.AccessRights { + rights := make([]topicsauthorizationrule.AccessRights, 0) + + if d.Get("listen").(bool) { + rights = append(rights, topicsauthorizationrule.AccessRightsListen) + } + + if d.Get("send").(bool) { + rights = append(rights, topicsauthorizationrule.AccessRightsSend) + } + + if d.Get("manage").(bool) { + rights = append(rights, topicsauthorizationrule.AccessRightsManage) + } + + return &rights +} + +func flattenTopicAuthorizationRuleRights(rights *[]topicsauthorizationrule.AccessRights) (listen, send, manage bool) { + if rights != nil { + for _, right := range *rights { + switch right { + case topicsauthorizationrule.AccessRightsListen: + listen = true + case topicsauthorizationrule.AccessRightsSend: + send = true + case topicsauthorizationrule.AccessRightsManage: + manage = true + default: + log.Printf("[DEBUG] Unknown Authorization Rule Right '%s'", right) + } + } + } + + return listen, send, manage +} diff --git a/internal/services/servicebus/servicebus_topic_authorization_rule_resource_test.go b/internal/services/servicebus/servicebus_topic_authorization_rule_resource_test.go index 6242d47d1a7b..cc95707037d1 100644 --- a/internal/services/servicebus/servicebus_topic_authorization_rule_resource_test.go +++ b/internal/services/servicebus/servicebus_topic_authorization_rule_resource_test.go @@ -6,10 +6,10 @@ import ( "strconv" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -137,17 +137,17 @@ func TestAccServiceBusTopicAuthorizationRule_withAliasConnectionString(t *testin } func (t ServiceBusTopicAuthorizationRuleResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.TopicAuthorizationRuleID(state.ID) + id, err := topicsauthorizationrule.ParseTopicAuthorizationRuleID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.TopicsClient.GetAuthorizationRule(ctx, id.ResourceGroup, id.NamespaceName, id.TopicName, id.AuthorizationRuleName) + resp, err := clients.ServiceBus.TopicsAuthClient.TopicsGetAuthorizationRule(ctx, *id) if err != nil { - return nil, fmt.Errorf("reading Service Bus Topic Authorization Rule (%s): %+v", id.String(), err) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (ServiceBusTopicAuthorizationRuleResource) base(data acceptance.TestData, listen, send, manage bool) string { diff --git a/internal/services/servicebus/servicebus_topic_data_source.go b/internal/services/servicebus/servicebus_topic_data_source.go index b90136ec390e..192214d1248d 100644 --- a/internal/services/servicebus/servicebus_topic_data_source.go +++ b/internal/services/servicebus/servicebus_topic_data_source.go @@ -4,16 +4,15 @@ import ( "fmt" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/resourcegroups" - - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" azValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" ) func dataSourceServiceBusTopic() *pluginsdk.Resource { @@ -34,7 +33,7 @@ func dataSourceServiceBusTopic() *pluginsdk.Resource { "namespace_id": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validate.NamespaceID, + ValidateFunc: namespaces.ValidateNamespaceID, AtLeastOneOf: []string{"namespace_id", "resource_group_name", "namespace_name"}, }, @@ -114,67 +113,75 @@ func dataSourceServiceBusTopicRead(d *pluginsdk.ResourceData, meta interface{}) subscriptionId := meta.(*clients.Client).Account.SubscriptionId defer cancel() - name := d.Get("name").(string) - var resourceGroup string var namespaceName string if v, ok := d.Get("namespace_id").(string); ok && v != "" { - namespaceId, err := parse.NamespaceID(v) + namespaceId, err := topics.ParseNamespaceID(v) if err != nil { - return fmt.Errorf("parsing topic ID %q: %+v", v, err) + return err } - resourceGroup = namespaceId.ResourceGroup - namespaceName = namespaceId.Name + resourceGroup = namespaceId.ResourceGroupName + namespaceName = namespaceId.NamespaceName } else { resourceGroup = d.Get("resource_group_name").(string) namespaceName = d.Get("namespace_name").(string) } - id := parse.NewTopicID(subscriptionId, resourceGroup, namespaceName, name) - resp, err := client.Get(ctx, resourceGroup, namespaceName, name) + id := topics.NewTopicID(subscriptionId, resourceGroup, namespaceName, d.Get("name").(string)) + + resp, err := client.Get(ctx, id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Service Bus Topic %q was not found in Resource Group %q Namespace %q", name, resourceGroup, namespaceName) + if response.WasNotFound(resp.HttpResponse) { + return fmt.Errorf("%s was not found", id) } - return fmt.Errorf("making Read request on Azure Service Bus Topic %q in Resource Group %q Namespace %q: %v", name, resourceGroup, namespaceName, err) + return fmt.Errorf("retrieving %s: %v", id, err) } d.SetId(id.ID()) - if props := resp.SBTopicProperties; props != nil { - d.Set("status", string(props.Status)) - d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) - d.Set("default_message_ttl", props.DefaultMessageTimeToLive) + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + status := "" + if v := props.Status; v != nil { + status = string(*v) + } + d.Set("status", status) + d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) + d.Set("default_message_ttl", props.DefaultMessageTimeToLive) - if window := props.DuplicateDetectionHistoryTimeWindow; window != nil && *window != "" { - d.Set("duplicate_detection_history_time_window", window) - } + if window := props.DuplicateDetectionHistoryTimeWindow; window != nil && *window != "" { + d.Set("duplicate_detection_history_time_window", window) + } - d.Set("enable_batched_operations", props.EnableBatchedOperations) - d.Set("enable_express", props.EnableExpress) - d.Set("enable_partitioning", props.EnablePartitioning) - d.Set("requires_duplicate_detection", props.RequiresDuplicateDetection) - d.Set("support_ordering", props.SupportOrdering) - - if maxSizeMB := props.MaxSizeInMegabytes; maxSizeMB != nil { - maxSize := int(*props.MaxSizeInMegabytes) - - // if the topic is in a premium namespace and partitioning is enabled then the - // max size returned by the API will be 16 times greater than the value set - if partitioning := props.EnablePartitioning; partitioning != nil && *partitioning { - namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient - namespace, err := namespacesClient.Get(ctx, resourceGroup, namespaceName) - if err != nil { - return err + d.Set("enable_batched_operations", props.EnableBatchedOperations) + d.Set("enable_express", props.EnableExpress) + d.Set("enable_partitioning", props.EnablePartitioning) + d.Set("requires_duplicate_detection", props.RequiresDuplicateDetection) + d.Set("support_ordering", props.SupportOrdering) + + if maxSizeMB := props.MaxSizeInMegabytes; maxSizeMB != nil { + maxSize := int(*props.MaxSizeInMegabytes) + + // if the topic is in a premium namespace and partitioning is enabled then the + // max size returned by the API will be 16 times greater than the value set + if partitioning := props.EnablePartitioning; partitioning != nil && *partitioning { + namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + namespace, err := namespacesClient.Get(ctx, namespaceId) + if err != nil { + return err + } + + if namespaceModel := namespace.Model; namespaceModel != nil { + if namespaceModel.Sku.Name != namespaces.SkuNamePremium { + const partitionCount = 16 + maxSize = int(*props.MaxSizeInMegabytes / partitionCount) + } + } } - if namespace.Sku.Name != servicebus.SkuNamePremium { - const partitionCount = 16 - maxSize = int(*props.MaxSizeInMegabytes / partitionCount) - } + d.Set("max_size_in_megabytes", maxSize) } - - d.Set("max_size_in_megabytes", maxSize) } } diff --git a/internal/services/servicebus/servicebus_topic_resource.go b/internal/services/servicebus/servicebus_topic_resource.go index 8421c276c9bf..26b74ad2cb17 100644 --- a/internal/services/servicebus/servicebus_topic_resource.go +++ b/internal/services/servicebus/servicebus_topic_resource.go @@ -5,11 +5,12 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" + "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" azValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" @@ -25,7 +26,7 @@ func resourceServiceBusTopic() *pluginsdk.Resource { Delete: resourceServiceBusTopicDelete, Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.TopicID(id) + _, err := topics.ParseTopicID(id) return err }), @@ -54,16 +55,16 @@ func resourceServiceBusTopicSchema() map[string]*pluginsdk.Schema { Type: pluginsdk.TypeString, Required: true, ForceNew: true, - ValidateFunc: azValidate.NamespaceID, + ValidateFunc: namespaces.ValidateNamespaceID, }, "status": { Type: pluginsdk.TypeString, Optional: true, - Default: string(servicebus.EntityStatusActive), + Default: string(topics.EntityStatusActive), ValidateFunc: validation.StringInSlice([]string{ - string(servicebus.EntityStatusActive), - string(servicebus.EntityStatusDisabled), + string(topics.EntityStatusActive), + string(topics.EntityStatusDisabled), }, false), }, @@ -140,79 +141,78 @@ func resourceServiceBusTopicCreateUpdate(d *pluginsdk.ResourceData, meta interfa defer cancel() log.Printf("[INFO] preparing arguments for Azure ServiceBus Topic creation.") - status := d.Get("status").(string) - - enableBatchedOps := d.Get("enable_batched_operations").(bool) - enableExpress := d.Get("enable_express").(bool) - enablePartitioning := d.Get("enable_partitioning").(bool) - maxSize := int32(d.Get("max_size_in_megabytes").(int)) - requiresDuplicateDetection := d.Get("requires_duplicate_detection").(bool) - supportOrdering := d.Get("support_ordering").(bool) - - var resourceId parse.TopicId + var id topics.TopicId if namespaceIdLit := d.Get("namespace_id").(string); namespaceIdLit != "" { - namespaceId, _ := parse.NamespaceID(namespaceIdLit) - resourceId = parse.NewTopicID(namespaceId.SubscriptionId, namespaceId.ResourceGroup, namespaceId.Name, d.Get("name").(string)) + namespaceId, err := topics.ParseNamespaceID(namespaceIdLit) + if err != nil { + return err + } + id = topics.NewTopicID(namespaceId.SubscriptionId, namespaceId.ResourceGroupName, namespaceId.NamespaceName, d.Get("name").(string)) } if d.IsNewResource() { - existing, err := client.Get(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.Name) + existing, err := client.Get(ctx, id) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("checking for presence of existing %s: %+v", resourceId, err) + if !response.WasNotFound(existing.HttpResponse) { + return fmt.Errorf("checking for presence of existing %s: %+v", id, err) } } - if !utils.ResponseWasNotFound(existing.Response) { - return tf.ImportAsExistsError("azurerm_service_fabric_cluster", resourceId.ID()) + if !response.WasNotFound(existing.HttpResponse) { + return tf.ImportAsExistsError("azurerm_service_fabric_cluster", id.ID()) } } - parameters := servicebus.SBTopic{ - Name: utils.String(resourceId.Name), - SBTopicProperties: &servicebus.SBTopicProperties{ - Status: servicebus.EntityStatus(status), - EnableBatchedOperations: utils.Bool(enableBatchedOps), - EnableExpress: utils.Bool(enableExpress), - EnablePartitioning: utils.Bool(enablePartitioning), - MaxSizeInMegabytes: utils.Int32(maxSize), - RequiresDuplicateDetection: utils.Bool(requiresDuplicateDetection), - SupportOrdering: utils.Bool(supportOrdering), + status := topics.EntityStatus(d.Get("status").(string)) + parameters := topics.SBTopic{ + Name: utils.String(id.TopicName), + Properties: &topics.SBTopicProperties{ + Status: &status, + EnableBatchedOperations: utils.Bool(d.Get("enable_batched_operations").(bool)), + EnableExpress: utils.Bool(d.Get("enable_express").(bool)), + EnablePartitioning: utils.Bool(d.Get("enable_partitioning").(bool)), + MaxSizeInMegabytes: utils.Int64(int64(d.Get("max_size_in_megabytes").(int))), + RequiresDuplicateDetection: utils.Bool(d.Get("requires_duplicate_detection").(bool)), + SupportOrdering: utils.Bool(d.Get("support_ordering").(bool)), }, } if autoDeleteOnIdle := d.Get("auto_delete_on_idle").(string); autoDeleteOnIdle != "" { - parameters.SBTopicProperties.AutoDeleteOnIdle = utils.String(autoDeleteOnIdle) + parameters.Properties.AutoDeleteOnIdle = utils.String(autoDeleteOnIdle) } if defaultTTL := d.Get("default_message_ttl").(string); defaultTTL != "" { - parameters.SBTopicProperties.DefaultMessageTimeToLive = utils.String(defaultTTL) + parameters.Properties.DefaultMessageTimeToLive = utils.String(defaultTTL) } if duplicateWindow := d.Get("duplicate_detection_history_time_window").(string); duplicateWindow != "" { - parameters.SBTopicProperties.DuplicateDetectionHistoryTimeWindow = utils.String(duplicateWindow) + parameters.Properties.DuplicateDetectionHistoryTimeWindow = utils.String(duplicateWindow) } // We need to retrieve the namespace because Premium namespace works differently from Basic and Standard namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient - namespace, err := namespacesClient.Get(ctx, resourceId.ResourceGroup, resourceId.NamespaceName) + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + resp, err := namespacesClient.Get(ctx, namespaceId) if err != nil { - return fmt.Errorf("retrieving ServiceBus Namespace %q (Resource Group %q): %+v", resourceId.NamespaceName, resourceId.ResourceGroup, err) + return fmt.Errorf("retrieving ServiceBus Namespace %q (Resource Group %q): %+v", id.NamespaceName, id.ResourceGroupName, err) } // output of `max_message_size_in_kilobytes` is also set in non-Premium namespaces, with a value of 256 if v, ok := d.GetOk("max_message_size_in_kilobytes"); ok && v.(int) != 256 { - if namespace.Sku.Name != servicebus.SkuNamePremium { - return fmt.Errorf("ServiceBus Topic %q does not support input on `max_message_size_in_kilobytes` in %s SKU and should be removed", resourceId.Name, namespace.Sku.Name) + if model := resp.Model; model != nil { + if model.Sku.Name != namespaces.SkuNamePremium { + return fmt.Errorf("%s does not support input on `max_message_size_in_kilobytes` in %s SKU and should be removed", id, model.Sku.Name) + } + parameters.Properties.MaxMessageSizeInKilobytes = utils.Int64(int64(v.(int))) } - parameters.SBTopicProperties.MaxMessageSizeInKilobytes = utils.Int64(int64(v.(int))) + } - if _, err := client.CreateOrUpdate(ctx, resourceId.ResourceGroup, resourceId.NamespaceName, resourceId.Name, parameters); err != nil { - return fmt.Errorf("creating/updating %s: %v", resourceId, err) + if _, err := client.CreateOrUpdate(ctx, id, parameters); err != nil { + return fmt.Errorf("creating/updating %s: %v", id, err) } - d.SetId(resourceId.ID()) + d.SetId(id.ID()) return resourceServiceBusTopicRead(d, meta) } @@ -221,58 +221,67 @@ func resourceServiceBusTopicRead(d *pluginsdk.ResourceData, meta interface{}) er ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.TopicID(d.Id()) + id, err := topics.ParseTopicID(d.Id()) if err != nil { return err } - resp, err := client.Get(ctx, id.ResourceGroup, id.NamespaceName, id.Name) + resp, err := client.Get(ctx, *id) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { + if response.WasNotFound(resp.HttpResponse) { d.SetId("") return nil } return fmt.Errorf("retrieving %s: %+v", id, err) } - d.Set("name", id.Name) - d.Set("namespace_id", parse.NewNamespaceID(id.SubscriptionId, id.ResourceGroup, id.NamespaceName).ID()) + d.Set("name", id.TopicName) + d.Set("namespace_id", topics.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName).ID()) - if props := resp.SBTopicProperties; props != nil { - d.Set("status", string(props.Status)) - d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) - d.Set("default_message_ttl", props.DefaultMessageTimeToLive) + if model := resp.Model; model != nil { + if props := model.Properties; props != nil { + status := "" + if v := props.Status; v != nil { + status = string(*v) + } + d.Set("status", status) + d.Set("auto_delete_on_idle", props.AutoDeleteOnIdle) + d.Set("default_message_ttl", props.DefaultMessageTimeToLive) - if window := props.DuplicateDetectionHistoryTimeWindow; window != nil && *window != "" { - d.Set("duplicate_detection_history_time_window", window) - } + if window := props.DuplicateDetectionHistoryTimeWindow; window != nil && *window != "" { + d.Set("duplicate_detection_history_time_window", window) + } - d.Set("enable_batched_operations", props.EnableBatchedOperations) - d.Set("enable_express", props.EnableExpress) - d.Set("enable_partitioning", props.EnablePartitioning) - d.Set("max_message_size_in_kilobytes", props.MaxMessageSizeInKilobytes) - d.Set("requires_duplicate_detection", props.RequiresDuplicateDetection) - d.Set("support_ordering", props.SupportOrdering) - - if maxSizeMB := props.MaxSizeInMegabytes; maxSizeMB != nil { - maxSize := int(*props.MaxSizeInMegabytes) - - // if the topic is in a premium namespace and partitioning is enabled then the - // max size returned by the API will be 16 times greater than the value set - if partitioning := props.EnablePartitioning; partitioning != nil && *partitioning { - namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient - namespace, err := namespacesClient.Get(ctx, id.ResourceGroup, id.NamespaceName) - if err != nil { - return err + d.Set("enable_batched_operations", props.EnableBatchedOperations) + d.Set("enable_express", props.EnableExpress) + d.Set("enable_partitioning", props.EnablePartitioning) + d.Set("max_message_size_in_kilobytes", props.MaxMessageSizeInKilobytes) + d.Set("requires_duplicate_detection", props.RequiresDuplicateDetection) + d.Set("support_ordering", props.SupportOrdering) + + if maxSizeMB := props.MaxSizeInMegabytes; maxSizeMB != nil { + maxSize := int(*props.MaxSizeInMegabytes) + + // if the topic is in a premium namespace and partitioning is enabled then the + // max size returned by the API will be 16 times greater than the value set + if partitioning := props.EnablePartitioning; partitioning != nil && *partitioning { + namespacesClient := meta.(*clients.Client).ServiceBus.NamespacesClient + namespaceId := namespaces.NewNamespaceID(id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) + namespaceResp, err := namespacesClient.Get(ctx, namespaceId) + if err != nil { + return err + } + + if namespaceModel := namespaceResp.Model; namespaceModel != nil { + if namespaceModel.Sku.Name != namespaces.SkuNamePremium { + const partitionCount = 16 + maxSize = int(*props.MaxSizeInMegabytes / partitionCount) + } + } } - if namespace.Sku.Name != servicebus.SkuNamePremium { - const partitionCount = 16 - maxSize = int(*props.MaxSizeInMegabytes / partitionCount) - } + d.Set("max_size_in_megabytes", maxSize) } - - d.Set("max_size_in_megabytes", maxSize) } } @@ -284,14 +293,14 @@ func resourceServiceBusTopicDelete(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.TopicID(d.Id()) + id, err := topics.ParseTopicID(d.Id()) if err != nil { return err } - resp, err := client.Delete(ctx, id.ResourceGroup, id.NamespaceName, id.Name) + resp, err := client.Delete(ctx, *id) if err != nil { - if !utils.ResponseWasNotFound(resp) { + if !response.WasNotFound(resp.HttpResponse) { return fmt.Errorf("deleting %s: %+v", id, err) } } diff --git a/internal/services/servicebus/servicebus_topic_resource_test.go b/internal/services/servicebus/servicebus_topic_resource_test.go index d5b718978705..8eac17ea09ce 100644 --- a/internal/services/servicebus/servicebus_topic_resource_test.go +++ b/internal/services/servicebus/servicebus_topic_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/servicebus/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -226,17 +226,17 @@ func TestAccServiceBusTopic_isoTimeSpanAttributes(t *testing.T) { } func (t ServiceBusTopicResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.TopicID(state.ID) + id, err := topics.ParseTopicID(state.ID) if err != nil { return nil, err } - resp, err := clients.ServiceBus.TopicsClient.Get(ctx, id.ResourceGroup, id.NamespaceName, id.Name) + resp, err := clients.ServiceBus.TopicsClient.Get(ctx, *id) if err != nil { - return nil, fmt.Errorf("reading Service Bus Topic (%s): %+v", id.String(), err) + return nil, fmt.Errorf("retrieving %s: %+v", *id, err) } - return utils.Bool(resp.ID != nil), nil + return utils.Bool(resp.Model != nil), nil } func (ServiceBusTopicResource) basic(data acceptance.TestData) string { diff --git a/internal/services/servicebus/transition.go b/internal/services/servicebus/transition.go new file mode 100644 index 000000000000..449c32f02993 --- /dev/null +++ b/internal/services/servicebus/transition.go @@ -0,0 +1,23 @@ +package servicebus + +import "github.com/hashicorp/terraform-provider-azurerm/utils" + +func expandTags(input map[string]interface{}) *map[string]string { + output := make(map[string]string) + for k, v := range input { + output[k] = v.(string) + } + return &output +} + +func flattenTags(input *map[string]string) map[string]*string { + output := make(map[string]*string) + + if input != nil { + for k, v := range *input { + output[k] = utils.String(v) + } + } + + return output +} diff --git a/internal/services/signalr/migration/network_acl_v0_to_v1.go b/internal/services/signalr/migration/network_acl_v0_to_v1.go index be5bd3044551..501da6dda575 100644 --- a/internal/services/signalr/migration/network_acl_v0_to_v1.go +++ b/internal/services/signalr/migration/network_acl_v0_to_v1.go @@ -5,7 +5,7 @@ import ( "fmt" "log" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/sdk/2020-05-01/signalr" + "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) diff --git a/internal/services/signalr/migration/service_v0_to_v1.go b/internal/services/signalr/migration/service_v0_to_v1.go index f11229b91db1..968d1a52109c 100644 --- a/internal/services/signalr/migration/service_v0_to_v1.go +++ b/internal/services/signalr/migration/service_v0_to_v1.go @@ -5,7 +5,7 @@ import ( "fmt" "log" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/sdk/2020-05-01/signalr" + "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" ) diff --git a/internal/services/signalr/signalr_service_data_source.go b/internal/services/signalr/signalr_service_data_source.go index 92d2ade7a45c..2ab75c7b3f4a 100644 --- a/internal/services/signalr/signalr_service_data_source.go +++ b/internal/services/signalr/signalr_service_data_source.go @@ -8,8 +8,8 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/sdk/2020-05-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" ) diff --git a/internal/services/signalr/signalr_service_network_acl_resource.go b/internal/services/signalr/signalr_service_network_acl_resource.go index ab6f5011201f..b770192bc3ee 100644 --- a/internal/services/signalr/signalr_service_network_acl_resource.go +++ b/internal/services/signalr/signalr_service_network_acl_resource.go @@ -5,11 +5,11 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/locks" networkValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/sdk/2020-05-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" @@ -197,6 +197,9 @@ func resourceSignalRServiceNetworkACLCreateUpdate(d *pluginsdk.ResourceData, met model.Properties.NetworkACLs = &networkACL } + // todo remove this when https://github.com/hashicorp/pandora/issues/1096 is fixed + model.SystemData = nil + if err := client.UpdateThenPoll(ctx, *id, model); err != nil { return fmt.Errorf("creating/updating NetworkACL for %s: %v", id, err) } @@ -299,6 +302,9 @@ func resourceSignalRServiceNetworkACLDelete(d *pluginsdk.ResourceData, meta inte model.Properties.NetworkACLs = networkACL } + // todo remove this when https://github.com/hashicorp/pandora/issues/1096 is fixed + model.SystemData = nil + if err := client.UpdateThenPoll(ctx, *id, model); err != nil { return fmt.Errorf("resetting the default Network ACL configuration for %s: %+v", *id, err) } diff --git a/internal/services/signalr/signalr_service_network_acl_resource_test.go b/internal/services/signalr/signalr_service_network_acl_resource_test.go index 969d16927eb2..6b04ec4d941d 100644 --- a/internal/services/signalr/signalr_service_network_acl_resource_test.go +++ b/internal/services/signalr/signalr_service_network_acl_resource_test.go @@ -5,10 +5,10 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/sdk/2020-05-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) diff --git a/internal/services/signalr/signalr_service_resource.go b/internal/services/signalr/signalr_service_resource.go index 96d60beae934..5b933d64184a 100644 --- a/internal/services/signalr/signalr_service_resource.go +++ b/internal/services/signalr/signalr_service_resource.go @@ -11,11 +11,12 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/go-azure-helpers/resourcemanager/tags" + "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/sdk/2020-05-01/signalr" signalrValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" @@ -106,9 +107,10 @@ func resourceArmSignalRServiceCreate(d *pluginsdk.ResourceData, meta interface{} resourceType := signalr.SignalRResource{ Location: utils.String(location), Properties: &signalr.SignalRProperties{ - Cors: expandSignalRCors(cors), - Features: &expandedFeatures, - Upstream: expandUpstreamSettings(upstreamSettings), + Cors: expandSignalRCors(cors), + Features: &expandedFeatures, + Upstream: expandUpstreamSettings(upstreamSettings), + LiveTraceConfiguration: expandSignalRLiveTraceConfig(d.Get("live_trace").([]interface{})), }, Sku: expandSignalRServiceSku(sku), Tags: tags.Expand(d.Get("tags").(map[string]interface{})), @@ -195,6 +197,10 @@ func resourceArmSignalRServiceRead(d *pluginsdk.ResourceData, meta interface{}) return fmt.Errorf("setting `upstream_endpoint`: %+v", err) } + if err := d.Set("live_trace", flattenSignalRLiveTraceConfig(props.LiveTraceConfiguration)); err != nil { + return fmt.Errorf("setting `live_trace`:%+v", err) + } + if err := tags.FlattenAndSet(d, model.Tags); err != nil { return err } @@ -223,7 +229,7 @@ func resourceArmSignalRServiceUpdate(d *pluginsdk.ResourceData, meta interface{} resourceType := signalr.SignalRResource{} - if d.HasChanges("cors", "features", "upstream_endpoint", "connectivity_logs_enabled", "messaging_logs_enabled", "service_mode", "live_trace_enabled") { + if d.HasChanges("cors", "features", "upstream_endpoint", "connectivity_logs_enabled", "messaging_logs_enabled", "service_mode", "live_trace_enabled", "live_trace") { resourceType.Properties = &signalr.SignalRProperties{} if d.HasChange("cors") { @@ -231,6 +237,10 @@ func resourceArmSignalRServiceUpdate(d *pluginsdk.ResourceData, meta interface{} resourceType.Properties.Cors = expandSignalRCors(corsRaw) } + if d.HasChange("live_trace") { + resourceType.Properties.LiveTraceConfiguration = expandSignalRLiveTraceConfig(d.Get("live_trace").([]interface{})) + } + if d.HasChanges("connectivity_logs_enabled", "messaging_logs_enabled", "service_mode", "live_trace_enabled") { features := make([]signalr.SignalRFeature, 0) if d.HasChange("connectivity_logs_enabled") { @@ -457,6 +467,101 @@ func flattenSignalRServiceSku(input *signalr.ResourceSku) []interface{} { } } +func expandSignalRLiveTraceConfig(input []interface{}) *signalr.LiveTraceConfiguration { + resourceCategories := make([]signalr.LiveTraceCategory, 0) + if len(input) == 0 || input[0] == nil { + return nil + } + + v := input[0].(map[string]interface{}) + + enabled := "false" + if v["enabled"].(bool) { + enabled = "true" + } + + messageLogEnabled := "false" + if v["messaging_logs_enabled"].(bool) { + messageLogEnabled = "true" + } + resourceCategories = append(resourceCategories, signalr.LiveTraceCategory{ + Name: utils.String("MessagingLogs"), + Enabled: utils.String(messageLogEnabled), + }) + + connectivityLogEnabled := "false" + if v["connectivity_logs_enabled"].(bool) { + connectivityLogEnabled = "true" + } + resourceCategories = append(resourceCategories, signalr.LiveTraceCategory{ + Name: utils.String("ConnectivityLogs"), + Enabled: utils.String(connectivityLogEnabled), + }) + + httpLogEnabled := "false" + if v["http_request_logs_enabled"].(bool) { + httpLogEnabled = "true" + } + resourceCategories = append(resourceCategories, signalr.LiveTraceCategory{ + Name: utils.String("HttpRequestLogs"), + Enabled: utils.String(httpLogEnabled), + }) + + return &signalr.LiveTraceConfiguration{ + Enabled: &enabled, + Categories: &resourceCategories, + } +} + +func flattenSignalRLiveTraceConfig(input *signalr.LiveTraceConfiguration) []interface{} { + result := make([]interface{}, 0) + if input == nil { + return result + } + + var enabled bool + if input.Enabled != nil { + enabled = strings.EqualFold(*input.Enabled, "true") + } + + var ( + messagingLogEnabled bool + connectivityLogEnabled bool + httpLogsEnabled bool + ) + + if input.Categories != nil { + for _, item := range *input.Categories { + name := "" + if item.Name != nil { + name = *item.Name + } + + var cateEnabled string + if item.Enabled != nil { + cateEnabled = *item.Enabled + } + + switch name { + case "MessagingLogs": + messagingLogEnabled = strings.EqualFold(cateEnabled, "true") + case "ConnectivityLogs": + connectivityLogEnabled = strings.EqualFold(cateEnabled, "true") + case "HttpRequestLogs": + httpLogsEnabled = strings.EqualFold(cateEnabled, "true") + default: + continue + } + } + } + return []interface{}{map[string]interface{}{ + "enabled": enabled, + "messaging_logs_enabled": messagingLogEnabled, + "connectivity_logs_enabled": connectivityLogEnabled, + "http_request_logs_enabled": httpLogsEnabled, + }} +} + func resourceArmSignalRServiceSchema() map[string]*pluginsdk.Schema { return map[string]*pluginsdk.Schema{ "name": { @@ -508,9 +613,43 @@ func resourceArmSignalRServiceSchema() map[string]*pluginsdk.Schema { }, "live_trace_enabled": { - Type: pluginsdk.TypeBool, + Type: pluginsdk.TypeBool, + Optional: true, + Default: false, + Deprecated: "`live_trace_enabled` has been deprecated in favor of `live_trace` and will be removed in 4.0.", + }, + + "live_trace": { + Type: pluginsdk.TypeList, Optional: true, - Default: false, + MaxItems: 1, + Elem: &pluginsdk.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: pluginsdk.TypeBool, + Optional: true, + Default: true, + }, + + "connectivity_logs_enabled": { + Type: pluginsdk.TypeBool, + Default: true, + Optional: true, + }, + + "messaging_logs_enabled": { + Type: pluginsdk.TypeBool, + Default: true, + Optional: true, + }, + + "http_request_logs_enabled": { + Type: pluginsdk.TypeBool, + Default: true, + Optional: true, + }, + }, + }, }, "service_mode": { diff --git a/internal/services/signalr/signalr_service_resource_test.go b/internal/services/signalr/signalr_service_resource_test.go index fd7806198364..c65a989edb02 100644 --- a/internal/services/signalr/signalr_service_resource_test.go +++ b/internal/services/signalr/signalr_service_resource_test.go @@ -6,10 +6,10 @@ import ( "testing" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/sdk/2020-05-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" ) @@ -433,6 +433,28 @@ func TestAccSignalRService_withTags(t *testing.T) { }) } +func TestAccSignalRService_liveTrace(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_signalr_service", "test") + r := SignalRServiceResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.liveTrace(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.liveTraceUpdated(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func (r SignalRServiceResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { id, err := signalr.ParseSignalRID(state.ID) if err != nil { @@ -738,3 +760,64 @@ resource "azurerm_signalr_service" "test" { } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } + +func (r SignalRServiceResource) liveTrace(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_signalr_service" "test" { + name = "acctestSignalR-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + + live_trace { + enabled = true + messaging_logs_enabled = false + connectivity_logs_enabled = true + } + + sku { + name = "Free_F1" + capacity = 1 + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} + +func (r SignalRServiceResource) liveTraceUpdated(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_signalr_service" "test" { + name = "acctestSignalR-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + + live_trace { + enabled = false + messaging_logs_enabled = true + connectivity_logs_enabled = false + http_request_logs_enabled = false + } + + sku { + name = "Free_F1" + capacity = 1 + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} diff --git a/internal/services/signalr/web_pubsub_resource.go b/internal/services/signalr/web_pubsub_resource.go index a39dc59aa921..cd59f324b9d6 100644 --- a/internal/services/signalr/web_pubsub_resource.go +++ b/internal/services/signalr/web_pubsub_resource.go @@ -6,11 +6,10 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" - "github.com/Azure/azure-sdk-for-go/services/webpubsub/mgmt/2021-10-01/webpubsub" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" diff --git a/internal/services/springcloud/client/client.go b/internal/services/springcloud/client/client.go index a228522165f9..9377d32c7ace 100644 --- a/internal/services/springcloud/client/client.go +++ b/internal/services/springcloud/client/client.go @@ -1,7 +1,7 @@ package client import ( - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/internal/common" ) diff --git a/internal/services/springcloud/spring_cloud_active_deployment_resource.go b/internal/services/springcloud/spring_cloud_active_deployment_resource.go index a0fbd4cea9ae..edc009eb697e 100644 --- a/internal/services/springcloud/spring_cloud_active_deployment_resource.go +++ b/internal/services/springcloud/spring_cloud_active_deployment_resource.go @@ -6,7 +6,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" diff --git a/internal/services/springcloud/spring_cloud_api_portal_custom_domain_resource.go b/internal/services/springcloud/spring_cloud_api_portal_custom_domain_resource.go index 6c0489982934..340b049fa1a0 100644 --- a/internal/services/springcloud/spring_cloud_api_portal_custom_domain_resource.go +++ b/internal/services/springcloud/spring_cloud_api_portal_custom_domain_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" diff --git a/internal/services/springcloud/spring_cloud_api_portal_resource.go b/internal/services/springcloud/spring_cloud_api_portal_resource.go index 2c0318c36c0d..07b446d70488 100644 --- a/internal/services/springcloud/spring_cloud_api_portal_resource.go +++ b/internal/services/springcloud/spring_cloud_api_portal_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" diff --git a/internal/services/springcloud/spring_cloud_app_cosmosdb_association_resource.go b/internal/services/springcloud/spring_cloud_app_cosmosdb_association_resource.go index 56364ff99c67..b95d9ef2fe7b 100644 --- a/internal/services/springcloud/spring_cloud_app_cosmosdb_association_resource.go +++ b/internal/services/springcloud/spring_cloud_app_cosmosdb_association_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" cosmosValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/cosmos/validate" diff --git a/internal/services/springcloud/spring_cloud_app_mysql_association_resource.go b/internal/services/springcloud/spring_cloud_app_mysql_association_resource.go index f072fd3b5b49..8f67a8979da2 100644 --- a/internal/services/springcloud/spring_cloud_app_mysql_association_resource.go +++ b/internal/services/springcloud/spring_cloud_app_mysql_association_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" mysqlValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/mysql/validate" diff --git a/internal/services/springcloud/spring_cloud_app_redis_association_resource.go b/internal/services/springcloud/spring_cloud_app_redis_association_resource.go index 39c2a24a4ffc..1ec7d4688361 100644 --- a/internal/services/springcloud/spring_cloud_app_redis_association_resource.go +++ b/internal/services/springcloud/spring_cloud_app_redis_association_resource.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" redisValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/redis/validate" diff --git a/internal/services/springcloud/spring_cloud_app_resource.go b/internal/services/springcloud/spring_cloud_app_resource.go index 0759a0c2c188..d2567c92637c 100644 --- a/internal/services/springcloud/spring_cloud_app_resource.go +++ b/internal/services/springcloud/spring_cloud_app_resource.go @@ -6,7 +6,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" diff --git a/internal/services/springcloud/spring_cloud_app_resource_test.go b/internal/services/springcloud/spring_cloud_app_resource_test.go index 8955b9944c2d..3be78f64ac5d 100644 --- a/internal/services/springcloud/spring_cloud_app_resource_test.go +++ b/internal/services/springcloud/spring_cloud_app_resource_test.go @@ -348,6 +348,16 @@ resource "azurerm_spring_cloud_service" "test" { resource "azurerm_spring_cloud_configuration_service" "test" { name = "default" spring_cloud_service_id = azurerm_spring_cloud_service.test.id + repository { + name = "fake" + label = "master" + patterns = ["app/dev", "app/prod"] + uri = "https://github.com/Azure-Samples/piggymetrics" + search_paths = ["dir1", "dir2"] + strict_host_key_checking = false + username = "adminuser" + password = "H@Sh1CoR3!" + } } resource "azurerm_spring_cloud_app" "test" { diff --git a/internal/services/springcloud/spring_cloud_build_deployment_resource.go b/internal/services/springcloud/spring_cloud_build_deployment_resource.go index a36712e5233d..6cdb22f70da7 100644 --- a/internal/services/springcloud/spring_cloud_build_deployment_resource.go +++ b/internal/services/springcloud/spring_cloud_build_deployment_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" @@ -56,6 +56,14 @@ func resourceSpringCloudBuildDeployment() *pluginsdk.Resource { ValidateFunc: validation.StringIsNotEmpty, }, + "addon_json": { + Type: pluginsdk.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringIsJSON, + DiffSuppressFunc: pluginsdk.SuppressJsonDiff, + }, + "environment_variables": { Type: pluginsdk.TypeMap, Optional: true, @@ -83,30 +91,16 @@ func resourceSpringCloudBuildDeployment() *pluginsdk.Resource { Type: pluginsdk.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice([]string{ - "500m", - "1", - "2", - "3", - "4", - }, false), + // NOTE: we're intentionally not validating this field since additional values are possible when enabled by the service team + ValidateFunc: validation.StringIsNotEmpty, }, "memory": { Type: pluginsdk.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice([]string{ - "512Mi", - "1Gi", - "2Gi", - "3Gi", - "4Gi", - "5Gi", - "6Gi", - "7Gi", - "8Gi", - }, false), + // NOTE: we're intentionally not validating this field since additional values are possible when enabled by the service team + ValidateFunc: validation.StringIsNotEmpty, }, }, }, @@ -149,6 +143,11 @@ func resourceSpringCloudBuildDeploymentCreateUpdate(d *pluginsdk.ResourceData, m return fmt.Errorf("invalid `sku` for Spring Cloud Service %q (Resource Group %q)", appId.SpringName, appId.ResourceGroup) } + addonConfig, err := expandSpringCloudAppAddon(d.Get("addon_json").(string)) + if err != nil { + return err + } + deployment := appplatform.DeploymentResource{ Sku: &appplatform.Sku{ Name: service.Sku.Name, @@ -160,6 +159,7 @@ func resourceSpringCloudBuildDeploymentCreateUpdate(d *pluginsdk.ResourceData, m BuildResultID: utils.String(d.Get("build_result_id").(string)), }, DeploymentSettings: &appplatform.DeploymentSettings{ + AddonConfigs: addonConfig, EnvironmentVariables: expandSpringCloudDeploymentEnvironmentVariables(d.Get("environment_variables").(map[string]interface{})), ResourceRequests: expandSpringCloudBuildDeploymentResourceRequests(d.Get("quota").([]interface{})), }, @@ -211,6 +211,9 @@ func resourceSpringCloudBuildDeploymentRead(d *pluginsdk.ResourceData, meta inte if err := d.Set("quota", flattenSpringCloudDeploymentResourceRequests(settings.ResourceRequests)); err != nil { return fmt.Errorf("setting `quota`: %+v", err) } + if err := d.Set("addon_json", flattenSpringCloudAppAddon(settings.AddonConfigs)); err != nil { + return fmt.Errorf("setting `addon_json`: %s", err) + } } if source, ok := resp.Properties.Source.AsBuildResultUserSourceInfo(); ok && source != nil { d.Set("build_result_id", source.BuildResultID) diff --git a/internal/services/springcloud/spring_cloud_build_deployment_resource_test.go b/internal/services/springcloud/spring_cloud_build_deployment_resource_test.go index aef116efedfb..9678351d4d1c 100644 --- a/internal/services/springcloud/spring_cloud_build_deployment_resource_test.go +++ b/internal/services/springcloud/spring_cloud_build_deployment_resource_test.go @@ -60,6 +60,28 @@ func TestAccSpringCloudBuildDeployment_complete(t *testing.T) { }) } +func TestAccSpringCloudBuildDeployment_addon(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_spring_cloud_build_deployment", "test") + r := SpringCloudBuildDeploymentResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.addon(data, "app/dev"), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.addon(data, "app/prod"), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccSpringCloudBuildDeployment_update(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_spring_cloud_build_deployment", "test") r := SpringCloudBuildDeploymentResource{} @@ -149,6 +171,33 @@ resource "azurerm_spring_cloud_build_deployment" "test" { `, r.template(data), data.RandomString) } +func (r SpringCloudBuildDeploymentResource) addon(data acceptance.TestData, pattern string) string { + return fmt.Sprintf(` +%s + +resource "azurerm_spring_cloud_build_deployment" "test" { + name = "acctest-scjd%s" + spring_cloud_app_id = azurerm_spring_cloud_app.test.id + build_result_id = "" + instance_count = 2 + + environment_variables = { + "Foo" : "Bar" + "Env" : "Staging" + } + quota { + cpu = "2" + memory = "2Gi" + } + addon_json = jsonencode({ + applicationConfigurationService = { + configFilePatterns = "%s" + } + }) +} +`, SpringCloudAppResource{}.addon(data), data.RandomString, pattern) +} + func (SpringCloudBuildDeploymentResource) template(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/springcloud/spring_cloud_build_pack_binding_resource.go b/internal/services/springcloud/spring_cloud_build_pack_binding_resource.go index 76143b73fb98..9a75723d0d8b 100644 --- a/internal/services/springcloud/spring_cloud_build_pack_binding_resource.go +++ b/internal/services/springcloud/spring_cloud_build_pack_binding_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" diff --git a/internal/services/springcloud/spring_cloud_builder_resource.go b/internal/services/springcloud/spring_cloud_builder_resource.go index a3caf8d5c930..290a93c4c2ec 100644 --- a/internal/services/springcloud/spring_cloud_builder_resource.go +++ b/internal/services/springcloud/spring_cloud_builder_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" diff --git a/internal/services/springcloud/spring_cloud_certificate_resource.go b/internal/services/springcloud/spring_cloud_certificate_resource.go index 62946bac055b..75392c7f16c1 100644 --- a/internal/services/springcloud/spring_cloud_certificate_resource.go +++ b/internal/services/springcloud/spring_cloud_certificate_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" diff --git a/internal/services/springcloud/spring_cloud_configuration_service_resource.go b/internal/services/springcloud/spring_cloud_configuration_service_resource.go index ef0875621595..2d15d984a48b 100644 --- a/internal/services/springcloud/spring_cloud_configuration_service_resource.go +++ b/internal/services/springcloud/spring_cloud_configuration_service_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" diff --git a/internal/services/springcloud/spring_cloud_container_deployment_resource.go b/internal/services/springcloud/spring_cloud_container_deployment_resource.go index 6332c358bb36..0d4be752d361 100644 --- a/internal/services/springcloud/spring_cloud_container_deployment_resource.go +++ b/internal/services/springcloud/spring_cloud_container_deployment_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" @@ -62,6 +62,14 @@ func resourceSpringCloudContainerDeployment() *pluginsdk.Resource { ValidateFunc: validation.StringIsNotEmpty, }, + "addon_json": { + Type: pluginsdk.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.StringIsJSON, + DiffSuppressFunc: pluginsdk.SuppressJsonDiff, + }, + "arguments": { Type: pluginsdk.TypeList, Optional: true, @@ -115,30 +123,16 @@ func resourceSpringCloudContainerDeployment() *pluginsdk.Resource { Type: pluginsdk.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice([]string{ - "500m", - "1", - "2", - "3", - "4", - }, false), + // NOTE: we're intentionally not validating this field since additional values are possible when enabled by the service team + ValidateFunc: validation.StringIsNotEmpty, }, "memory": { Type: pluginsdk.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice([]string{ - "512Mi", - "1Gi", - "2Gi", - "3Gi", - "4Gi", - "5Gi", - "6Gi", - "7Gi", - "8Gi", - }, false), + // NOTE: we're intentionally not validating this field since additional values are possible when enabled by the service team + ValidateFunc: validation.StringIsNotEmpty, }, }, }, @@ -181,6 +175,11 @@ func resourceSpringCloudContainerDeploymentCreateUpdate(d *pluginsdk.ResourceDat return fmt.Errorf("invalid `sku` for Spring Cloud Service %q (Resource Group %q)", appId.SpringName, appId.ResourceGroup) } + addonConfig, err := expandSpringCloudAppAddon(d.Get("addon_json").(string)) + if err != nil { + return err + } + deployment := appplatform.DeploymentResource{ Sku: &appplatform.Sku{ Name: service.Sku.Name, @@ -198,6 +197,7 @@ func resourceSpringCloudContainerDeploymentCreateUpdate(d *pluginsdk.ResourceDat }, }, DeploymentSettings: &appplatform.DeploymentSettings{ + AddonConfigs: addonConfig, EnvironmentVariables: expandSpringCloudDeploymentEnvironmentVariables(d.Get("environment_variables").(map[string]interface{})), ResourceRequests: expandSpringCloudContainerDeploymentResourceRequests(d.Get("quota").([]interface{})), }, @@ -249,6 +249,9 @@ func resourceSpringCloudContainerDeploymentRead(d *pluginsdk.ResourceData, meta if err := d.Set("quota", flattenSpringCloudDeploymentResourceRequests(settings.ResourceRequests)); err != nil { return fmt.Errorf("setting `quota`: %+v", err) } + if err := d.Set("addon_json", flattenSpringCloudAppAddon(settings.AddonConfigs)); err != nil { + return fmt.Errorf("setting `addon_json`: %s", err) + } } if source, ok := resp.Properties.Source.AsCustomContainerUserSourceInfo(); ok && source != nil { if container := source.CustomContainer; container != nil { diff --git a/internal/services/springcloud/spring_cloud_container_deployment_resource_test.go b/internal/services/springcloud/spring_cloud_container_deployment_resource_test.go index bac3f4f7b4d9..e05e127cac44 100644 --- a/internal/services/springcloud/spring_cloud_container_deployment_resource_test.go +++ b/internal/services/springcloud/spring_cloud_container_deployment_resource_test.go @@ -60,6 +60,28 @@ func TestAccSpringCloudContainerDeployment_complete(t *testing.T) { }) } +func TestAccSpringCloudContainerDeployment_addon(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_spring_cloud_container_deployment", "test") + r := SpringCloudContainerDeploymentResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.addon(data, "app/dev"), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.addon(data, "app/prod"), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccSpringCloudContainerDeployment_update(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_spring_cloud_container_deployment", "test") r := SpringCloudContainerDeploymentResource{} @@ -137,8 +159,8 @@ resource "azurerm_spring_cloud_container_deployment" "test" { name = "acctest-scjd%s" spring_cloud_app_id = azurerm_spring_cloud_app.test.id instance_count = 2 - arguments = ["-c", "echo hello"] - commands = ["/bin/sh"] + arguments = ["-cp", "/app/resources:/app/classes:/app/libs/*", "hello.Application"] + commands = ["java"] environment_variables = { "Foo" : "Bar" "Env" : "Staging" @@ -150,6 +172,32 @@ resource "azurerm_spring_cloud_container_deployment" "test" { `, r.template(data), data.RandomString) } +func (r SpringCloudContainerDeploymentResource) addon(data acceptance.TestData, pattern string) string { + return fmt.Sprintf(` +%s + +resource "azurerm_spring_cloud_container_deployment" "test" { + name = "acctest-scjd%s" + spring_cloud_app_id = azurerm_spring_cloud_app.test.id + instance_count = 2 + arguments = ["-cp", "/app/resources:/app/classes:/app/libs/*", "hello.Application"] + commands = ["java"] + environment_variables = { + "Foo" : "Bar" + "Env" : "Staging" + } + server = "docker.io" + image = "springio/gs-spring-boot-docker" + language_framework = "springboot" + addon_json = jsonencode({ + applicationConfigurationService = { + configFilePatterns = "%s" + } + }) +} +`, SpringCloudAppResource{}.addon(data), data.RandomString, pattern) +} + func (SpringCloudContainerDeploymentResource) template(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/internal/services/springcloud/spring_cloud_custom_domain_resource.go b/internal/services/springcloud/spring_cloud_custom_domain_resource.go index d729a380345b..af4272c5864a 100644 --- a/internal/services/springcloud/spring_cloud_custom_domain_resource.go +++ b/internal/services/springcloud/spring_cloud_custom_domain_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" diff --git a/internal/services/springcloud/spring_cloud_gateway_custom_domain_resource.go b/internal/services/springcloud/spring_cloud_gateway_custom_domain_resource.go index fac14da63d7c..e3dc44882e83 100644 --- a/internal/services/springcloud/spring_cloud_gateway_custom_domain_resource.go +++ b/internal/services/springcloud/spring_cloud_gateway_custom_domain_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" diff --git a/internal/services/springcloud/spring_cloud_gateway_resource.go b/internal/services/springcloud/spring_cloud_gateway_resource.go index 398aac826626..eb99d0e8bd1b 100644 --- a/internal/services/springcloud/spring_cloud_gateway_resource.go +++ b/internal/services/springcloud/spring_cloud_gateway_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" @@ -182,30 +182,16 @@ func resourceSpringCloudGateway() *pluginsdk.Resource { Type: pluginsdk.TypeString, Optional: true, Default: "1", - ValidateFunc: validation.StringInSlice([]string{ - "500m", - "1", - "2", - "3", - "4", - }, false), + // NOTE: we're intentionally not validating this field since additional values are possible when enabled by the service team + ValidateFunc: validation.StringIsNotEmpty, }, "memory": { Type: pluginsdk.TypeString, Optional: true, Default: "2Gi", - ValidateFunc: validation.StringInSlice([]string{ - "512Mi", - "1Gi", - "2Gi", - "3Gi", - "4Gi", - "5Gi", - "6Gi", - "7Gi", - "8Gi", - }, false), + // NOTE: we're intentionally not validating this field since additional values are possible when enabled by the service team + ValidateFunc: validation.StringIsNotEmpty, }, }, }, diff --git a/internal/services/springcloud/spring_cloud_gateway_route_config_resource.go b/internal/services/springcloud/spring_cloud_gateway_route_config_resource.go index c2639ed0a428..45acabb0c7fd 100644 --- a/internal/services/springcloud/spring_cloud_gateway_route_config_resource.go +++ b/internal/services/springcloud/spring_cloud_gateway_route_config_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" @@ -108,7 +108,7 @@ func resourceSpringCloudGatewayRouteConfig() *pluginsdk.Resource { "uri": { Type: pluginsdk.TypeString, Optional: true, - ValidateFunc: validation.IsURLWithHTTPorHTTPS, + ValidateFunc: validation.StringIsNotEmpty, }, "classification_tags": { diff --git a/internal/services/springcloud/spring_cloud_java_deployment_resource.go b/internal/services/springcloud/spring_cloud_java_deployment_resource.go index 42380699ecb4..788439f21be6 100644 --- a/internal/services/springcloud/spring_cloud_java_deployment_resource.go +++ b/internal/services/springcloud/spring_cloud_java_deployment_resource.go @@ -6,7 +6,7 @@ import ( "strconv" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" @@ -356,13 +356,8 @@ func resourceSprintCloudJavaDeploymentSchema() map[string]*pluginsdk.Schema { Type: pluginsdk.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice([]string{ - "500m", - "1", - "2", - "3", - "4", - }, false), + // NOTE: we're intentionally not validating this field since additional values are possible when enabled by the service team + ValidateFunc: validation.StringIsNotEmpty, }, // The value returned in GET will be recalculated by the service if the deprecated "memory_in_gb" is honored, so make this property as Computed. @@ -370,17 +365,8 @@ func resourceSprintCloudJavaDeploymentSchema() map[string]*pluginsdk.Schema { Type: pluginsdk.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice([]string{ - "512Mi", - "1Gi", - "2Gi", - "3Gi", - "4Gi", - "5Gi", - "6Gi", - "7Gi", - "8Gi", - }, false), + // NOTE: we're intentionally not validating this field since additional values are possible when enabled by the service team + ValidateFunc: validation.StringIsNotEmpty, }, }, }, diff --git a/internal/services/springcloud/spring_cloud_service_resource.go b/internal/services/springcloud/spring_cloud_service_resource.go index 12835ef69642..b4dab7197184 100644 --- a/internal/services/springcloud/spring_cloud_service_resource.go +++ b/internal/services/springcloud/spring_cloud_service_resource.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" diff --git a/internal/services/springcloud/spring_cloud_storage_resource.go b/internal/services/springcloud/spring_cloud_storage_resource.go index 785684dbd962..280b99c303ca 100644 --- a/internal/services/springcloud/spring_cloud_storage_resource.go +++ b/internal/services/springcloud/spring_cloud_storage_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" + "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/springcloud/parse" diff --git a/internal/services/storage/client/client.go b/internal/services/storage/client/client.go index ee85dccb1711..ce8fd84d421b 100644 --- a/internal/services/storage/client/client.go +++ b/internal/services/storage/client/client.go @@ -7,9 +7,9 @@ import ( "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-04-01/storage" "github.com/Azure/azure-sdk-for-go/services/storagesync/mgmt/2020-03-01/storagesync" "github.com/Azure/go-autorest/autorest" - az "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies" "github.com/hashicorp/terraform-provider-azurerm/internal/common" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/sdk/2021-04-01/objectreplicationpolicies" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/shim" "github.com/tombuildsstuff/giovanni/storage/2019-12-12/blob/accounts" "github.com/tombuildsstuff/giovanni/storage/2019-12-12/blob/blobs" @@ -33,7 +33,7 @@ type Client struct { BlobInventoryPoliciesClient *storage.BlobInventoryPoliciesClient CloudEndpointsClient *storagesync.CloudEndpointsClient EncryptionScopesClient *storage.EncryptionScopesClient - Environment az.Environment + Environment azure.Environment FileServicesClient *storage.FileServicesClient ObjectReplicationClient *objectreplicationpolicies.ObjectReplicationPoliciesClient SyncServiceClient *storagesync.ServicesClient diff --git a/internal/services/storage/parse/object_replication.go b/internal/services/storage/parse/object_replication.go index ed8712c5babe..fb30b5c638c3 100644 --- a/internal/services/storage/parse/object_replication.go +++ b/internal/services/storage/parse/object_replication.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/sdk/2021-04-01/objectreplicationpolicies" + "github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies" ) // This is manual for concat two ids are not supported in auto-generation diff --git a/internal/services/storage/parse/object_replication_test.go b/internal/services/storage/parse/object_replication_test.go index 7ffaeb52d907..977fe33563be 100644 --- a/internal/services/storage/parse/object_replication_test.go +++ b/internal/services/storage/parse/object_replication_test.go @@ -5,8 +5,8 @@ package parse import ( "testing" + "github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies" "github.com/hashicorp/terraform-provider-azurerm/internal/resourceid" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/sdk/2021-04-01/objectreplicationpolicies" ) var _ resourceid.Formatter = ObjectReplicationId{} diff --git a/internal/services/storage/storage_management_policy_data_source.go b/internal/services/storage/storage_management_policy_data_source.go index fe9e68592522..5c7946a66212 100644 --- a/internal/services/storage/storage_management_policy_data_source.go +++ b/internal/services/storage/storage_management_policy_data_source.go @@ -102,6 +102,18 @@ func dataSourceStorageManagementPolicy() *pluginsdk.Resource { Type: pluginsdk.TypeInt, Computed: true, }, + "tier_to_archive_after_days_since_last_access_time_greater_than": { + Type: pluginsdk.TypeInt, + Computed: true, + }, + "delete_after_days_since_last_access_time_greater_than": { + Type: pluginsdk.TypeInt, + Computed: true, + }, + "tier_to_cool_after_days_since_last_access_time_greater_than": { + Type: pluginsdk.TypeInt, + Computed: true, + }, }, }, }, @@ -167,7 +179,7 @@ func dataSourceStorageManagementPolicyRead(d *pluginsdk.ResourceData, meta inter } id := parse.NewStorageAccountManagementPolicyID(storageAccountId.SubscriptionId, storageAccountId.ResourceGroup, storageAccountId.Name, "default") - resp, err := client.Get(ctx, id.ResourceGroup, id.ManagementPolicyName) + resp, err := client.Get(ctx, id.ResourceGroup, id.StorageAccountName) if err != nil { if utils.ResponseWasNotFound(resp.Response) { return fmt.Errorf("%s was not found", id) diff --git a/internal/services/storage/storage_object_replication_resource.go b/internal/services/storage/storage_object_replication_resource.go index fb4a766eda93..f1aafae26bcd 100644 --- a/internal/services/storage/storage_object_replication_resource.go +++ b/internal/services/storage/storage_object_replication_resource.go @@ -6,10 +6,10 @@ import ( "time" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/sdk/2021-04-01/objectreplicationpolicies" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" diff --git a/internal/services/streamanalytics/stream_analytics_output_blob_resource.go b/internal/services/streamanalytics/stream_analytics_output_blob_resource.go index 68758b495aa1..6638b1254a84 100644 --- a/internal/services/streamanalytics/stream_analytics_output_blob_resource.go +++ b/internal/services/streamanalytics/stream_analytics_output_blob_resource.go @@ -64,13 +64,6 @@ func resourceStreamAnalyticsOutputBlob() *pluginsdk.Resource { Required: true, }, - "storage_account_key": { - Type: pluginsdk.TypeString, - Required: true, - Sensitive: true, - ValidateFunc: validation.StringIsNotEmpty, - }, - "storage_account_name": { Type: pluginsdk.TypeString, Required: true, @@ -91,6 +84,16 @@ func resourceStreamAnalyticsOutputBlob() *pluginsdk.Resource { "serialization": schemaStreamAnalyticsOutputSerialization(), + "authentication_mode": { + Type: pluginsdk.TypeString, + Optional: true, + Default: string(streamanalytics.AuthenticationModeConnectionString), + ValidateFunc: validation.StringInSlice([]string{ + string(streamanalytics.AuthenticationModeConnectionString), + string(streamanalytics.AuthenticationModeMsi), + }, false), + }, + "batch_max_wait_time": { Type: pluginsdk.TypeString, Optional: true, @@ -101,6 +104,13 @@ func resourceStreamAnalyticsOutputBlob() *pluginsdk.Resource { Optional: true, ValidateFunc: validation.FloatBetween(0, 10000), }, + + "storage_account_key": { + Type: pluginsdk.TypeString, + Optional: true, + Sensitive: true, + ValidateFunc: validation.StringIsNotEmpty, + }, }, } } @@ -129,7 +139,6 @@ func resourceStreamAnalyticsOutputBlobCreateUpdate(d *pluginsdk.ResourceData, me containerName := d.Get("storage_container_name").(string) dateFormat := d.Get("date_format").(string) pathPattern := d.Get("path_pattern").(string) - storageAccountKey := d.Get("storage_account_key").(string) storageAccountName := d.Get("storage_account_name").(string) timeFormat := d.Get("time_format").(string) @@ -147,14 +156,15 @@ func resourceStreamAnalyticsOutputBlobCreateUpdate(d *pluginsdk.ResourceData, me BlobOutputDataSourceProperties: &streamanalytics.BlobOutputDataSourceProperties{ StorageAccounts: &[]streamanalytics.StorageAccount{ { - AccountKey: utils.String(storageAccountKey), + AccountKey: getStorageAccountKey(d.Get("storage_account_key").(string)), AccountName: utils.String(storageAccountName), }, }, - Container: utils.String(containerName), - DateFormat: utils.String(dateFormat), - PathPattern: utils.String(pathPattern), - TimeFormat: utils.String(timeFormat), + Container: utils.String(containerName), + DateFormat: utils.String(dateFormat), + PathPattern: utils.String(pathPattern), + TimeFormat: utils.String(timeFormat), + AuthenticationMode: streamanalytics.AuthenticationMode(d.Get("authentication_mode").(string)), }, }, Serialization: serialization, @@ -223,6 +233,7 @@ func resourceStreamAnalyticsOutputBlobRead(d *pluginsdk.ResourceData, meta inter d.Set("path_pattern", v.PathPattern) d.Set("storage_container_name", v.Container) d.Set("time_format", v.TimeFormat) + d.Set("authentication_mode", v.AuthenticationMode) if accounts := v.StorageAccounts; accounts != nil && len(*accounts) > 0 { account := (*accounts)[0] @@ -257,3 +268,11 @@ func resourceStreamAnalyticsOutputBlobDelete(d *pluginsdk.ResourceData, meta int return nil } + +func getStorageAccountKey(input string) *string { + if input == "" { + return nil + } + + return utils.String(input) +} diff --git a/internal/services/streamanalytics/stream_analytics_output_blob_resource_test.go b/internal/services/streamanalytics/stream_analytics_output_blob_resource_test.go index 2b2ea22541dc..86bab171b238 100644 --- a/internal/services/streamanalytics/stream_analytics_output_blob_resource_test.go +++ b/internal/services/streamanalytics/stream_analytics_output_blob_resource_test.go @@ -110,6 +110,29 @@ func TestAccStreamAnalyticsOutputBlob_requiresImport(t *testing.T) { }) } +func TestAccStreamAnalyticsOutputBlob_authenticationMode(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_stream_analytics_output_blob", "test") + r := StreamAnalyticsOutputBlobResource{} + identity := "identity { type = \"SystemAssigned\" }" + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.csv(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("storage_account_key"), + { + Config: r.authenticationMode(data, identity), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep("storage_account_key"), + }) +} + func (r StreamAnalyticsOutputBlobResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { name := state.Attributes["name"] jobName := state.Attributes["stream_analytics_job_name"] @@ -126,7 +149,7 @@ func (r StreamAnalyticsOutputBlobResource) Exists(ctx context.Context, client *c } func (r StreamAnalyticsOutputBlobResource) avro(data acceptance.TestData) string { - template := r.template(data) + template := r.template(data, "") return fmt.Sprintf(` %s @@ -149,7 +172,7 @@ resource "azurerm_stream_analytics_output_blob" "test" { } func (r StreamAnalyticsOutputBlobResource) csv(data acceptance.TestData) string { - template := r.template(data) + template := r.template(data, "") return fmt.Sprintf(` %s @@ -174,7 +197,7 @@ resource "azurerm_stream_analytics_output_blob" "test" { } func (r StreamAnalyticsOutputBlobResource) json(data acceptance.TestData) string { - template := r.template(data) + template := r.template(data, "") return fmt.Sprintf(` %s @@ -199,7 +222,7 @@ resource "azurerm_stream_analytics_output_blob" "test" { } func (r StreamAnalyticsOutputBlobResource) parquet(data acceptance.TestData) string { - template := r.template(data) + template := r.template(data, "") return fmt.Sprintf(` %s @@ -224,7 +247,7 @@ resource "azurerm_stream_analytics_output_blob" "test" { } func (r StreamAnalyticsOutputBlobResource) updated(data acceptance.TestData) string { - template := r.template(data) + template := r.template(data, "") return fmt.Sprintf(` %s @@ -287,7 +310,31 @@ resource "azurerm_stream_analytics_output_blob" "import" { `, template) } -func (r StreamAnalyticsOutputBlobResource) template(data acceptance.TestData) string { +func (r StreamAnalyticsOutputBlobResource) authenticationMode(data acceptance.TestData, identity string) string { + return fmt.Sprintf(` +%s + +resource "azurerm_stream_analytics_output_blob" "test" { + name = "acctestinput-%d" + stream_analytics_job_name = azurerm_stream_analytics_job.test.name + resource_group_name = azurerm_stream_analytics_job.test.resource_group_name + storage_account_name = azurerm_storage_account.test.name + storage_container_name = azurerm_storage_container.test.name + path_pattern = "some-pattern" + date_format = "yyyy-MM-dd" + time_format = "HH" + authentication_mode = "Msi" + + serialization { + type = "Csv" + encoding = "UTF8" + field_delimiter = "," + } +} +`, r.template(data, identity), data.RandomInteger) +} + +func (r StreamAnalyticsOutputBlobResource) template(data acceptance.TestData, identity string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -330,6 +377,7 @@ resource "azurerm_stream_analytics_job" "test" { FROM [YourInputAlias] QUERY + %s } -`, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomInteger, identity) } diff --git a/internal/services/synapse/synapse_integration_runtime_azure_resource.go b/internal/services/synapse/synapse_integration_runtime_azure_resource.go index a48e0e3a3525..7191b27d034b 100644 --- a/internal/services/synapse/synapse_integration_runtime_azure_resource.go +++ b/internal/services/synapse/synapse_integration_runtime_azure_resource.go @@ -6,6 +6,7 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/synapse/mgmt/2021-03-01/synapse" + "github.com/hashicorp/go-azure-helpers/resourcemanager/location" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" @@ -54,7 +55,17 @@ func resourceSynapseIntegrationRuntimeAzure() *pluginsdk.Resource { ValidateFunc: validate.WorkspaceID, }, - "location": azure.SchemaLocation(), + "location": { + Type: pluginsdk.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.Any( + location.EnhancedValidate, + validation.StringInSlice([]string{"AutoResolve"}, false), + ), + StateFunc: location.StateFunc, + DiffSuppressFunc: location.DiffSuppressFunc, + }, "compute_type": { Type: pluginsdk.TypeString, diff --git a/internal/services/synapse/synapse_integration_runtime_azure_resource_test.go b/internal/services/synapse/synapse_integration_runtime_azure_resource_test.go index 49ca923cff9d..3382c10517f0 100644 --- a/internal/services/synapse/synapse_integration_runtime_azure_resource_test.go +++ b/internal/services/synapse/synapse_integration_runtime_azure_resource_test.go @@ -89,6 +89,20 @@ func TestAccSynapseIntegrationRuntimeAzure_update(t *testing.T) { }) } +func TestAccSynapseIntegrationRuntimeAzure_autoResolve(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_synapse_integration_runtime_azure", "test") + r := IntegrationRuntimeAzureResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.autoResolve(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + }) +} + func (r IntegrationRuntimeAzureResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { id, err := parse.IntegrationRuntimeID(state.ID) if err != nil { @@ -113,6 +127,18 @@ resource "azurerm_synapse_integration_runtime_azure" "test" { `, r.template(data)) } +func (r IntegrationRuntimeAzureResource) autoResolve(data acceptance.TestData) string { + return fmt.Sprintf(` +%s + +resource "azurerm_synapse_integration_runtime_azure" "test" { + name = "azure-integration-runtime" + synapse_workspace_id = azurerm_synapse_workspace.test.id + location = "AutoResolve" +} +`, r.template(data)) +} + func (r IntegrationRuntimeAzureResource) requiresImport(data acceptance.TestData) string { return fmt.Sprintf(` %s diff --git a/internal/services/trafficmanager/azure_endpoint_resource.go b/internal/services/trafficmanager/azure_endpoint_resource.go index 2d74ce052597..311c08de7884 100644 --- a/internal/services/trafficmanager/azure_endpoint_resource.go +++ b/internal/services/trafficmanager/azure_endpoint_resource.go @@ -67,7 +67,8 @@ func resourceAzureEndpoint() *pluginsdk.Resource { "weight": { Type: pluginsdk.TypeInt, - Required: true, + Optional: true, + Computed: true, ValidateFunc: validation.IntBetween(1, 1000), }, @@ -174,7 +175,6 @@ func resourceAzureEndpointCreateUpdate(d *pluginsdk.ResourceData, meta interface EndpointStatus: &status, TargetResourceId: utils.String(d.Get("target_resource_id").(string)), Subnets: expandEndpointSubnetConfig(d.Get("subnet").([]interface{})), - Weight: utils.Int64(int64(d.Get("weight").(int))), }, } @@ -182,6 +182,10 @@ func resourceAzureEndpointCreateUpdate(d *pluginsdk.ResourceData, meta interface params.Properties.Priority = utils.Int64(int64(priority)) } + if weight := d.Get("weight").(int); weight != 0 { + params.Properties.Weight = utils.Int64(int64(weight)) + } + inputMappings := d.Get("geo_mappings").([]interface{}) geoMappings := make([]string, 0) for _, v := range inputMappings { diff --git a/internal/services/trafficmanager/azure_endpoint_resource_test.go b/internal/services/trafficmanager/azure_endpoint_resource_test.go index f753e2e2b1a0..ebbbb4152cca 100644 --- a/internal/services/trafficmanager/azure_endpoint_resource_test.go +++ b/internal/services/trafficmanager/azure_endpoint_resource_test.go @@ -31,6 +31,21 @@ func TestAccAzureEndpoint_basic(t *testing.T) { }) } +func TestAccAzureEndpoint_priority(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_traffic_manager_azure_endpoint", "test") + r := AzureEndpointResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.priority(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccAzureEndpoint_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_traffic_manager_azure_endpoint", "test") r := AzureEndpointResource{} @@ -133,6 +148,50 @@ resource "azurerm_traffic_manager_azure_endpoint" "test" { `, template, data.RandomInteger) } +func (r AzureEndpointResource) priority(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-traffic-%[1]d" + location = "%[2]s" +} + +resource "azurerm_traffic_manager_profile" "test" { + name = "acctest-TMP-%[1]d" + resource_group_name = azurerm_resource_group.test.name + traffic_routing_method = "Priority" + + dns_config { + relative_name = "acctest-tmp-%[1]d" + ttl = 30 + } + + monitor_config { + protocol = "HTTPS" + port = 443 + path = "/" + } +} + +resource "azurerm_public_ip" "test" { + name = "acctestpublicip-%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + allocation_method = "Static" + domain_name_label = "acctestpublicip-%[1]d" +} + +resource "azurerm_traffic_manager_azure_endpoint" "test" { + name = "acctestend-azure%[1]d" + target_resource_id = azurerm_public_ip.test.id + profile_id = azurerm_traffic_manager_profile.test.id +} +`, data.RandomInteger, data.Locations.Primary) +} + func (r AzureEndpointResource) requiresImport(data acceptance.TestData) string { template := r.basic(data) return fmt.Sprintf(` diff --git a/internal/services/trafficmanager/external_endpoint_resource.go b/internal/services/trafficmanager/external_endpoint_resource.go index 5fc9a110c7e8..ce759b9ed30e 100644 --- a/internal/services/trafficmanager/external_endpoint_resource.go +++ b/internal/services/trafficmanager/external_endpoint_resource.go @@ -67,7 +67,8 @@ func resourceExternalEndpoint() *pluginsdk.Resource { "weight": { Type: pluginsdk.TypeInt, - Required: true, + Optional: true, + Computed: true, ValidateFunc: validation.IntBetween(1, 1000), }, @@ -182,7 +183,6 @@ func resourceExternalEndpointCreateUpdate(d *pluginsdk.ResourceData, meta interf EndpointStatus: &status, Target: utils.String(d.Get("target").(string)), Subnets: expandEndpointSubnetConfig(d.Get("subnet").([]interface{})), - Weight: utils.Int64(int64(d.Get("weight").(int))), }, } @@ -190,6 +190,10 @@ func resourceExternalEndpointCreateUpdate(d *pluginsdk.ResourceData, meta interf params.Properties.Priority = utils.Int64(int64(priority)) } + if weight := d.Get("weight").(int); weight != 0 { + params.Properties.Weight = utils.Int64(int64(weight)) + } + if endpointLocation := d.Get("endpoint_location").(string); endpointLocation != "" { params.Properties.EndpointLocation = utils.String(endpointLocation) } diff --git a/internal/services/trafficmanager/external_endpoint_resource_test.go b/internal/services/trafficmanager/external_endpoint_resource_test.go index da38c745e6a6..25362604b8e9 100644 --- a/internal/services/trafficmanager/external_endpoint_resource_test.go +++ b/internal/services/trafficmanager/external_endpoint_resource_test.go @@ -31,6 +31,21 @@ func TestAccExternalEndpoint_basic(t *testing.T) { }) } +func TestAccExternalEndpoint_priority(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_traffic_manager_external_endpoint", "test") + r := ExternalEndpointResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.priority(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccExternalEndpoint_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_traffic_manager_external_endpoint", "test") r := ExternalEndpointResource{} @@ -138,6 +153,42 @@ resource "azurerm_traffic_manager_external_endpoint" "test" { `, r.template(data), data.RandomInteger) } +func (r ExternalEndpointResource) priority(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-traffic-%[1]d" + location = "%[2]s" +} + +resource "azurerm_traffic_manager_profile" "test" { + name = "acctest-TMP-%[1]d" + resource_group_name = azurerm_resource_group.test.name + traffic_routing_method = "Priority" + + dns_config { + relative_name = "acctest-tmp-%[1]d" + ttl = 30 + } + + monitor_config { + protocol = "HTTPS" + port = 443 + path = "/" + } +} + +resource "azurerm_traffic_manager_external_endpoint" "test" { + name = "acctestend-azure%[1]d" + target = "www.example.com" + profile_id = azurerm_traffic_manager_profile.test.id +} +`, data.RandomInteger, data.Locations.Primary) +} + func (r ExternalEndpointResource) requiresImport(data acceptance.TestData) string { return fmt.Sprintf(` %s diff --git a/internal/services/trafficmanager/nested_endpoint_resource.go b/internal/services/trafficmanager/nested_endpoint_resource.go index 4b3fbe1f9f59..0c88213af08e 100644 --- a/internal/services/trafficmanager/nested_endpoint_resource.go +++ b/internal/services/trafficmanager/nested_endpoint_resource.go @@ -68,7 +68,8 @@ func resourceNestedEndpoint() *pluginsdk.Resource { "weight": { Type: pluginsdk.TypeInt, - Required: true, + Optional: true, + Computed: true, ValidateFunc: validation.IntBetween(1, 1000), }, @@ -201,10 +202,13 @@ func resourceNestedEndpointCreateUpdate(d *pluginsdk.ResourceData, meta interfac MinChildEndpoints: utils.Int64(int64(d.Get("minimum_child_endpoints").(int))), TargetResourceId: utils.String(d.Get("target_resource_id").(string)), Subnets: expandEndpointSubnetConfig(d.Get("subnet").([]interface{})), - Weight: utils.Int64(int64(d.Get("weight").(int))), }, } + if weight := d.Get("weight").(int); weight != 0 { + params.Properties.Weight = utils.Int64(int64(weight)) + } + minChildEndpointsIPv4 := d.Get("minimum_required_child_endpoints_ipv4").(int) if minChildEndpointsIPv4 > 0 { params.Properties.MinChildEndpointsIPv4 = utils.Int64(int64(minChildEndpointsIPv4)) diff --git a/internal/services/trafficmanager/nested_endpoint_resource_test.go b/internal/services/trafficmanager/nested_endpoint_resource_test.go index 9a2907cbea31..65816b96631f 100644 --- a/internal/services/trafficmanager/nested_endpoint_resource_test.go +++ b/internal/services/trafficmanager/nested_endpoint_resource_test.go @@ -31,6 +31,21 @@ func TestAccNestedEndpoint_basic(t *testing.T) { }) } +func TestAccNestedEndpoint_priority(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_traffic_manager_nested_endpoint", "test") + r := NestedEndpointResource{} + + data.ResourceTest(t, r, []acceptance.TestStep{ + { + Config: r.priority(data), + Check: acceptance.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + func TestAccNestedEndpoint_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_traffic_manager_nested_endpoint", "test") r := NestedEndpointResource{} @@ -124,6 +139,60 @@ resource "azurerm_traffic_manager_nested_endpoint" "test" { `, r.template(data), data.RandomInteger) } +func (r NestedEndpointResource) priority(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-traffic-%[1]d" + location = "%[2]s" +} + +resource "azurerm_traffic_manager_profile" "parent" { + name = "acctest-TMP-%[1]d" + resource_group_name = azurerm_resource_group.test.name + traffic_routing_method = "Priority" + + dns_config { + relative_name = "acctest-tmp-%[1]d" + ttl = 30 + } + + monitor_config { + protocol = "HTTPS" + port = 443 + path = "/" + } +} + +resource "azurerm_traffic_manager_profile" "child" { + name = "acctesttmpchild%[1]d" + resource_group_name = azurerm_resource_group.test.name + traffic_routing_method = "Priority" + + dns_config { + relative_name = "acctesttmpchild%[1]d" + ttl = 30 + } + + monitor_config { + protocol = "HTTPS" + port = 443 + path = "/" + } +} + +resource "azurerm_traffic_manager_nested_endpoint" "test" { + name = "acctestend-parent%[1]d" + target_resource_id = azurerm_traffic_manager_profile.child.id + profile_id = azurerm_traffic_manager_profile.parent.id + minimum_child_endpoints = 5 +} +`, data.RandomInteger, data.Locations.Primary) +} + func (r NestedEndpointResource) requiresImport(data acceptance.TestData) string { return fmt.Sprintf(` %s diff --git a/internal/services/web/app_service.go b/internal/services/web/app_service.go index 4b36fa25de72..e27c38122828 100644 --- a/internal/services/web/app_service.go +++ b/internal/services/web/app_service.go @@ -5,9 +5,8 @@ import ( "log" "strings" - "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" - "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/utils" diff --git a/internal/services/web/app_service_environment_resource.go b/internal/services/web/app_service_environment_resource.go index 83318f0c77ee..2625dbd01460 100644 --- a/internal/services/web/app_service_environment_resource.go +++ b/internal/services/web/app_service_environment_resource.go @@ -7,10 +7,9 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" - "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" helpersValidate "github.com/hashicorp/terraform-provider-azurerm/helpers/validate" diff --git a/internal/services/web/app_service_hybrid_connection_resource.go b/internal/services/web/app_service_hybrid_connection_resource.go index be33e407b32e..5bf6f6d16b02 100644 --- a/internal/services/web/app_service_hybrid_connection_resource.go +++ b/internal/services/web/app_service_hybrid_connection_resource.go @@ -6,10 +6,9 @@ import ( "log" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" - "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" "github.com/hashicorp/go-azure-helpers/lang/response" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-sdk/resource-manager/relay/2017-04-01/hybridconnections" "github.com/hashicorp/go-azure-sdk/resource-manager/relay/2017-04-01/namespaces" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" diff --git a/internal/services/web/function_app_resource.go b/internal/services/web/function_app_resource.go index 911bb8150570..7178abc58cf4 100644 --- a/internal/services/web/function_app_resource.go +++ b/internal/services/web/function_app_resource.go @@ -7,9 +7,8 @@ import ( "strings" "time" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" - "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2021-02-01/web" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema" "github.com/hashicorp/terraform-provider-azurerm/helpers/azure" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" diff --git a/test/main.tf b/test/main.tf new file mode 100644 index 000000000000..4100073e2067 --- /dev/null +++ b/test/main.tf @@ -0,0 +1,96 @@ +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "xiaxintestRG-WAlogs" + location = "east us" +} + +resource "azurerm_service_plan" "test" { + name = "xiaxintestASP-logging" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + os_type = "Linux" + sku_name = "B1" +} + +resource "azurerm_linux_web_app" "test" { + name = "LinuxWA-logging" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + service_plan_id = azurerm_service_plan.test.id + + site_config {} + + /* logs { + application_logs { + file_system_level = "Off" + azure_blob_storage { + level = "Information" + sas_url = "http://x.com/" + retention_in_days = 2 + } + } + + http_logs { + file_system { + retention_in_days = 4 + retention_in_mb = 25 + } + } + detailed_error_messages = true + } */ +} + +resource "azurerm_linux_web_app" "test1" { + name = "LinuxWA-loggingDefault" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + service_plan_id = azurerm_service_plan.test.id + site_config {} + logs { + application_logs { + file_system_level = "Information" + azure_blob_storage { + level = "Warning" + sas_url = "http://x.com/" + retention_in_days = 2 + } + } + + http_logs { + file_system { + retention_in_days = 7 + retention_in_mb = 25 + } + } + detailed_error_messages = true + } +} + +resource "azurerm_linux_web_app" "test2" { + name = "LinuxWA-logging1" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + service_plan_id = azurerm_service_plan.test.id + site_config {} + logs { +# application_logs { +# file_system_level = "Off" +# azure_blob_storage { +# level = "Warning" +# sas_url = "http://x.com/" +# retention_in_days = 2 +# } +# } + +# http_logs { +# file_system { +# retention_in_days = 7 +# retention_in_mb = 25 +# } +# } + detailed_error_messages = true + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/CHANGELOG.md new file mode 100644 index 000000000000..52911e4cc5e4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/CHANGELOG.md @@ -0,0 +1,2 @@ +# Change History + diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/_meta.json new file mode 100644 index 000000000000..e28978dd44bc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/_meta.json @@ -0,0 +1,11 @@ +{ + "commit": "bb4175d29020cfff55f1d9087c2a5a89765067dc", + "readme": "/_/azure-rest-api-specs/specification/azure-kusto/resource-manager/readme.md", + "tag": "package-2022-02", + "use": "@microsoft.azure/autorest.go@2.1.187", + "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", + "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-2022-02 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix /_/azure-rest-api-specs/specification/azure-kusto/resource-manager/readme.md", + "additional_properties": { + "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix" + } +} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/attacheddatabaseconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/attacheddatabaseconfigurations.go new file mode 100644 index 000000000000..68745276e272 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/attacheddatabaseconfigurations.go @@ -0,0 +1,449 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// AttachedDatabaseConfigurationsClient is the the Azure Kusto management API provides a RESTful set of web services +// that interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, +// update, and delete clusters and databases. +type AttachedDatabaseConfigurationsClient struct { + BaseClient +} + +// NewAttachedDatabaseConfigurationsClient creates an instance of the AttachedDatabaseConfigurationsClient client. +func NewAttachedDatabaseConfigurationsClient(subscriptionID string) AttachedDatabaseConfigurationsClient { + return NewAttachedDatabaseConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewAttachedDatabaseConfigurationsClientWithBaseURI creates an instance of the AttachedDatabaseConfigurationsClient +// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI +// (sovereign clouds, Azure stack). +func NewAttachedDatabaseConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) AttachedDatabaseConfigurationsClient { + return AttachedDatabaseConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability checks that the attached database configuration resource name is valid and is not already in +// use. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// resourceName - the name of the resource. +func (client AttachedDatabaseConfigurationsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, resourceName AttachedDatabaseConfigurationsCheckNameRequest) (result CheckNameResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceName, + Constraints: []validation.Constraint{{Target: "resourceName.Name", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "resourceName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("kusto.AttachedDatabaseConfigurationsClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CheckNameAvailability", resp, "Failure responding to request") + return + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client AttachedDatabaseConfigurationsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, resourceName AttachedDatabaseConfigurationsCheckNameRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/attachedDatabaseConfigurationCheckNameAvailability", pathParameters), + autorest.WithJSON(resourceName), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client AttachedDatabaseConfigurationsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client AttachedDatabaseConfigurationsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate creates or updates an attached database configuration. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// attachedDatabaseConfigurationName - the name of the attached database configuration. +// parameters - the database parameters supplied to the CreateOrUpdate operation. +func (client AttachedDatabaseConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string, parameters AttachedDatabaseConfiguration) (result AttachedDatabaseConfigurationsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.AttachedDatabaseConfigurationProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.AttachedDatabaseConfigurationProperties.DatabaseName", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.AttachedDatabaseConfigurationProperties.ClusterResourceID", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + return result, validation.NewError("kusto.AttachedDatabaseConfigurationsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, attachedDatabaseConfigurationName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client AttachedDatabaseConfigurationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string, parameters AttachedDatabaseConfiguration) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "attachedDatabaseConfigurationName": autorest.Encode("path", attachedDatabaseConfigurationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/attachedDatabaseConfigurations/{attachedDatabaseConfigurationName}", 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 AttachedDatabaseConfigurationsClient) CreateOrUpdateSender(req *http.Request) (future AttachedDatabaseConfigurationsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client AttachedDatabaseConfigurationsClient) CreateOrUpdateResponder(resp *http.Response) (result AttachedDatabaseConfiguration, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the attached database configuration with the given name. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// attachedDatabaseConfigurationName - the name of the attached database configuration. +func (client AttachedDatabaseConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string) (result AttachedDatabaseConfigurationsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, attachedDatabaseConfigurationName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client AttachedDatabaseConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "attachedDatabaseConfigurationName": autorest.Encode("path", attachedDatabaseConfigurationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/attachedDatabaseConfigurations/{attachedDatabaseConfigurationName}", 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 AttachedDatabaseConfigurationsClient) DeleteSender(req *http.Request) (future AttachedDatabaseConfigurationsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client AttachedDatabaseConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get returns an attached database configuration. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// attachedDatabaseConfigurationName - the name of the attached database configuration. +func (client AttachedDatabaseConfigurationsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string) (result AttachedDatabaseConfiguration, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, attachedDatabaseConfigurationName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client AttachedDatabaseConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "attachedDatabaseConfigurationName": autorest.Encode("path", attachedDatabaseConfigurationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/attachedDatabaseConfigurations/{attachedDatabaseConfigurationName}", 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 AttachedDatabaseConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client AttachedDatabaseConfigurationsClient) GetResponder(resp *http.Response) (result AttachedDatabaseConfiguration, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByCluster returns the list of attached database configurations of the given Kusto cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client AttachedDatabaseConfigurationsClient) ListByCluster(ctx context.Context, resourceGroupName string, clusterName string) (result AttachedDatabaseConfigurationListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.ListByCluster") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListByClusterPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "ListByCluster", nil, "Failure preparing request") + return + } + + resp, err := client.ListByClusterSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "ListByCluster", resp, "Failure sending request") + return + } + + result, err = client.ListByClusterResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "ListByCluster", resp, "Failure responding to request") + return + } + + return +} + +// ListByClusterPreparer prepares the ListByCluster request. +func (client AttachedDatabaseConfigurationsClient) ListByClusterPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/attachedDatabaseConfigurations", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByClusterSender sends the ListByCluster request. The method will close the +// http.Response Body if it receives an error. +func (client AttachedDatabaseConfigurationsClient) ListByClusterSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByClusterResponder handles the response to the ListByCluster request. The method always +// closes the http.Response Body. +func (client AttachedDatabaseConfigurationsClient) ListByClusterResponder(resp *http.Response) (result AttachedDatabaseConfigurationListResult, err error) { + err = autorest.Respond( + resp, + 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/kusto/mgmt/2022-02-01/kusto/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/client.go new file mode 100644 index 000000000000..50a48b7ef37c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/client.go @@ -0,0 +1,42 @@ +// Package kusto implements the Azure ARM Kusto service API version 2022-02-01. +// +// The Azure Kusto management API provides a RESTful set of web services that interact with Azure Kusto services to +// manage your clusters and databases. The API enables you to create, update, and delete clusters and databases. +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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 Kusto + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Kusto. +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 using a custom endpoint. Use this when interacting with +// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +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/kusto/mgmt/2022-02-01/kusto/clusterprincipalassignments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/clusterprincipalassignments.go new file mode 100644 index 000000000000..e50bc79d604c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/clusterprincipalassignments.go @@ -0,0 +1,446 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ClusterPrincipalAssignmentsClient is the the Azure Kusto management API provides a RESTful set of web services that +// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and +// delete clusters and databases. +type ClusterPrincipalAssignmentsClient struct { + BaseClient +} + +// NewClusterPrincipalAssignmentsClient creates an instance of the ClusterPrincipalAssignmentsClient client. +func NewClusterPrincipalAssignmentsClient(subscriptionID string) ClusterPrincipalAssignmentsClient { + return NewClusterPrincipalAssignmentsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewClusterPrincipalAssignmentsClientWithBaseURI creates an instance of the ClusterPrincipalAssignmentsClient client +// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign +// clouds, Azure stack). +func NewClusterPrincipalAssignmentsClientWithBaseURI(baseURI string, subscriptionID string) ClusterPrincipalAssignmentsClient { + return ClusterPrincipalAssignmentsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability checks that the principal assignment name is valid and is not already in use. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// principalAssignmentName - the name of the principal assignment. +func (client ClusterPrincipalAssignmentsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName ClusterPrincipalAssignmentCheckNameRequest) (result CheckNameResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: principalAssignmentName, + Constraints: []validation.Constraint{{Target: "principalAssignmentName.Name", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "principalAssignmentName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("kusto.ClusterPrincipalAssignmentsClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, principalAssignmentName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CheckNameAvailability", resp, "Failure responding to request") + return + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client ClusterPrincipalAssignmentsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName ClusterPrincipalAssignmentCheckNameRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/checkPrincipalAssignmentNameAvailability", pathParameters), + autorest.WithJSON(principalAssignmentName), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client ClusterPrincipalAssignmentsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client ClusterPrincipalAssignmentsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate create a Kusto cluster principalAssignment. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// principalAssignmentName - the name of the Kusto principalAssignment. +// parameters - the Kusto cluster principalAssignment's parameters supplied for the operation. +func (client ClusterPrincipalAssignmentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string, parameters ClusterPrincipalAssignment) (result ClusterPrincipalAssignmentsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.ClusterPrincipalProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterPrincipalProperties.PrincipalID", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("kusto.ClusterPrincipalAssignmentsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, principalAssignmentName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ClusterPrincipalAssignmentsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string, parameters ClusterPrincipalAssignment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "principalAssignmentName": autorest.Encode("path", principalAssignmentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/principalAssignments/{principalAssignmentName}", 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 ClusterPrincipalAssignmentsClient) CreateOrUpdateSender(req *http.Request) (future ClusterPrincipalAssignmentsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ClusterPrincipalAssignmentsClient) CreateOrUpdateResponder(resp *http.Response) (result ClusterPrincipalAssignment, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a Kusto cluster principalAssignment. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// principalAssignmentName - the name of the Kusto principalAssignment. +func (client ClusterPrincipalAssignmentsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string) (result ClusterPrincipalAssignmentsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, principalAssignmentName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ClusterPrincipalAssignmentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "principalAssignmentName": autorest.Encode("path", principalAssignmentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/principalAssignments/{principalAssignmentName}", 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 ClusterPrincipalAssignmentsClient) DeleteSender(req *http.Request) (future ClusterPrincipalAssignmentsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ClusterPrincipalAssignmentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a Kusto cluster principalAssignment. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// principalAssignmentName - the name of the Kusto principalAssignment. +func (client ClusterPrincipalAssignmentsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string) (result ClusterPrincipalAssignment, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, principalAssignmentName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client ClusterPrincipalAssignmentsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "principalAssignmentName": autorest.Encode("path", principalAssignmentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/principalAssignments/{principalAssignmentName}", 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 ClusterPrincipalAssignmentsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ClusterPrincipalAssignmentsClient) GetResponder(resp *http.Response) (result ClusterPrincipalAssignment, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists all Kusto cluster principalAssignments. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClusterPrincipalAssignmentsClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result ClusterPrincipalAssignmentListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "List", resp, "Failure responding to request") + return + } + + return +} + +// ListPreparer prepares the List request. +func (client ClusterPrincipalAssignmentsClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/principalAssignments", 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 ClusterPrincipalAssignmentsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ClusterPrincipalAssignmentsClient) ListResponder(resp *http.Response) (result ClusterPrincipalAssignmentListResult, err error) { + err = autorest.Respond( + resp, + 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/kusto/mgmt/2022-02-01/kusto/clusters.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/clusters.go new file mode 100644 index 000000000000..6dcc304845cc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/clusters.go @@ -0,0 +1,1525 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ClustersClient is the the Azure Kusto management API provides a RESTful set of web services that interact with Azure +// Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and +// databases. +type ClustersClient struct { + BaseClient +} + +// NewClustersClient creates an instance of the ClustersClient client. +func NewClustersClient(subscriptionID string) ClustersClient { + return NewClustersClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewClustersClientWithBaseURI creates an instance of the ClustersClient client using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewClustersClientWithBaseURI(baseURI string, subscriptionID string) ClustersClient { + return ClustersClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// AddLanguageExtensions add a list of language extensions that can run within KQL queries. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// languageExtensionsToAdd - the language extensions to add. +func (client ClustersClient) AddLanguageExtensions(ctx context.Context, resourceGroupName string, clusterName string, languageExtensionsToAdd LanguageExtensionsList) (result ClustersAddLanguageExtensionsFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.AddLanguageExtensions") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.AddLanguageExtensionsPreparer(ctx, resourceGroupName, clusterName, languageExtensionsToAdd) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "AddLanguageExtensions", nil, "Failure preparing request") + return + } + + result, err = client.AddLanguageExtensionsSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "AddLanguageExtensions", result.Response(), "Failure sending request") + return + } + + return +} + +// AddLanguageExtensionsPreparer prepares the AddLanguageExtensions request. +func (client ClustersClient) AddLanguageExtensionsPreparer(ctx context.Context, resourceGroupName string, clusterName string, languageExtensionsToAdd LanguageExtensionsList) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/addLanguageExtensions", pathParameters), + autorest.WithJSON(languageExtensionsToAdd), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// AddLanguageExtensionsSender sends the AddLanguageExtensions request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) AddLanguageExtensionsSender(req *http.Request) (future ClustersAddLanguageExtensionsFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// AddLanguageExtensionsResponder handles the response to the AddLanguageExtensions request. The method always +// closes the http.Response Body. +func (client ClustersClient) AddLanguageExtensionsResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// CheckNameAvailability checks that the cluster name is valid and is not already in use. +// Parameters: +// location - azure location (region) name. +// clusterName - the name of the cluster. +func (client ClustersClient) CheckNameAvailability(ctx context.Context, location string, clusterName ClusterCheckNameRequest) (result CheckNameResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: clusterName, + Constraints: []validation.Constraint{{Target: "clusterName.Name", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "clusterName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("kusto.ClustersClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, location, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CheckNameAvailability", resp, "Failure responding to request") + return + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client ClustersClient) CheckNameAvailabilityPreparer(ctx context.Context, location string, clusterName ClusterCheckNameRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/locations/{location}/checkNameAvailability", pathParameters), + autorest.WithJSON(clusterName), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client ClustersClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate create or update a Kusto cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// parameters - the Kusto cluster parameters supplied to the CreateOrUpdate operation. +// ifMatch - the ETag of the cluster. Omit this value to always overwrite the current cluster. Specify the +// last-seen ETag value to prevent accidentally overwriting concurrent changes. +// ifNoneMatch - set to '*' to allow a new cluster to be created, but to prevent updating an existing cluster. +// Other values will result in a 412 Pre-condition Failed response. +func (client ClustersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, parameters Cluster, ifMatch string, ifNoneMatch string) (result ClustersCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.Sku", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.OptimizedAutoscale", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.OptimizedAutoscale.Version", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.OptimizedAutoscale.IsEnabled", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.OptimizedAutoscale.Minimum", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.OptimizedAutoscale.Maximum", Name: validation.Null, Rule: true, Chain: nil}, + }}, + {Target: "parameters.ClusterProperties.VirtualNetworkConfiguration", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.VirtualNetworkConfiguration.SubnetID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.VirtualNetworkConfiguration.EnginePublicIPID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.VirtualNetworkConfiguration.DataManagementPublicIPID", Name: validation.Null, Rule: true, Chain: nil}, + }}, + }}}}}); err != nil { + return result, validation.NewError("kusto.ClustersClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, parameters, ifMatch, ifNoneMatch) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ClustersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, parameters Cluster, ifMatch string, ifNoneMatch string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + parameters.SystemData = nil + parameters.Etag = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + if len(ifMatch) > 0 { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithHeader("If-Match", autorest.String(ifMatch))) + } + if len(ifNoneMatch) > 0 { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithHeader("If-None-Match", autorest.String(ifNoneMatch))) + } + 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 ClustersClient) CreateOrUpdateSender(req *http.Request) (future ClustersCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ClustersClient) CreateOrUpdateResponder(resp *http.Response) (result Cluster, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a Kusto cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClustersClient) Delete(ctx context.Context, resourceGroupName string, clusterName string) (result ClustersDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ClustersClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}", 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 ClustersClient) DeleteSender(req *http.Request) (future ClustersDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ClustersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// DetachFollowerDatabases detaches all followers of a database owned by this cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// followerDatabaseToRemove - the follower databases properties to remove. +func (client ClustersClient) DetachFollowerDatabases(ctx context.Context, resourceGroupName string, clusterName string, followerDatabaseToRemove FollowerDatabaseDefinition) (result ClustersDetachFollowerDatabasesFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.DetachFollowerDatabases") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: followerDatabaseToRemove, + Constraints: []validation.Constraint{{Target: "followerDatabaseToRemove.ClusterResourceID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "followerDatabaseToRemove.AttachedDatabaseConfigurationName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("kusto.ClustersClient", "DetachFollowerDatabases", err.Error()) + } + + req, err := client.DetachFollowerDatabasesPreparer(ctx, resourceGroupName, clusterName, followerDatabaseToRemove) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "DetachFollowerDatabases", nil, "Failure preparing request") + return + } + + result, err = client.DetachFollowerDatabasesSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "DetachFollowerDatabases", result.Response(), "Failure sending request") + return + } + + return +} + +// DetachFollowerDatabasesPreparer prepares the DetachFollowerDatabases request. +func (client ClustersClient) DetachFollowerDatabasesPreparer(ctx context.Context, resourceGroupName string, clusterName string, followerDatabaseToRemove FollowerDatabaseDefinition) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + followerDatabaseToRemove.DatabaseName = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/detachFollowerDatabases", pathParameters), + autorest.WithJSON(followerDatabaseToRemove), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DetachFollowerDatabasesSender sends the DetachFollowerDatabases request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) DetachFollowerDatabasesSender(req *http.Request) (future ClustersDetachFollowerDatabasesFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DetachFollowerDatabasesResponder handles the response to the DetachFollowerDatabases request. The method always +// closes the http.Response Body. +func (client ClustersClient) DetachFollowerDatabasesResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// DiagnoseVirtualNetwork diagnoses network connectivity status for external resources on which the service is +// dependent on. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClustersClient) DiagnoseVirtualNetwork(ctx context.Context, resourceGroupName string, clusterName string) (result ClustersDiagnoseVirtualNetworkFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.DiagnoseVirtualNetwork") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DiagnoseVirtualNetworkPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "DiagnoseVirtualNetwork", nil, "Failure preparing request") + return + } + + result, err = client.DiagnoseVirtualNetworkSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "DiagnoseVirtualNetwork", result.Response(), "Failure sending request") + return + } + + return +} + +// DiagnoseVirtualNetworkPreparer prepares the DiagnoseVirtualNetwork request. +func (client ClustersClient) DiagnoseVirtualNetworkPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/diagnoseVirtualNetwork", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DiagnoseVirtualNetworkSender sends the DiagnoseVirtualNetwork request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) DiagnoseVirtualNetworkSender(req *http.Request) (future ClustersDiagnoseVirtualNetworkFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DiagnoseVirtualNetworkResponder handles the response to the DiagnoseVirtualNetwork request. The method always +// closes the http.Response Body. +func (client ClustersClient) DiagnoseVirtualNetworkResponder(resp *http.Response) (result DiagnoseVirtualNetworkResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get gets a Kusto cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClustersClient) Get(ctx context.Context, resourceGroupName string, clusterName string) (result Cluster, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client ClustersClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}", 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 ClustersClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ClustersClient) GetResponder(resp *http.Response) (result Cluster, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists all Kusto clusters within a subscription. +func (client ClustersClient) List(ctx context.Context) (result ClusterListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "List", resp, "Failure responding to request") + return + } + + return +} + +// ListPreparer prepares the List request. +func (client ClustersClient) ListPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Kusto/clusters", 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 ClustersClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ClustersClient) ListResponder(resp *http.Response) (result ClusterListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup lists all Kusto clusters within a resource group. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +func (client ClustersClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ClusterListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListByResourceGroup", resp, "Failure responding to request") + return + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client ClustersClient) 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 = "2022-02-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.Kusto/clusters", 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 ClustersClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client ClustersClient) ListByResourceGroupResponder(resp *http.Response) (result ClusterListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListFollowerDatabases returns a list of databases that are owned by this cluster and were followed by another +// cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClustersClient) ListFollowerDatabases(ctx context.Context, resourceGroupName string, clusterName string) (result FollowerDatabaseListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListFollowerDatabases") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListFollowerDatabasesPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListFollowerDatabases", nil, "Failure preparing request") + return + } + + resp, err := client.ListFollowerDatabasesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListFollowerDatabases", resp, "Failure sending request") + return + } + + result, err = client.ListFollowerDatabasesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListFollowerDatabases", resp, "Failure responding to request") + return + } + + return +} + +// ListFollowerDatabasesPreparer prepares the ListFollowerDatabases request. +func (client ClustersClient) ListFollowerDatabasesPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/listFollowerDatabases", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListFollowerDatabasesSender sends the ListFollowerDatabases request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) ListFollowerDatabasesSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListFollowerDatabasesResponder handles the response to the ListFollowerDatabases request. The method always +// closes the http.Response Body. +func (client ClustersClient) ListFollowerDatabasesResponder(resp *http.Response) (result FollowerDatabaseListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListLanguageExtensions returns a list of language extensions that can run within KQL queries. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClustersClient) ListLanguageExtensions(ctx context.Context, resourceGroupName string, clusterName string) (result LanguageExtensionsList, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListLanguageExtensions") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListLanguageExtensionsPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListLanguageExtensions", nil, "Failure preparing request") + return + } + + resp, err := client.ListLanguageExtensionsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListLanguageExtensions", resp, "Failure sending request") + return + } + + result, err = client.ListLanguageExtensionsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListLanguageExtensions", resp, "Failure responding to request") + return + } + + return +} + +// ListLanguageExtensionsPreparer prepares the ListLanguageExtensions request. +func (client ClustersClient) ListLanguageExtensionsPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/listLanguageExtensions", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListLanguageExtensionsSender sends the ListLanguageExtensions request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) ListLanguageExtensionsSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListLanguageExtensionsResponder handles the response to the ListLanguageExtensions request. The method always +// closes the http.Response Body. +func (client ClustersClient) ListLanguageExtensionsResponder(resp *http.Response) (result LanguageExtensionsList, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListOutboundNetworkDependenciesEndpoints gets the network endpoints of all outbound dependencies of a Kusto cluster +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClustersClient) ListOutboundNetworkDependenciesEndpoints(ctx context.Context, resourceGroupName string, clusterName string) (result OutboundNetworkDependenciesEndpointListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListOutboundNetworkDependenciesEndpoints") + defer func() { + sc := -1 + if result.ondelr.Response.Response != nil { + sc = result.ondelr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listOutboundNetworkDependenciesEndpointsNextResults + req, err := client.ListOutboundNetworkDependenciesEndpointsPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListOutboundNetworkDependenciesEndpoints", nil, "Failure preparing request") + return + } + + resp, err := client.ListOutboundNetworkDependenciesEndpointsSender(req) + if err != nil { + result.ondelr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListOutboundNetworkDependenciesEndpoints", resp, "Failure sending request") + return + } + + result.ondelr, err = client.ListOutboundNetworkDependenciesEndpointsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListOutboundNetworkDependenciesEndpoints", resp, "Failure responding to request") + return + } + if result.ondelr.hasNextLink() && result.ondelr.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListOutboundNetworkDependenciesEndpointsPreparer prepares the ListOutboundNetworkDependenciesEndpoints request. +func (client ClustersClient) ListOutboundNetworkDependenciesEndpointsPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/outboundNetworkDependenciesEndpoints", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListOutboundNetworkDependenciesEndpointsSender sends the ListOutboundNetworkDependenciesEndpoints request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) ListOutboundNetworkDependenciesEndpointsSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListOutboundNetworkDependenciesEndpointsResponder handles the response to the ListOutboundNetworkDependenciesEndpoints request. The method always +// closes the http.Response Body. +func (client ClustersClient) ListOutboundNetworkDependenciesEndpointsResponder(resp *http.Response) (result OutboundNetworkDependenciesEndpointListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listOutboundNetworkDependenciesEndpointsNextResults retrieves the next set of results, if any. +func (client ClustersClient) listOutboundNetworkDependenciesEndpointsNextResults(ctx context.Context, lastResults OutboundNetworkDependenciesEndpointListResult) (result OutboundNetworkDependenciesEndpointListResult, err error) { + req, err := lastResults.outboundNetworkDependenciesEndpointListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "kusto.ClustersClient", "listOutboundNetworkDependenciesEndpointsNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListOutboundNetworkDependenciesEndpointsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "kusto.ClustersClient", "listOutboundNetworkDependenciesEndpointsNextResults", resp, "Failure sending next results request") + } + result, err = client.ListOutboundNetworkDependenciesEndpointsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "listOutboundNetworkDependenciesEndpointsNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListOutboundNetworkDependenciesEndpointsComplete enumerates all values, automatically crossing page boundaries as required. +func (client ClustersClient) ListOutboundNetworkDependenciesEndpointsComplete(ctx context.Context, resourceGroupName string, clusterName string) (result OutboundNetworkDependenciesEndpointListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListOutboundNetworkDependenciesEndpoints") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListOutboundNetworkDependenciesEndpoints(ctx, resourceGroupName, clusterName) + return +} + +// ListSkus lists eligible SKUs for Kusto resource provider. +func (client ClustersClient) ListSkus(ctx context.Context) (result SkuDescriptionList, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListSkus") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListSkusPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkus", nil, "Failure preparing request") + return + } + + resp, err := client.ListSkusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkus", resp, "Failure sending request") + return + } + + result, err = client.ListSkusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkus", resp, "Failure responding to request") + return + } + + return +} + +// ListSkusPreparer prepares the ListSkus request. +func (client ClustersClient) ListSkusPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Kusto/skus", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSkusSender sends the ListSkus request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) ListSkusSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListSkusResponder handles the response to the ListSkus request. The method always +// closes the http.Response Body. +func (client ClustersClient) ListSkusResponder(resp *http.Response) (result SkuDescriptionList, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListSkusByResource returns the SKUs available for the provided resource. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClustersClient) ListSkusByResource(ctx context.Context, resourceGroupName string, clusterName string) (result ListResourceSkusResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListSkusByResource") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListSkusByResourcePreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkusByResource", nil, "Failure preparing request") + return + } + + resp, err := client.ListSkusByResourceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkusByResource", resp, "Failure sending request") + return + } + + result, err = client.ListSkusByResourceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkusByResource", resp, "Failure responding to request") + return + } + + return +} + +// ListSkusByResourcePreparer prepares the ListSkusByResource request. +func (client ClustersClient) ListSkusByResourcePreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/skus", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSkusByResourceSender sends the ListSkusByResource request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) ListSkusByResourceSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListSkusByResourceResponder handles the response to the ListSkusByResource request. The method always +// closes the http.Response Body. +func (client ClustersClient) ListSkusByResourceResponder(resp *http.Response) (result ListResourceSkusResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// RemoveLanguageExtensions remove a list of language extensions that can run within KQL queries. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// languageExtensionsToRemove - the language extensions to remove. +func (client ClustersClient) RemoveLanguageExtensions(ctx context.Context, resourceGroupName string, clusterName string, languageExtensionsToRemove LanguageExtensionsList) (result ClustersRemoveLanguageExtensionsFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.RemoveLanguageExtensions") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RemoveLanguageExtensionsPreparer(ctx, resourceGroupName, clusterName, languageExtensionsToRemove) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "RemoveLanguageExtensions", nil, "Failure preparing request") + return + } + + result, err = client.RemoveLanguageExtensionsSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "RemoveLanguageExtensions", result.Response(), "Failure sending request") + return + } + + return +} + +// RemoveLanguageExtensionsPreparer prepares the RemoveLanguageExtensions request. +func (client ClustersClient) RemoveLanguageExtensionsPreparer(ctx context.Context, resourceGroupName string, clusterName string, languageExtensionsToRemove LanguageExtensionsList) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/removeLanguageExtensions", pathParameters), + autorest.WithJSON(languageExtensionsToRemove), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RemoveLanguageExtensionsSender sends the RemoveLanguageExtensions request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) RemoveLanguageExtensionsSender(req *http.Request) (future ClustersRemoveLanguageExtensionsFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// RemoveLanguageExtensionsResponder handles the response to the RemoveLanguageExtensions request. The method always +// closes the http.Response Body. +func (client ClustersClient) RemoveLanguageExtensionsResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Start starts a Kusto cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClustersClient) Start(ctx context.Context, resourceGroupName string, clusterName string) (result ClustersStartFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Start") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StartPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Start", nil, "Failure preparing request") + return + } + + result, err = client.StartSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Start", result.Response(), "Failure sending request") + return + } + + return +} + +// StartPreparer prepares the Start request. +func (client ClustersClient) StartPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/start", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StartSender sends the Start request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) StartSender(req *http.Request) (future ClustersStartFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// StartResponder handles the response to the Start request. The method always +// closes the http.Response Body. +func (client ClustersClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Stop stops a Kusto cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ClustersClient) Stop(ctx context.Context, resourceGroupName string, clusterName string) (result ClustersStopFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Stop") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StopPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Stop", nil, "Failure preparing request") + return + } + + result, err = client.StopSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Stop", result.Response(), "Failure sending request") + return + } + + return +} + +// StopPreparer prepares the Stop request. +func (client ClustersClient) StopPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/stop", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StopSender sends the Stop request. The method will close the +// http.Response Body if it receives an error. +func (client ClustersClient) StopSender(req *http.Request) (future ClustersStopFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// StopResponder handles the response to the Stop request. The method always +// closes the http.Response Body. +func (client ClustersClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update update a Kusto cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// parameters - the Kusto cluster parameters supplied to the Update operation. +// ifMatch - the ETag of the cluster. Omit this value to always overwrite the current cluster. Specify the +// last-seen ETag value to prevent accidentally overwriting concurrent changes. +func (client ClustersClient) Update(ctx context.Context, resourceGroupName string, clusterName string, parameters ClusterUpdate, ifMatch string) (result ClustersUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, parameters, ifMatch) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ClustersClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, parameters ClusterUpdate, ifMatch string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + if len(ifMatch) > 0 { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithHeader("If-Match", autorest.String(ifMatch))) + } + 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 ClustersClient) UpdateSender(req *http.Request) (future ClustersUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ClustersClient) UpdateResponder(resp *http.Response) (result Cluster, err error) { + err = autorest.Respond( + resp, + 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/kusto/mgmt/2022-02-01/kusto/databaseprincipalassignments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/databaseprincipalassignments.go new file mode 100644 index 000000000000..c0dffb18354a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/databaseprincipalassignments.go @@ -0,0 +1,456 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// DatabasePrincipalAssignmentsClient is the the Azure Kusto management API provides a RESTful set of web services that +// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and +// delete clusters and databases. +type DatabasePrincipalAssignmentsClient struct { + BaseClient +} + +// NewDatabasePrincipalAssignmentsClient creates an instance of the DatabasePrincipalAssignmentsClient client. +func NewDatabasePrincipalAssignmentsClient(subscriptionID string) DatabasePrincipalAssignmentsClient { + return NewDatabasePrincipalAssignmentsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDatabasePrincipalAssignmentsClientWithBaseURI creates an instance of the DatabasePrincipalAssignmentsClient +// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI +// (sovereign clouds, Azure stack). +func NewDatabasePrincipalAssignmentsClientWithBaseURI(baseURI string, subscriptionID string) DatabasePrincipalAssignmentsClient { + return DatabasePrincipalAssignmentsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability checks that the database principal assignment is valid and is not already in use. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// principalAssignmentName - the name of the resource. +func (client DatabasePrincipalAssignmentsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName DatabasePrincipalAssignmentCheckNameRequest) (result CheckNameResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: principalAssignmentName, + Constraints: []validation.Constraint{{Target: "principalAssignmentName.Name", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "principalAssignmentName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("kusto.DatabasePrincipalAssignmentsClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, databaseName, principalAssignmentName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CheckNameAvailability", resp, "Failure responding to request") + return + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client DatabasePrincipalAssignmentsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName DatabasePrincipalAssignmentCheckNameRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/checkPrincipalAssignmentNameAvailability", pathParameters), + autorest.WithJSON(principalAssignmentName), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasePrincipalAssignmentsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client DatabasePrincipalAssignmentsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate creates a Kusto cluster database principalAssignment. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// principalAssignmentName - the name of the Kusto principalAssignment. +// parameters - the Kusto principalAssignments parameters supplied for the operation. +func (client DatabasePrincipalAssignmentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string, parameters DatabasePrincipalAssignment) (result DatabasePrincipalAssignmentsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.DatabasePrincipalProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.DatabasePrincipalProperties.PrincipalID", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("kusto.DatabasePrincipalAssignmentsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, principalAssignmentName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DatabasePrincipalAssignmentsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string, parameters DatabasePrincipalAssignment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "principalAssignmentName": autorest.Encode("path", principalAssignmentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}", 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 DatabasePrincipalAssignmentsClient) CreateOrUpdateSender(req *http.Request) (future DatabasePrincipalAssignmentsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client DatabasePrincipalAssignmentsClient) CreateOrUpdateResponder(resp *http.Response) (result DatabasePrincipalAssignment, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a Kusto principalAssignment. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// principalAssignmentName - the name of the Kusto principalAssignment. +func (client DatabasePrincipalAssignmentsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string) (result DatabasePrincipalAssignmentsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName, principalAssignmentName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DatabasePrincipalAssignmentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "principalAssignmentName": autorest.Encode("path", principalAssignmentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}", 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 DatabasePrincipalAssignmentsClient) DeleteSender(req *http.Request) (future DatabasePrincipalAssignmentsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client DatabasePrincipalAssignmentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a Kusto cluster database principalAssignment. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// principalAssignmentName - the name of the Kusto principalAssignment. +func (client DatabasePrincipalAssignmentsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string) (result DatabasePrincipalAssignment, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName, principalAssignmentName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client DatabasePrincipalAssignmentsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "principalAssignmentName": autorest.Encode("path", principalAssignmentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}", 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 DatabasePrincipalAssignmentsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DatabasePrincipalAssignmentsClient) GetResponder(resp *http.Response) (result DatabasePrincipalAssignment, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists all Kusto cluster database principalAssignments. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +func (client DatabasePrincipalAssignmentsClient) List(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DatabasePrincipalAssignmentListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPreparer(ctx, resourceGroupName, clusterName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "List", resp, "Failure responding to request") + return + } + + return +} + +// ListPreparer prepares the List request. +func (client DatabasePrincipalAssignmentsClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments", 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 DatabasePrincipalAssignmentsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client DatabasePrincipalAssignmentsClient) ListResponder(resp *http.Response) (result DatabasePrincipalAssignmentListResult, err error) { + err = autorest.Respond( + resp, + 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/kusto/mgmt/2022-02-01/kusto/databases.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/databases.go new file mode 100644 index 000000000000..c4aea5947106 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/databases.go @@ -0,0 +1,761 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// DatabasesClient is the the Azure Kusto management API provides a RESTful set of web services that interact with +// Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete +// clusters and databases. +type DatabasesClient struct { + BaseClient +} + +// NewDatabasesClient creates an instance of the DatabasesClient client. +func NewDatabasesClient(subscriptionID string) DatabasesClient { + return NewDatabasesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDatabasesClientWithBaseURI creates an instance of the DatabasesClient client using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewDatabasesClientWithBaseURI(baseURI string, subscriptionID string) DatabasesClient { + return DatabasesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// AddPrincipals add Database principals permissions. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// databasePrincipalsToAdd - list of database principals to add. +func (client DatabasesClient) AddPrincipals(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, databasePrincipalsToAdd DatabasePrincipalListRequest) (result DatabasePrincipalListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.AddPrincipals") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.AddPrincipalsPreparer(ctx, resourceGroupName, clusterName, databaseName, databasePrincipalsToAdd) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "AddPrincipals", nil, "Failure preparing request") + return + } + + resp, err := client.AddPrincipalsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "AddPrincipals", resp, "Failure sending request") + return + } + + result, err = client.AddPrincipalsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "AddPrincipals", resp, "Failure responding to request") + return + } + + return +} + +// AddPrincipalsPreparer prepares the AddPrincipals request. +func (client DatabasesClient) AddPrincipalsPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, databasePrincipalsToAdd DatabasePrincipalListRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/addPrincipals", pathParameters), + autorest.WithJSON(databasePrincipalsToAdd), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// AddPrincipalsSender sends the AddPrincipals request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) AddPrincipalsSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// AddPrincipalsResponder handles the response to the AddPrincipals request. The method always +// closes the http.Response Body. +func (client DatabasesClient) AddPrincipalsResponder(resp *http.Response) (result DatabasePrincipalListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CheckNameAvailability checks that the databases resource name is valid and is not already in use. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// resourceName - the name of the resource. +func (client DatabasesClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, resourceName CheckNameRequest) (result CheckNameResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceName, + Constraints: []validation.Constraint{{Target: "resourceName.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("kusto.DatabasesClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CheckNameAvailability", resp, "Failure responding to request") + return + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client DatabasesClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, resourceName CheckNameRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/checkNameAvailability", pathParameters), + autorest.WithJSON(resourceName), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client DatabasesClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate creates or updates a database. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// parameters - the database parameters supplied to the CreateOrUpdate operation. +func (client DatabasesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters BasicDatabase) (result DatabasesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DatabasesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters BasicDatabase) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}", 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 DatabasesClient) CreateOrUpdateSender(req *http.Request) (future DatabasesCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client DatabasesClient) CreateOrUpdateResponder(resp *http.Response) (result DatabaseModel, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the database with the given name. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +func (client DatabasesClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DatabasesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DatabasesClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}", 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 DatabasesClient) DeleteSender(req *http.Request) (future DatabasesDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client DatabasesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get returns a database. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +func (client DatabasesClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DatabaseModel, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client DatabasesClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}", 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 DatabasesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DatabasesClient) GetResponder(resp *http.Response) (result DatabaseModel, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByCluster returns the list of databases of the given Kusto cluster. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client DatabasesClient) ListByCluster(ctx context.Context, resourceGroupName string, clusterName string) (result DatabaseListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.ListByCluster") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListByClusterPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListByCluster", nil, "Failure preparing request") + return + } + + resp, err := client.ListByClusterSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListByCluster", resp, "Failure sending request") + return + } + + result, err = client.ListByClusterResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListByCluster", resp, "Failure responding to request") + return + } + + return +} + +// ListByClusterPreparer prepares the ListByCluster request. +func (client DatabasesClient) ListByClusterPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByClusterSender sends the ListByCluster request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ListByClusterSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByClusterResponder handles the response to the ListByCluster request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ListByClusterResponder(resp *http.Response) (result DatabaseListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListPrincipals returns a list of database principals of the given Kusto cluster and database. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +func (client DatabasesClient) ListPrincipals(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DatabasePrincipalListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.ListPrincipals") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPrincipalsPreparer(ctx, resourceGroupName, clusterName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListPrincipals", nil, "Failure preparing request") + return + } + + resp, err := client.ListPrincipalsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListPrincipals", resp, "Failure sending request") + return + } + + result, err = client.ListPrincipalsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListPrincipals", resp, "Failure responding to request") + return + } + + return +} + +// ListPrincipalsPreparer prepares the ListPrincipals request. +func (client DatabasesClient) ListPrincipalsPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/listPrincipals", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListPrincipalsSender sends the ListPrincipals request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) ListPrincipalsSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListPrincipalsResponder handles the response to the ListPrincipals request. The method always +// closes the http.Response Body. +func (client DatabasesClient) ListPrincipalsResponder(resp *http.Response) (result DatabasePrincipalListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// RemovePrincipals remove Database principals permissions. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// databasePrincipalsToRemove - list of database principals to remove. +func (client DatabasesClient) RemovePrincipals(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, databasePrincipalsToRemove DatabasePrincipalListRequest) (result DatabasePrincipalListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.RemovePrincipals") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RemovePrincipalsPreparer(ctx, resourceGroupName, clusterName, databaseName, databasePrincipalsToRemove) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "RemovePrincipals", nil, "Failure preparing request") + return + } + + resp, err := client.RemovePrincipalsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "RemovePrincipals", resp, "Failure sending request") + return + } + + result, err = client.RemovePrincipalsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "RemovePrincipals", resp, "Failure responding to request") + return + } + + return +} + +// RemovePrincipalsPreparer prepares the RemovePrincipals request. +func (client DatabasesClient) RemovePrincipalsPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, databasePrincipalsToRemove DatabasePrincipalListRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/removePrincipals", pathParameters), + autorest.WithJSON(databasePrincipalsToRemove), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RemovePrincipalsSender sends the RemovePrincipals request. The method will close the +// http.Response Body if it receives an error. +func (client DatabasesClient) RemovePrincipalsSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// RemovePrincipalsResponder handles the response to the RemovePrincipals request. The method always +// closes the http.Response Body. +func (client DatabasesClient) RemovePrincipalsResponder(resp *http.Response) (result DatabasePrincipalListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update updates a database. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// parameters - the database parameters supplied to the Update operation. +func (client DatabasesClient) Update(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters BasicDatabase) (result DatabasesUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client DatabasesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters BasicDatabase) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}", 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 DatabasesClient) UpdateSender(req *http.Request) (future DatabasesUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client DatabasesClient) UpdateResponder(resp *http.Response) (result DatabaseModel, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/dataconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/dataconnections.go new file mode 100644 index 000000000000..eb2f1a06795b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/dataconnections.go @@ -0,0 +1,618 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// DataConnectionsClient is the the Azure Kusto management API provides a RESTful set of web services that interact +// with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete +// clusters and databases. +type DataConnectionsClient struct { + BaseClient +} + +// NewDataConnectionsClient creates an instance of the DataConnectionsClient client. +func NewDataConnectionsClient(subscriptionID string) DataConnectionsClient { + return NewDataConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDataConnectionsClientWithBaseURI creates an instance of the DataConnectionsClient client using a custom endpoint. +// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewDataConnectionsClientWithBaseURI(baseURI string, subscriptionID string) DataConnectionsClient { + return DataConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability checks that the data connection name is valid and is not already in use. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// dataConnectionName - the name of the data connection. +func (client DataConnectionsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName DataConnectionCheckNameRequest) (result CheckNameResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: dataConnectionName, + Constraints: []validation.Constraint{{Target: "dataConnectionName.Name", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "dataConnectionName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("kusto.DataConnectionsClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", resp, "Failure responding to request") + return + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client DataConnectionsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName DataConnectionCheckNameRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/checkNameAvailability", pathParameters), + autorest.WithJSON(dataConnectionName), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client DataConnectionsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client DataConnectionsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate creates or updates a data connection. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// dataConnectionName - the name of the data connection. +// parameters - the data connection parameters supplied to the CreateOrUpdate operation. +func (client DataConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (result DataConnectionsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DataConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "dataConnectionName": autorest.Encode("path", dataConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", 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 DataConnectionsClient) CreateOrUpdateSender(req *http.Request) (future DataConnectionsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client DataConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result DataConnectionModel, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// DataConnectionValidationMethod checks that the data connection parameters are valid. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// parameters - the data connection parameters supplied to the CreateOrUpdate operation. +func (client DataConnectionsClient) DataConnectionValidationMethod(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters DataConnectionValidation) (result DataConnectionsDataConnectionValidationMethodFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.DataConnectionValidationMethod") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DataConnectionValidationMethodPreparer(ctx, resourceGroupName, clusterName, databaseName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", nil, "Failure preparing request") + return + } + + result, err = client.DataConnectionValidationMethodSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", result.Response(), "Failure sending request") + return + } + + return +} + +// DataConnectionValidationMethodPreparer prepares the DataConnectionValidationMethod request. +func (client DataConnectionsClient) DataConnectionValidationMethodPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters DataConnectionValidation) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnectionValidation", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DataConnectionValidationMethodSender sends the DataConnectionValidationMethod request. The method will close the +// http.Response Body if it receives an error. +func (client DataConnectionsClient) DataConnectionValidationMethodSender(req *http.Request) (future DataConnectionsDataConnectionValidationMethodFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DataConnectionValidationMethodResponder handles the response to the DataConnectionValidationMethod request. The method always +// closes the http.Response Body. +func (client DataConnectionsClient) DataConnectionValidationMethodResponder(resp *http.Response) (result DataConnectionValidationListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the data connection with the given name. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// dataConnectionName - the name of the data connection. +func (client DataConnectionsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (result DataConnectionsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DataConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "dataConnectionName": autorest.Encode("path", dataConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", 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 DataConnectionsClient) DeleteSender(req *http.Request) (future DataConnectionsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client DataConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get returns a data connection. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// dataConnectionName - the name of the data connection. +func (client DataConnectionsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (result DataConnectionModel, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client DataConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "dataConnectionName": autorest.Encode("path", dataConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", 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 DataConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DataConnectionsClient) GetResponder(resp *http.Response) (result DataConnectionModel, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByDatabase returns the list of data connections of the given Kusto database. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +func (client DataConnectionsClient) ListByDatabase(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DataConnectionListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.ListByDatabase") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, clusterName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", nil, "Failure preparing request") + return + } + + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", resp, "Failure sending request") + return + } + + result, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", resp, "Failure responding to request") + return + } + + return +} + +// ListByDatabasePreparer prepares the ListByDatabase request. +func (client DataConnectionsClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByDatabaseSender sends the ListByDatabase request. The method will close the +// http.Response Body if it receives an error. +func (client DataConnectionsClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByDatabaseResponder handles the response to the ListByDatabase request. The method always +// closes the http.Response Body. +func (client DataConnectionsClient) ListByDatabaseResponder(resp *http.Response) (result DataConnectionListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update updates a data connection. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// dataConnectionName - the name of the data connection. +// parameters - the data connection parameters supplied to the Update operation. +func (client DataConnectionsClient) Update(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (result DataConnectionsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client DataConnectionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "dataConnectionName": autorest.Encode("path", dataConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", 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 DataConnectionsClient) UpdateSender(req *http.Request) (future DataConnectionsUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client DataConnectionsClient) UpdateResponder(resp *http.Response) (result DataConnectionModel, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/enums.go new file mode 100644 index 000000000000..f746200224e3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/enums.go @@ -0,0 +1,668 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// AzureScaleType enumerates the values for azure scale type. +type AzureScaleType string + +const ( + // AzureScaleTypeAutomatic ... + AzureScaleTypeAutomatic AzureScaleType = "automatic" + // AzureScaleTypeManual ... + AzureScaleTypeManual AzureScaleType = "manual" + // AzureScaleTypeNone ... + AzureScaleTypeNone AzureScaleType = "none" +) + +// PossibleAzureScaleTypeValues returns an array of possible values for the AzureScaleType const type. +func PossibleAzureScaleTypeValues() []AzureScaleType { + return []AzureScaleType{AzureScaleTypeAutomatic, AzureScaleTypeManual, AzureScaleTypeNone} +} + +// AzureSkuName enumerates the values for azure sku name. +type AzureSkuName string + +const ( + // AzureSkuNameDevNoSLAStandardD11V2 ... + AzureSkuNameDevNoSLAStandardD11V2 AzureSkuName = "Dev(No SLA)_Standard_D11_v2" + // AzureSkuNameDevNoSLAStandardE2aV4 ... + AzureSkuNameDevNoSLAStandardE2aV4 AzureSkuName = "Dev(No SLA)_Standard_E2a_v4" + // AzureSkuNameStandardD11V2 ... + AzureSkuNameStandardD11V2 AzureSkuName = "Standard_D11_v2" + // AzureSkuNameStandardD12V2 ... + AzureSkuNameStandardD12V2 AzureSkuName = "Standard_D12_v2" + // AzureSkuNameStandardD13V2 ... + AzureSkuNameStandardD13V2 AzureSkuName = "Standard_D13_v2" + // AzureSkuNameStandardD14V2 ... + AzureSkuNameStandardD14V2 AzureSkuName = "Standard_D14_v2" + // AzureSkuNameStandardD16dV5 ... + AzureSkuNameStandardD16dV5 AzureSkuName = "Standard_D16d_v5" + // AzureSkuNameStandardD32dV4 ... + AzureSkuNameStandardD32dV4 AzureSkuName = "Standard_D32d_v4" + // AzureSkuNameStandardD32dV5 ... + AzureSkuNameStandardD32dV5 AzureSkuName = "Standard_D32d_v5" + // AzureSkuNameStandardDS13V21TBPS ... + AzureSkuNameStandardDS13V21TBPS AzureSkuName = "Standard_DS13_v2+1TB_PS" + // AzureSkuNameStandardDS13V22TBPS ... + AzureSkuNameStandardDS13V22TBPS AzureSkuName = "Standard_DS13_v2+2TB_PS" + // AzureSkuNameStandardDS14V23TBPS ... + AzureSkuNameStandardDS14V23TBPS AzureSkuName = "Standard_DS14_v2+3TB_PS" + // AzureSkuNameStandardDS14V24TBPS ... + AzureSkuNameStandardDS14V24TBPS AzureSkuName = "Standard_DS14_v2+4TB_PS" + // AzureSkuNameStandardE16adsV5 ... + AzureSkuNameStandardE16adsV5 AzureSkuName = "Standard_E16ads_v5" + // AzureSkuNameStandardE16asV43TBPS ... + AzureSkuNameStandardE16asV43TBPS AzureSkuName = "Standard_E16as_v4+3TB_PS" + // AzureSkuNameStandardE16asV44TBPS ... + AzureSkuNameStandardE16asV44TBPS AzureSkuName = "Standard_E16as_v4+4TB_PS" + // AzureSkuNameStandardE16asV53TBPS ... + AzureSkuNameStandardE16asV53TBPS AzureSkuName = "Standard_E16as_v5+3TB_PS" + // AzureSkuNameStandardE16asV54TBPS ... + AzureSkuNameStandardE16asV54TBPS AzureSkuName = "Standard_E16as_v5+4TB_PS" + // AzureSkuNameStandardE16aV4 ... + AzureSkuNameStandardE16aV4 AzureSkuName = "Standard_E16a_v4" + // AzureSkuNameStandardE16sV43TBPS ... + AzureSkuNameStandardE16sV43TBPS AzureSkuName = "Standard_E16s_v4+3TB_PS" + // AzureSkuNameStandardE16sV44TBPS ... + AzureSkuNameStandardE16sV44TBPS AzureSkuName = "Standard_E16s_v4+4TB_PS" + // AzureSkuNameStandardE16sV53TBPS ... + AzureSkuNameStandardE16sV53TBPS AzureSkuName = "Standard_E16s_v5+3TB_PS" + // AzureSkuNameStandardE16sV54TBPS ... + AzureSkuNameStandardE16sV54TBPS AzureSkuName = "Standard_E16s_v5+4TB_PS" + // AzureSkuNameStandardE2adsV5 ... + AzureSkuNameStandardE2adsV5 AzureSkuName = "Standard_E2ads_v5" + // AzureSkuNameStandardE2aV4 ... + AzureSkuNameStandardE2aV4 AzureSkuName = "Standard_E2a_v4" + // AzureSkuNameStandardE4adsV5 ... + AzureSkuNameStandardE4adsV5 AzureSkuName = "Standard_E4ads_v5" + // AzureSkuNameStandardE4aV4 ... + AzureSkuNameStandardE4aV4 AzureSkuName = "Standard_E4a_v4" + // AzureSkuNameStandardE64iV3 ... + AzureSkuNameStandardE64iV3 AzureSkuName = "Standard_E64i_v3" + // AzureSkuNameStandardE80idsV4 ... + AzureSkuNameStandardE80idsV4 AzureSkuName = "Standard_E80ids_v4" + // AzureSkuNameStandardE8adsV5 ... + AzureSkuNameStandardE8adsV5 AzureSkuName = "Standard_E8ads_v5" + // AzureSkuNameStandardE8asV41TBPS ... + AzureSkuNameStandardE8asV41TBPS AzureSkuName = "Standard_E8as_v4+1TB_PS" + // AzureSkuNameStandardE8asV42TBPS ... + AzureSkuNameStandardE8asV42TBPS AzureSkuName = "Standard_E8as_v4+2TB_PS" + // AzureSkuNameStandardE8asV51TBPS ... + AzureSkuNameStandardE8asV51TBPS AzureSkuName = "Standard_E8as_v5+1TB_PS" + // AzureSkuNameStandardE8asV52TBPS ... + AzureSkuNameStandardE8asV52TBPS AzureSkuName = "Standard_E8as_v5+2TB_PS" + // AzureSkuNameStandardE8aV4 ... + AzureSkuNameStandardE8aV4 AzureSkuName = "Standard_E8a_v4" + // AzureSkuNameStandardE8sV41TBPS ... + AzureSkuNameStandardE8sV41TBPS AzureSkuName = "Standard_E8s_v4+1TB_PS" + // AzureSkuNameStandardE8sV42TBPS ... + AzureSkuNameStandardE8sV42TBPS AzureSkuName = "Standard_E8s_v4+2TB_PS" + // AzureSkuNameStandardE8sV51TBPS ... + AzureSkuNameStandardE8sV51TBPS AzureSkuName = "Standard_E8s_v5+1TB_PS" + // AzureSkuNameStandardE8sV52TBPS ... + AzureSkuNameStandardE8sV52TBPS AzureSkuName = "Standard_E8s_v5+2TB_PS" + // AzureSkuNameStandardL16s ... + AzureSkuNameStandardL16s AzureSkuName = "Standard_L16s" + // AzureSkuNameStandardL16sV2 ... + AzureSkuNameStandardL16sV2 AzureSkuName = "Standard_L16s_v2" + // AzureSkuNameStandardL4s ... + AzureSkuNameStandardL4s AzureSkuName = "Standard_L4s" + // AzureSkuNameStandardL8s ... + AzureSkuNameStandardL8s AzureSkuName = "Standard_L8s" + // AzureSkuNameStandardL8sV2 ... + AzureSkuNameStandardL8sV2 AzureSkuName = "Standard_L8s_v2" +) + +// PossibleAzureSkuNameValues returns an array of possible values for the AzureSkuName const type. +func PossibleAzureSkuNameValues() []AzureSkuName { + return []AzureSkuName{AzureSkuNameDevNoSLAStandardD11V2, AzureSkuNameDevNoSLAStandardE2aV4, AzureSkuNameStandardD11V2, AzureSkuNameStandardD12V2, AzureSkuNameStandardD13V2, AzureSkuNameStandardD14V2, AzureSkuNameStandardD16dV5, AzureSkuNameStandardD32dV4, AzureSkuNameStandardD32dV5, AzureSkuNameStandardDS13V21TBPS, AzureSkuNameStandardDS13V22TBPS, AzureSkuNameStandardDS14V23TBPS, AzureSkuNameStandardDS14V24TBPS, AzureSkuNameStandardE16adsV5, AzureSkuNameStandardE16asV43TBPS, AzureSkuNameStandardE16asV44TBPS, AzureSkuNameStandardE16asV53TBPS, AzureSkuNameStandardE16asV54TBPS, AzureSkuNameStandardE16aV4, AzureSkuNameStandardE16sV43TBPS, AzureSkuNameStandardE16sV44TBPS, AzureSkuNameStandardE16sV53TBPS, AzureSkuNameStandardE16sV54TBPS, AzureSkuNameStandardE2adsV5, AzureSkuNameStandardE2aV4, AzureSkuNameStandardE4adsV5, AzureSkuNameStandardE4aV4, AzureSkuNameStandardE64iV3, AzureSkuNameStandardE80idsV4, AzureSkuNameStandardE8adsV5, AzureSkuNameStandardE8asV41TBPS, AzureSkuNameStandardE8asV42TBPS, AzureSkuNameStandardE8asV51TBPS, AzureSkuNameStandardE8asV52TBPS, AzureSkuNameStandardE8aV4, AzureSkuNameStandardE8sV41TBPS, AzureSkuNameStandardE8sV42TBPS, AzureSkuNameStandardE8sV51TBPS, AzureSkuNameStandardE8sV52TBPS, AzureSkuNameStandardL16s, AzureSkuNameStandardL16sV2, AzureSkuNameStandardL4s, AzureSkuNameStandardL8s, AzureSkuNameStandardL8sV2} +} + +// AzureSkuTier enumerates the values for azure sku tier. +type AzureSkuTier string + +const ( + // AzureSkuTierBasic ... + AzureSkuTierBasic AzureSkuTier = "Basic" + // AzureSkuTierStandard ... + AzureSkuTierStandard AzureSkuTier = "Standard" +) + +// PossibleAzureSkuTierValues returns an array of possible values for the AzureSkuTier const type. +func PossibleAzureSkuTierValues() []AzureSkuTier { + return []AzureSkuTier{AzureSkuTierBasic, AzureSkuTierStandard} +} + +// BlobStorageEventType enumerates the values for blob storage event type. +type BlobStorageEventType string + +const ( + // BlobStorageEventTypeMicrosoftStorageBlobCreated ... + BlobStorageEventTypeMicrosoftStorageBlobCreated BlobStorageEventType = "Microsoft.Storage.BlobCreated" + // BlobStorageEventTypeMicrosoftStorageBlobRenamed ... + BlobStorageEventTypeMicrosoftStorageBlobRenamed BlobStorageEventType = "Microsoft.Storage.BlobRenamed" +) + +// PossibleBlobStorageEventTypeValues returns an array of possible values for the BlobStorageEventType const type. +func PossibleBlobStorageEventTypeValues() []BlobStorageEventType { + return []BlobStorageEventType{BlobStorageEventTypeMicrosoftStorageBlobCreated, BlobStorageEventTypeMicrosoftStorageBlobRenamed} +} + +// ClusterNetworkAccessFlag enumerates the values for cluster network access flag. +type ClusterNetworkAccessFlag string + +const ( + // ClusterNetworkAccessFlagDisabled ... + ClusterNetworkAccessFlagDisabled ClusterNetworkAccessFlag = "Disabled" + // ClusterNetworkAccessFlagEnabled ... + ClusterNetworkAccessFlagEnabled ClusterNetworkAccessFlag = "Enabled" +) + +// PossibleClusterNetworkAccessFlagValues returns an array of possible values for the ClusterNetworkAccessFlag const type. +func PossibleClusterNetworkAccessFlagValues() []ClusterNetworkAccessFlag { + return []ClusterNetworkAccessFlag{ClusterNetworkAccessFlagDisabled, ClusterNetworkAccessFlagEnabled} +} + +// ClusterPrincipalRole enumerates the values for cluster principal role. +type ClusterPrincipalRole string + +const ( + // ClusterPrincipalRoleAllDatabasesAdmin ... + ClusterPrincipalRoleAllDatabasesAdmin ClusterPrincipalRole = "AllDatabasesAdmin" + // ClusterPrincipalRoleAllDatabasesViewer ... + ClusterPrincipalRoleAllDatabasesViewer ClusterPrincipalRole = "AllDatabasesViewer" +) + +// PossibleClusterPrincipalRoleValues returns an array of possible values for the ClusterPrincipalRole const type. +func PossibleClusterPrincipalRoleValues() []ClusterPrincipalRole { + return []ClusterPrincipalRole{ClusterPrincipalRoleAllDatabasesAdmin, ClusterPrincipalRoleAllDatabasesViewer} +} + +// Compression enumerates the values for compression. +type Compression string + +const ( + // CompressionGZip ... + CompressionGZip Compression = "GZip" + // CompressionNone ... + CompressionNone Compression = "None" +) + +// PossibleCompressionValues returns an array of possible values for the Compression const type. +func PossibleCompressionValues() []Compression { + return []Compression{CompressionGZip, CompressionNone} +} + +// CreatedByType enumerates the values for created by type. +type CreatedByType string + +const ( + // CreatedByTypeApplication ... + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey ... + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity ... + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser ... + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns an array of possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{CreatedByTypeApplication, CreatedByTypeKey, CreatedByTypeManagedIdentity, CreatedByTypeUser} +} + +// DatabasePrincipalRole enumerates the values for database principal role. +type DatabasePrincipalRole string + +const ( + // DatabasePrincipalRoleAdmin ... + DatabasePrincipalRoleAdmin DatabasePrincipalRole = "Admin" + // DatabasePrincipalRoleIngestor ... + DatabasePrincipalRoleIngestor DatabasePrincipalRole = "Ingestor" + // DatabasePrincipalRoleMonitor ... + DatabasePrincipalRoleMonitor DatabasePrincipalRole = "Monitor" + // DatabasePrincipalRoleUnrestrictedViewer ... + DatabasePrincipalRoleUnrestrictedViewer DatabasePrincipalRole = "UnrestrictedViewer" + // DatabasePrincipalRoleUser ... + DatabasePrincipalRoleUser DatabasePrincipalRole = "User" + // DatabasePrincipalRoleViewer ... + DatabasePrincipalRoleViewer DatabasePrincipalRole = "Viewer" +) + +// PossibleDatabasePrincipalRoleValues returns an array of possible values for the DatabasePrincipalRole const type. +func PossibleDatabasePrincipalRoleValues() []DatabasePrincipalRole { + return []DatabasePrincipalRole{DatabasePrincipalRoleAdmin, DatabasePrincipalRoleIngestor, DatabasePrincipalRoleMonitor, DatabasePrincipalRoleUnrestrictedViewer, DatabasePrincipalRoleUser, DatabasePrincipalRoleViewer} +} + +// DatabasePrincipalType enumerates the values for database principal type. +type DatabasePrincipalType string + +const ( + // DatabasePrincipalTypeApp ... + DatabasePrincipalTypeApp DatabasePrincipalType = "App" + // DatabasePrincipalTypeGroup ... + DatabasePrincipalTypeGroup DatabasePrincipalType = "Group" + // DatabasePrincipalTypeUser ... + DatabasePrincipalTypeUser DatabasePrincipalType = "User" +) + +// PossibleDatabasePrincipalTypeValues returns an array of possible values for the DatabasePrincipalType const type. +func PossibleDatabasePrincipalTypeValues() []DatabasePrincipalType { + return []DatabasePrincipalType{DatabasePrincipalTypeApp, DatabasePrincipalTypeGroup, DatabasePrincipalTypeUser} +} + +// DatabaseRouting enumerates the values for database routing. +type DatabaseRouting string + +const ( + // DatabaseRoutingMulti ... + DatabaseRoutingMulti DatabaseRouting = "Multi" + // DatabaseRoutingSingle ... + DatabaseRoutingSingle DatabaseRouting = "Single" +) + +// PossibleDatabaseRoutingValues returns an array of possible values for the DatabaseRouting const type. +func PossibleDatabaseRoutingValues() []DatabaseRouting { + return []DatabaseRouting{DatabaseRoutingMulti, DatabaseRoutingSingle} +} + +// DefaultPrincipalsModificationKind enumerates the values for default principals modification kind. +type DefaultPrincipalsModificationKind string + +const ( + // DefaultPrincipalsModificationKindNone ... + DefaultPrincipalsModificationKindNone DefaultPrincipalsModificationKind = "None" + // DefaultPrincipalsModificationKindReplace ... + DefaultPrincipalsModificationKindReplace DefaultPrincipalsModificationKind = "Replace" + // DefaultPrincipalsModificationKindUnion ... + DefaultPrincipalsModificationKindUnion DefaultPrincipalsModificationKind = "Union" +) + +// PossibleDefaultPrincipalsModificationKindValues returns an array of possible values for the DefaultPrincipalsModificationKind const type. +func PossibleDefaultPrincipalsModificationKindValues() []DefaultPrincipalsModificationKind { + return []DefaultPrincipalsModificationKind{DefaultPrincipalsModificationKindNone, DefaultPrincipalsModificationKindReplace, DefaultPrincipalsModificationKindUnion} +} + +// EngineType enumerates the values for engine type. +type EngineType string + +const ( + // EngineTypeV2 ... + EngineTypeV2 EngineType = "V2" + // EngineTypeV3 ... + EngineTypeV3 EngineType = "V3" +) + +// PossibleEngineTypeValues returns an array of possible values for the EngineType const type. +func PossibleEngineTypeValues() []EngineType { + return []EngineType{EngineTypeV2, EngineTypeV3} +} + +// EventGridDataFormat enumerates the values for event grid data format. +type EventGridDataFormat string + +const ( + // EventGridDataFormatAPACHEAVRO ... + EventGridDataFormatAPACHEAVRO EventGridDataFormat = "APACHEAVRO" + // EventGridDataFormatAVRO ... + EventGridDataFormatAVRO EventGridDataFormat = "AVRO" + // EventGridDataFormatCSV ... + EventGridDataFormatCSV EventGridDataFormat = "CSV" + // EventGridDataFormatJSON ... + EventGridDataFormatJSON EventGridDataFormat = "JSON" + // EventGridDataFormatMULTIJSON ... + EventGridDataFormatMULTIJSON EventGridDataFormat = "MULTIJSON" + // EventGridDataFormatORC ... + EventGridDataFormatORC EventGridDataFormat = "ORC" + // EventGridDataFormatPARQUET ... + EventGridDataFormatPARQUET EventGridDataFormat = "PARQUET" + // EventGridDataFormatPSV ... + EventGridDataFormatPSV EventGridDataFormat = "PSV" + // EventGridDataFormatRAW ... + EventGridDataFormatRAW EventGridDataFormat = "RAW" + // EventGridDataFormatSCSV ... + EventGridDataFormatSCSV EventGridDataFormat = "SCSV" + // EventGridDataFormatSINGLEJSON ... + EventGridDataFormatSINGLEJSON EventGridDataFormat = "SINGLEJSON" + // EventGridDataFormatSOHSV ... + EventGridDataFormatSOHSV EventGridDataFormat = "SOHSV" + // EventGridDataFormatTSV ... + EventGridDataFormatTSV EventGridDataFormat = "TSV" + // EventGridDataFormatTSVE ... + EventGridDataFormatTSVE EventGridDataFormat = "TSVE" + // EventGridDataFormatTXT ... + EventGridDataFormatTXT EventGridDataFormat = "TXT" + // EventGridDataFormatW3CLOGFILE ... + EventGridDataFormatW3CLOGFILE EventGridDataFormat = "W3CLOGFILE" +) + +// PossibleEventGridDataFormatValues returns an array of possible values for the EventGridDataFormat const type. +func PossibleEventGridDataFormatValues() []EventGridDataFormat { + return []EventGridDataFormat{EventGridDataFormatAPACHEAVRO, EventGridDataFormatAVRO, EventGridDataFormatCSV, EventGridDataFormatJSON, EventGridDataFormatMULTIJSON, EventGridDataFormatORC, EventGridDataFormatPARQUET, EventGridDataFormatPSV, EventGridDataFormatRAW, EventGridDataFormatSCSV, EventGridDataFormatSINGLEJSON, EventGridDataFormatSOHSV, EventGridDataFormatTSV, EventGridDataFormatTSVE, EventGridDataFormatTXT, EventGridDataFormatW3CLOGFILE} +} + +// EventHubDataFormat enumerates the values for event hub data format. +type EventHubDataFormat string + +const ( + // EventHubDataFormatAPACHEAVRO ... + EventHubDataFormatAPACHEAVRO EventHubDataFormat = "APACHEAVRO" + // EventHubDataFormatAVRO ... + EventHubDataFormatAVRO EventHubDataFormat = "AVRO" + // EventHubDataFormatCSV ... + EventHubDataFormatCSV EventHubDataFormat = "CSV" + // EventHubDataFormatJSON ... + EventHubDataFormatJSON EventHubDataFormat = "JSON" + // EventHubDataFormatMULTIJSON ... + EventHubDataFormatMULTIJSON EventHubDataFormat = "MULTIJSON" + // EventHubDataFormatORC ... + EventHubDataFormatORC EventHubDataFormat = "ORC" + // EventHubDataFormatPARQUET ... + EventHubDataFormatPARQUET EventHubDataFormat = "PARQUET" + // EventHubDataFormatPSV ... + EventHubDataFormatPSV EventHubDataFormat = "PSV" + // EventHubDataFormatRAW ... + EventHubDataFormatRAW EventHubDataFormat = "RAW" + // EventHubDataFormatSCSV ... + EventHubDataFormatSCSV EventHubDataFormat = "SCSV" + // EventHubDataFormatSINGLEJSON ... + EventHubDataFormatSINGLEJSON EventHubDataFormat = "SINGLEJSON" + // EventHubDataFormatSOHSV ... + EventHubDataFormatSOHSV EventHubDataFormat = "SOHSV" + // EventHubDataFormatTSV ... + EventHubDataFormatTSV EventHubDataFormat = "TSV" + // EventHubDataFormatTSVE ... + EventHubDataFormatTSVE EventHubDataFormat = "TSVE" + // EventHubDataFormatTXT ... + EventHubDataFormatTXT EventHubDataFormat = "TXT" + // EventHubDataFormatW3CLOGFILE ... + EventHubDataFormatW3CLOGFILE EventHubDataFormat = "W3CLOGFILE" +) + +// PossibleEventHubDataFormatValues returns an array of possible values for the EventHubDataFormat const type. +func PossibleEventHubDataFormatValues() []EventHubDataFormat { + return []EventHubDataFormat{EventHubDataFormatAPACHEAVRO, EventHubDataFormatAVRO, EventHubDataFormatCSV, EventHubDataFormatJSON, EventHubDataFormatMULTIJSON, EventHubDataFormatORC, EventHubDataFormatPARQUET, EventHubDataFormatPSV, EventHubDataFormatRAW, EventHubDataFormatSCSV, EventHubDataFormatSINGLEJSON, EventHubDataFormatSOHSV, EventHubDataFormatTSV, EventHubDataFormatTSVE, EventHubDataFormatTXT, EventHubDataFormatW3CLOGFILE} +} + +// IdentityType enumerates the values for identity type. +type IdentityType string + +const ( + // IdentityTypeNone ... + IdentityTypeNone IdentityType = "None" + // IdentityTypeSystemAssigned ... + IdentityTypeSystemAssigned IdentityType = "SystemAssigned" + // IdentityTypeSystemAssignedUserAssigned ... + IdentityTypeSystemAssignedUserAssigned IdentityType = "SystemAssigned, UserAssigned" + // IdentityTypeUserAssigned ... + IdentityTypeUserAssigned IdentityType = "UserAssigned" +) + +// PossibleIdentityTypeValues returns an array of possible values for the IdentityType const type. +func PossibleIdentityTypeValues() []IdentityType { + return []IdentityType{IdentityTypeNone, IdentityTypeSystemAssigned, IdentityTypeSystemAssignedUserAssigned, IdentityTypeUserAssigned} +} + +// IotHubDataFormat enumerates the values for iot hub data format. +type IotHubDataFormat string + +const ( + // IotHubDataFormatAPACHEAVRO ... + IotHubDataFormatAPACHEAVRO IotHubDataFormat = "APACHEAVRO" + // IotHubDataFormatAVRO ... + IotHubDataFormatAVRO IotHubDataFormat = "AVRO" + // IotHubDataFormatCSV ... + IotHubDataFormatCSV IotHubDataFormat = "CSV" + // IotHubDataFormatJSON ... + IotHubDataFormatJSON IotHubDataFormat = "JSON" + // IotHubDataFormatMULTIJSON ... + IotHubDataFormatMULTIJSON IotHubDataFormat = "MULTIJSON" + // IotHubDataFormatORC ... + IotHubDataFormatORC IotHubDataFormat = "ORC" + // IotHubDataFormatPARQUET ... + IotHubDataFormatPARQUET IotHubDataFormat = "PARQUET" + // IotHubDataFormatPSV ... + IotHubDataFormatPSV IotHubDataFormat = "PSV" + // IotHubDataFormatRAW ... + IotHubDataFormatRAW IotHubDataFormat = "RAW" + // IotHubDataFormatSCSV ... + IotHubDataFormatSCSV IotHubDataFormat = "SCSV" + // IotHubDataFormatSINGLEJSON ... + IotHubDataFormatSINGLEJSON IotHubDataFormat = "SINGLEJSON" + // IotHubDataFormatSOHSV ... + IotHubDataFormatSOHSV IotHubDataFormat = "SOHSV" + // IotHubDataFormatTSV ... + IotHubDataFormatTSV IotHubDataFormat = "TSV" + // IotHubDataFormatTSVE ... + IotHubDataFormatTSVE IotHubDataFormat = "TSVE" + // IotHubDataFormatTXT ... + IotHubDataFormatTXT IotHubDataFormat = "TXT" + // IotHubDataFormatW3CLOGFILE ... + IotHubDataFormatW3CLOGFILE IotHubDataFormat = "W3CLOGFILE" +) + +// PossibleIotHubDataFormatValues returns an array of possible values for the IotHubDataFormat const type. +func PossibleIotHubDataFormatValues() []IotHubDataFormat { + return []IotHubDataFormat{IotHubDataFormatAPACHEAVRO, IotHubDataFormatAVRO, IotHubDataFormatCSV, IotHubDataFormatJSON, IotHubDataFormatMULTIJSON, IotHubDataFormatORC, IotHubDataFormatPARQUET, IotHubDataFormatPSV, IotHubDataFormatRAW, IotHubDataFormatSCSV, IotHubDataFormatSINGLEJSON, IotHubDataFormatSOHSV, IotHubDataFormatTSV, IotHubDataFormatTSVE, IotHubDataFormatTXT, IotHubDataFormatW3CLOGFILE} +} + +// Kind enumerates the values for kind. +type Kind string + +const ( + // KindDatabase ... + KindDatabase Kind = "Database" + // KindReadOnlyFollowing ... + KindReadOnlyFollowing Kind = "ReadOnlyFollowing" + // KindReadWrite ... + KindReadWrite Kind = "ReadWrite" +) + +// PossibleKindValues returns an array of possible values for the Kind const type. +func PossibleKindValues() []Kind { + return []Kind{KindDatabase, KindReadOnlyFollowing, KindReadWrite} +} + +// KindBasicDataConnection enumerates the values for kind basic data connection. +type KindBasicDataConnection string + +const ( + // KindBasicDataConnectionKindDataConnection ... + KindBasicDataConnectionKindDataConnection KindBasicDataConnection = "DataConnection" + // KindBasicDataConnectionKindEventGrid ... + KindBasicDataConnectionKindEventGrid KindBasicDataConnection = "EventGrid" + // KindBasicDataConnectionKindEventHub ... + KindBasicDataConnectionKindEventHub KindBasicDataConnection = "EventHub" + // KindBasicDataConnectionKindIotHub ... + KindBasicDataConnectionKindIotHub KindBasicDataConnection = "IotHub" +) + +// PossibleKindBasicDataConnectionValues returns an array of possible values for the KindBasicDataConnection const type. +func PossibleKindBasicDataConnectionValues() []KindBasicDataConnection { + return []KindBasicDataConnection{KindBasicDataConnectionKindDataConnection, KindBasicDataConnectionKindEventGrid, KindBasicDataConnectionKindEventHub, KindBasicDataConnectionKindIotHub} +} + +// LanguageExtensionName enumerates the values for language extension name. +type LanguageExtensionName string + +const ( + // LanguageExtensionNamePYTHON ... + LanguageExtensionNamePYTHON LanguageExtensionName = "PYTHON" + // LanguageExtensionNameR ... + LanguageExtensionNameR LanguageExtensionName = "R" +) + +// PossibleLanguageExtensionNameValues returns an array of possible values for the LanguageExtensionName const type. +func PossibleLanguageExtensionNameValues() []LanguageExtensionName { + return []LanguageExtensionName{LanguageExtensionNamePYTHON, LanguageExtensionNameR} +} + +// PrincipalsModificationKind enumerates the values for principals modification kind. +type PrincipalsModificationKind string + +const ( + // PrincipalsModificationKindNone ... + PrincipalsModificationKindNone PrincipalsModificationKind = "None" + // PrincipalsModificationKindReplace ... + PrincipalsModificationKindReplace PrincipalsModificationKind = "Replace" + // PrincipalsModificationKindUnion ... + PrincipalsModificationKindUnion PrincipalsModificationKind = "Union" +) + +// PossiblePrincipalsModificationKindValues returns an array of possible values for the PrincipalsModificationKind const type. +func PossiblePrincipalsModificationKindValues() []PrincipalsModificationKind { + return []PrincipalsModificationKind{PrincipalsModificationKindNone, PrincipalsModificationKindReplace, PrincipalsModificationKindUnion} +} + +// PrincipalType enumerates the values for principal type. +type PrincipalType string + +const ( + // PrincipalTypeApp ... + PrincipalTypeApp PrincipalType = "App" + // PrincipalTypeGroup ... + PrincipalTypeGroup PrincipalType = "Group" + // PrincipalTypeUser ... + PrincipalTypeUser PrincipalType = "User" +) + +// PossiblePrincipalTypeValues returns an array of possible values for the PrincipalType const type. +func PossiblePrincipalTypeValues() []PrincipalType { + return []PrincipalType{PrincipalTypeApp, PrincipalTypeGroup, PrincipalTypeUser} +} + +// ProvisioningState enumerates the values for provisioning state. +type ProvisioningState string + +const ( + // ProvisioningStateCreating ... + ProvisioningStateCreating ProvisioningState = "Creating" + // ProvisioningStateDeleting ... + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed ... + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateMoving ... + ProvisioningStateMoving ProvisioningState = "Moving" + // ProvisioningStateRunning ... + ProvisioningStateRunning ProvisioningState = "Running" + // ProvisioningStateSucceeded ... + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateMoving, ProvisioningStateRunning, ProvisioningStateSucceeded} +} + +// PublicIPType enumerates the values for public ip type. +type PublicIPType string + +const ( + // PublicIPTypeDualStack ... + PublicIPTypeDualStack PublicIPType = "DualStack" + // PublicIPTypeIPv4 ... + PublicIPTypeIPv4 PublicIPType = "IPv4" +) + +// PossiblePublicIPTypeValues returns an array of possible values for the PublicIPType const type. +func PossiblePublicIPTypeValues() []PublicIPType { + return []PublicIPType{PublicIPTypeDualStack, PublicIPTypeIPv4} +} + +// PublicNetworkAccess enumerates the values for public network access. +type PublicNetworkAccess string + +const ( + // PublicNetworkAccessDisabled ... + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + // PublicNetworkAccessEnabled ... + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns an array of possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{PublicNetworkAccessDisabled, PublicNetworkAccessEnabled} +} + +// Reason enumerates the values for reason. +type Reason string + +const ( + // ReasonAlreadyExists ... + ReasonAlreadyExists Reason = "AlreadyExists" + // ReasonInvalid ... + ReasonInvalid Reason = "Invalid" +) + +// PossibleReasonValues returns an array of possible values for the Reason const type. +func PossibleReasonValues() []Reason { + return []Reason{ReasonAlreadyExists, ReasonInvalid} +} + +// State enumerates the values for state. +type State string + +const ( + // StateCreating ... + StateCreating State = "Creating" + // StateDeleted ... + StateDeleted State = "Deleted" + // StateDeleting ... + StateDeleting State = "Deleting" + // StateRunning ... + StateRunning State = "Running" + // StateStarting ... + StateStarting State = "Starting" + // StateStopped ... + StateStopped State = "Stopped" + // StateStopping ... + StateStopping State = "Stopping" + // StateUnavailable ... + StateUnavailable State = "Unavailable" + // StateUpdating ... + StateUpdating State = "Updating" +) + +// PossibleStateValues returns an array of possible values for the State const type. +func PossibleStateValues() []State { + return []State{StateCreating, StateDeleted, StateDeleting, StateRunning, StateStarting, StateStopped, StateStopping, StateUnavailable, StateUpdating} +} + +// Status enumerates the values for status. +type Status string + +const ( + // StatusCanceled ... + StatusCanceled Status = "Canceled" + // StatusFailed ... + StatusFailed Status = "Failed" + // StatusRunning ... + StatusRunning Status = "Running" + // StatusSucceeded ... + StatusSucceeded Status = "Succeeded" +) + +// PossibleStatusValues returns an array of possible values for the Status const type. +func PossibleStatusValues() []Status { + return []Status{StatusCanceled, StatusFailed, StatusRunning, StatusSucceeded} +} + +// Type enumerates the values for type. +type Type string + +const ( + // TypeMicrosoftKustoclustersattachedDatabaseConfigurations ... + TypeMicrosoftKustoclustersattachedDatabaseConfigurations Type = "Microsoft.Kusto/clusters/attachedDatabaseConfigurations" + // TypeMicrosoftKustoclustersdatabases ... + TypeMicrosoftKustoclustersdatabases Type = "Microsoft.Kusto/clusters/databases" +) + +// PossibleTypeValues returns an array of possible values for the Type const type. +func PossibleTypeValues() []Type { + return []Type{TypeMicrosoftKustoclustersattachedDatabaseConfigurations, TypeMicrosoftKustoclustersdatabases} +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/managedprivateendpoints.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/managedprivateendpoints.go new file mode 100644 index 000000000000..e86c8b183786 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/managedprivateendpoints.go @@ -0,0 +1,534 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ManagedPrivateEndpointsClient is the the Azure Kusto management API provides a RESTful set of web services that +// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and +// delete clusters and databases. +type ManagedPrivateEndpointsClient struct { + BaseClient +} + +// NewManagedPrivateEndpointsClient creates an instance of the ManagedPrivateEndpointsClient client. +func NewManagedPrivateEndpointsClient(subscriptionID string) ManagedPrivateEndpointsClient { + return NewManagedPrivateEndpointsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewManagedPrivateEndpointsClientWithBaseURI creates an instance of the ManagedPrivateEndpointsClient client using a +// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, +// Azure stack). +func NewManagedPrivateEndpointsClientWithBaseURI(baseURI string, subscriptionID string) ManagedPrivateEndpointsClient { + return ManagedPrivateEndpointsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability checks that the managed private endpoints resource name is valid and is not already in use. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// resourceName - the name of the resource. +func (client ManagedPrivateEndpointsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, resourceName ManagedPrivateEndpointsCheckNameRequest) (result CheckNameResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceName, + Constraints: []validation.Constraint{{Target: "resourceName.Name", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "resourceName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("kusto.ManagedPrivateEndpointsClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CheckNameAvailability", resp, "Failure responding to request") + return + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client ManagedPrivateEndpointsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, resourceName ManagedPrivateEndpointsCheckNameRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/managedPrivateEndpointsCheckNameAvailability", pathParameters), + autorest.WithJSON(resourceName), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedPrivateEndpointsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client ManagedPrivateEndpointsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate creates a managed private endpoint. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// managedPrivateEndpointName - the name of the managed private endpoint. +// parameters - the managed private endpoint parameters. +func (client ManagedPrivateEndpointsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string, parameters ManagedPrivateEndpoint) (result ManagedPrivateEndpointsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.ManagedPrivateEndpointProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ManagedPrivateEndpointProperties.PrivateLinkResourceID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ManagedPrivateEndpointProperties.GroupID", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + return result, validation.NewError("kusto.ManagedPrivateEndpointsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, managedPrivateEndpointName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ManagedPrivateEndpointsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string, parameters ManagedPrivateEndpoint) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "managedPrivateEndpointName": autorest.Encode("path", managedPrivateEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + parameters.SystemData = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/managedPrivateEndpoints/{managedPrivateEndpointName}", 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 ManagedPrivateEndpointsClient) CreateOrUpdateSender(req *http.Request) (future ManagedPrivateEndpointsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ManagedPrivateEndpointsClient) CreateOrUpdateResponder(resp *http.Response) (result ManagedPrivateEndpoint, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a managed private endpoint. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// managedPrivateEndpointName - the name of the managed private endpoint. +func (client ManagedPrivateEndpointsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string) (result ManagedPrivateEndpointsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, managedPrivateEndpointName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ManagedPrivateEndpointsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "managedPrivateEndpointName": autorest.Encode("path", managedPrivateEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/managedPrivateEndpoints/{managedPrivateEndpointName}", 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 ManagedPrivateEndpointsClient) DeleteSender(req *http.Request) (future ManagedPrivateEndpointsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ManagedPrivateEndpointsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a managed private endpoint. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// managedPrivateEndpointName - the name of the managed private endpoint. +func (client ManagedPrivateEndpointsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string) (result ManagedPrivateEndpoint, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, managedPrivateEndpointName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client ManagedPrivateEndpointsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "managedPrivateEndpointName": autorest.Encode("path", managedPrivateEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/managedPrivateEndpoints/{managedPrivateEndpointName}", 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 ManagedPrivateEndpointsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ManagedPrivateEndpointsClient) GetResponder(resp *http.Response) (result ManagedPrivateEndpoint, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List returns the list of managed private endpoints. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client ManagedPrivateEndpointsClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result ManagedPrivateEndpointListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "List", resp, "Failure responding to request") + return + } + + return +} + +// ListPreparer prepares the List request. +func (client ManagedPrivateEndpointsClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/managedPrivateEndpoints", 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 ManagedPrivateEndpointsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ManagedPrivateEndpointsClient) ListResponder(resp *http.Response) (result ManagedPrivateEndpointListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update updates a managed private endpoint. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// managedPrivateEndpointName - the name of the managed private endpoint. +// parameters - the managed private endpoint parameters. +func (client ManagedPrivateEndpointsClient) Update(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string, parameters ManagedPrivateEndpoint) (result ManagedPrivateEndpointsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, managedPrivateEndpointName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ManagedPrivateEndpointsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string, parameters ManagedPrivateEndpoint) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "managedPrivateEndpointName": autorest.Encode("path", managedPrivateEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + parameters.SystemData = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/managedPrivateEndpoints/{managedPrivateEndpointName}", 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 ManagedPrivateEndpointsClient) UpdateSender(req *http.Request) (future ManagedPrivateEndpointsUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ManagedPrivateEndpointsClient) UpdateResponder(resp *http.Response) (result ManagedPrivateEndpoint, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, 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/kusto/mgmt/2022-02-01/kusto/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/models.go new file mode 100644 index 000000000000..10de556bd41c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/models.go @@ -0,0 +1,4819 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// The package's fully qualified name. +const fqdn = "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto" + +// AcceptedAudiences represents an accepted audience trusted by the cluster. +type AcceptedAudiences struct { + // Value - GUID or valid URL representing an accepted audience. + Value *string `json:"value,omitempty"` +} + +// AttachedDatabaseConfiguration class representing an attached database configuration. +type AttachedDatabaseConfiguration struct { + autorest.Response `json:"-"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // AttachedDatabaseConfigurationProperties - The properties of the attached database configuration. + *AttachedDatabaseConfigurationProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for AttachedDatabaseConfiguration. +func (adc AttachedDatabaseConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if adc.Location != nil { + objectMap["location"] = adc.Location + } + if adc.AttachedDatabaseConfigurationProperties != nil { + objectMap["properties"] = adc.AttachedDatabaseConfigurationProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for AttachedDatabaseConfiguration struct. +func (adc *AttachedDatabaseConfiguration) 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 "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + adc.Location = &location + } + case "properties": + if v != nil { + var attachedDatabaseConfigurationProperties AttachedDatabaseConfigurationProperties + err = json.Unmarshal(*v, &attachedDatabaseConfigurationProperties) + if err != nil { + return err + } + adc.AttachedDatabaseConfigurationProperties = &attachedDatabaseConfigurationProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + adc.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + adc.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + adc.Type = &typeVar + } + } + } + + return nil +} + +// AttachedDatabaseConfigurationListResult the list attached database configurations operation response. +type AttachedDatabaseConfigurationListResult struct { + autorest.Response `json:"-"` + // Value - The list of attached database configurations. + Value *[]AttachedDatabaseConfiguration `json:"value,omitempty"` +} + +// AttachedDatabaseConfigurationProperties class representing the an attached database configuration +// properties of kind specific. +type AttachedDatabaseConfigurationProperties struct { + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // DatabaseName - The name of the database which you would like to attach, use * if you want to follow all current and future databases. + DatabaseName *string `json:"databaseName,omitempty"` + // ClusterResourceID - The resource id of the cluster where the databases you would like to attach reside. + ClusterResourceID *string `json:"clusterResourceId,omitempty"` + // AttachedDatabaseNames - READ-ONLY; The list of databases from the clusterResourceId which are currently attached to the cluster. + AttachedDatabaseNames *[]string `json:"attachedDatabaseNames,omitempty"` + // DefaultPrincipalsModificationKind - The default principals modification kind. Possible values include: 'DefaultPrincipalsModificationKindUnion', 'DefaultPrincipalsModificationKindReplace', 'DefaultPrincipalsModificationKindNone' + DefaultPrincipalsModificationKind DefaultPrincipalsModificationKind `json:"defaultPrincipalsModificationKind,omitempty"` + // TableLevelSharingProperties - Table level sharing specifications + TableLevelSharingProperties *TableLevelSharingProperties `json:"tableLevelSharingProperties,omitempty"` +} + +// MarshalJSON is the custom marshaler for AttachedDatabaseConfigurationProperties. +func (adcp AttachedDatabaseConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if adcp.DatabaseName != nil { + objectMap["databaseName"] = adcp.DatabaseName + } + if adcp.ClusterResourceID != nil { + objectMap["clusterResourceId"] = adcp.ClusterResourceID + } + if adcp.DefaultPrincipalsModificationKind != "" { + objectMap["defaultPrincipalsModificationKind"] = adcp.DefaultPrincipalsModificationKind + } + if adcp.TableLevelSharingProperties != nil { + objectMap["tableLevelSharingProperties"] = adcp.TableLevelSharingProperties + } + return json.Marshal(objectMap) +} + +// AttachedDatabaseConfigurationsCheckNameRequest the result returned from a AttachedDatabaseConfigurations +// check name availability request. +type AttachedDatabaseConfigurationsCheckNameRequest struct { + // Name - Attached database resource name. + Name *string `json:"name,omitempty"` + // Type - The type of resource, for instance Microsoft.Kusto/clusters/attachedDatabaseConfigurations. + Type *string `json:"type,omitempty"` +} + +// AttachedDatabaseConfigurationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the +// results of a long-running operation. +type AttachedDatabaseConfigurationsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(AttachedDatabaseConfigurationsClient) (AttachedDatabaseConfiguration, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *AttachedDatabaseConfigurationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for AttachedDatabaseConfigurationsCreateOrUpdateFuture.Result. +func (future *AttachedDatabaseConfigurationsCreateOrUpdateFuture) result(client AttachedDatabaseConfigurationsClient) (adc AttachedDatabaseConfiguration, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + adc.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.AttachedDatabaseConfigurationsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if adc.Response.Response, err = future.GetResult(sender); err == nil && adc.Response.Response.StatusCode != http.StatusNoContent { + adc, err = client.CreateOrUpdateResponder(adc.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsCreateOrUpdateFuture", "Result", adc.Response.Response, "Failure responding to request") + } + } + return +} + +// AttachedDatabaseConfigurationsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type AttachedDatabaseConfigurationsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(AttachedDatabaseConfigurationsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *AttachedDatabaseConfigurationsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for AttachedDatabaseConfigurationsDeleteFuture.Result. +func (future *AttachedDatabaseConfigurationsDeleteFuture) result(client AttachedDatabaseConfigurationsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.AttachedDatabaseConfigurationsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// AzureCapacity azure capacity definition. +type AzureCapacity struct { + // ScaleType - Scale type. Possible values include: 'AzureScaleTypeAutomatic', 'AzureScaleTypeManual', 'AzureScaleTypeNone' + ScaleType AzureScaleType `json:"scaleType,omitempty"` + // Minimum - Minimum allowed capacity. + Minimum *int32 `json:"minimum,omitempty"` + // Maximum - Maximum allowed capacity. + Maximum *int32 `json:"maximum,omitempty"` + // Default - The default capacity that would be used. + Default *int32 `json:"default,omitempty"` +} + +// AzureEntityResource the resource model definition for an Azure Resource Manager resource with an etag. +type AzureEntityResource struct { + // Etag - READ-ONLY; Resource Etag. + Etag *string `json:"etag,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for AzureEntityResource. +func (aer AzureEntityResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// AzureResourceSku azure resource SKU definition. +type AzureResourceSku struct { + // ResourceType - Resource Namespace and Type. + ResourceType *string `json:"resourceType,omitempty"` + // Sku - The SKU details. + Sku *AzureSku `json:"sku,omitempty"` + // Capacity - The number of instances of the cluster. + Capacity *AzureCapacity `json:"capacity,omitempty"` +} + +// AzureSku azure SKU definition. +type AzureSku struct { + // Name - SKU name. Possible values include: 'AzureSkuNameDevNoSLAStandardD11V2', 'AzureSkuNameDevNoSLAStandardE2aV4', 'AzureSkuNameStandardD11V2', 'AzureSkuNameStandardD12V2', 'AzureSkuNameStandardD13V2', 'AzureSkuNameStandardD14V2', 'AzureSkuNameStandardD32dV4', 'AzureSkuNameStandardD16dV5', 'AzureSkuNameStandardD32dV5', 'AzureSkuNameStandardDS13V21TBPS', 'AzureSkuNameStandardDS13V22TBPS', 'AzureSkuNameStandardDS14V23TBPS', 'AzureSkuNameStandardDS14V24TBPS', 'AzureSkuNameStandardL4s', 'AzureSkuNameStandardL8s', 'AzureSkuNameStandardL16s', 'AzureSkuNameStandardL8sV2', 'AzureSkuNameStandardL16sV2', 'AzureSkuNameStandardE64iV3', 'AzureSkuNameStandardE80idsV4', 'AzureSkuNameStandardE2aV4', 'AzureSkuNameStandardE4aV4', 'AzureSkuNameStandardE8aV4', 'AzureSkuNameStandardE16aV4', 'AzureSkuNameStandardE8asV41TBPS', 'AzureSkuNameStandardE8asV42TBPS', 'AzureSkuNameStandardE16asV43TBPS', 'AzureSkuNameStandardE16asV44TBPS', 'AzureSkuNameStandardE8asV51TBPS', 'AzureSkuNameStandardE8asV52TBPS', 'AzureSkuNameStandardE16asV53TBPS', 'AzureSkuNameStandardE16asV54TBPS', 'AzureSkuNameStandardE2adsV5', 'AzureSkuNameStandardE4adsV5', 'AzureSkuNameStandardE8adsV5', 'AzureSkuNameStandardE16adsV5', 'AzureSkuNameStandardE8sV41TBPS', 'AzureSkuNameStandardE8sV42TBPS', 'AzureSkuNameStandardE16sV43TBPS', 'AzureSkuNameStandardE16sV44TBPS', 'AzureSkuNameStandardE8sV51TBPS', 'AzureSkuNameStandardE8sV52TBPS', 'AzureSkuNameStandardE16sV53TBPS', 'AzureSkuNameStandardE16sV54TBPS' + Name AzureSkuName `json:"name,omitempty"` + // Capacity - The number of instances of the cluster. + Capacity *int32 `json:"capacity,omitempty"` + // Tier - SKU tier. Possible values include: 'AzureSkuTierBasic', 'AzureSkuTierStandard' + Tier AzureSkuTier `json:"tier,omitempty"` +} + +// CheckNameRequest the result returned from a database check name availability request. +type CheckNameRequest struct { + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - The type of resource, for instance Microsoft.Kusto/clusters/databases. Possible values include: 'TypeMicrosoftKustoclustersdatabases', 'TypeMicrosoftKustoclustersattachedDatabaseConfigurations' + Type Type `json:"type,omitempty"` +} + +// CheckNameResult the result returned from a check name availability request. +type CheckNameResult struct { + autorest.Response `json:"-"` + // NameAvailable - Specifies a Boolean value that indicates if the name is available. + NameAvailable *bool `json:"nameAvailable,omitempty"` + // Name - The name that was checked. + Name *string `json:"name,omitempty"` + // Message - Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. + Message *string `json:"message,omitempty"` + // Reason - Message providing the reason why the given name is invalid. Possible values include: 'ReasonInvalid', 'ReasonAlreadyExists' + Reason Reason `json:"reason,omitempty"` +} + +// CloudError an error response from Kusto. +type CloudError struct { + // Error - An error response from Kusto. + Error *CloudErrorBody `json:"error,omitempty"` +} + +// CloudErrorBody an error response from Kusto. +type CloudErrorBody struct { + // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + // Message - A message describing the error, intended to be suitable for displaying in a user interface. + Message *string `json:"message,omitempty"` + // Target - The target of the particular error. For example, the name of the property in error. + Target *string `json:"target,omitempty"` + // Details - A list of additional details about the error. + Details *[]CloudErrorBody `json:"details,omitempty"` +} + +// Cluster class representing a Kusto cluster. +type Cluster struct { + autorest.Response `json:"-"` + // Sku - The SKU of the cluster. + Sku *AzureSku `json:"sku,omitempty"` + // SystemData - READ-ONLY + SystemData *SystemData `json:"systemData,omitempty"` + // Zones - The availability zones of the cluster. + Zones *[]string `json:"zones,omitempty"` + // Identity - The identity of the cluster, if configured. + Identity *Identity `json:"identity,omitempty"` + // ClusterProperties - The cluster properties. + *ClusterProperties `json:"properties,omitempty"` + // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string `json:"etag,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // Location - The geo-location where the resource lives + Location *string `json:"location,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Cluster. +func (c Cluster) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if c.Sku != nil { + objectMap["sku"] = c.Sku + } + if c.Zones != nil { + objectMap["zones"] = c.Zones + } + if c.Identity != nil { + objectMap["identity"] = c.Identity + } + if c.ClusterProperties != nil { + objectMap["properties"] = c.ClusterProperties + } + if c.Tags != nil { + objectMap["tags"] = c.Tags + } + if c.Location != nil { + objectMap["location"] = c.Location + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Cluster struct. +func (c *Cluster) 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 AzureSku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + c.Sku = &sku + } + case "systemData": + if v != nil { + var systemData SystemData + err = json.Unmarshal(*v, &systemData) + if err != nil { + return err + } + c.SystemData = &systemData + } + case "zones": + if v != nil { + var zones []string + err = json.Unmarshal(*v, &zones) + if err != nil { + return err + } + c.Zones = &zones + } + case "identity": + if v != nil { + var identity Identity + err = json.Unmarshal(*v, &identity) + if err != nil { + return err + } + c.Identity = &identity + } + case "properties": + if v != nil { + var clusterProperties ClusterProperties + err = json.Unmarshal(*v, &clusterProperties) + if err != nil { + return err + } + c.ClusterProperties = &clusterProperties + } + case "etag": + if v != nil { + var etag string + err = json.Unmarshal(*v, &etag) + if err != nil { + return err + } + c.Etag = &etag + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + c.Tags = tags + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + c.Location = &location + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + c.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + c.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + c.Type = &typeVar + } + } + } + + return nil +} + +// ClusterCheckNameRequest the result returned from a cluster check name availability request. +type ClusterCheckNameRequest struct { + // Name - Cluster name. + Name *string `json:"name,omitempty"` + // Type - The type of resource, Microsoft.Kusto/clusters. + Type *string `json:"type,omitempty"` +} + +// ClusterListResult the list Kusto clusters operation response. +type ClusterListResult struct { + autorest.Response `json:"-"` + // Value - The list of Kusto clusters. + Value *[]Cluster `json:"value,omitempty"` +} + +// ClusterPrincipalAssignment class representing a cluster principal assignment. +type ClusterPrincipalAssignment struct { + autorest.Response `json:"-"` + // ClusterPrincipalProperties - The cluster principal. + *ClusterPrincipalProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ClusterPrincipalAssignment. +func (cpa ClusterPrincipalAssignment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cpa.ClusterPrincipalProperties != nil { + objectMap["properties"] = cpa.ClusterPrincipalProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ClusterPrincipalAssignment struct. +func (cpa *ClusterPrincipalAssignment) 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 clusterPrincipalProperties ClusterPrincipalProperties + err = json.Unmarshal(*v, &clusterPrincipalProperties) + if err != nil { + return err + } + cpa.ClusterPrincipalProperties = &clusterPrincipalProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + cpa.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + cpa.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + cpa.Type = &typeVar + } + } + } + + return nil +} + +// ClusterPrincipalAssignmentCheckNameRequest a principal assignment check name availability request. +type ClusterPrincipalAssignmentCheckNameRequest struct { + // Name - Principal Assignment resource name. + Name *string `json:"name,omitempty"` + // Type - The type of resource, Microsoft.Kusto/clusters/principalAssignments. + Type *string `json:"type,omitempty"` +} + +// ClusterPrincipalAssignmentListResult the list Kusto cluster principal assignments operation response. +type ClusterPrincipalAssignmentListResult struct { + autorest.Response `json:"-"` + // Value - The list of Kusto cluster principal assignments. + Value *[]ClusterPrincipalAssignment `json:"value,omitempty"` +} + +// ClusterPrincipalAssignmentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results +// of a long-running operation. +type ClusterPrincipalAssignmentsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClusterPrincipalAssignmentsClient) (ClusterPrincipalAssignment, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClusterPrincipalAssignmentsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClusterPrincipalAssignmentsCreateOrUpdateFuture.Result. +func (future *ClusterPrincipalAssignmentsCreateOrUpdateFuture) result(client ClusterPrincipalAssignmentsClient) (cpa ClusterPrincipalAssignment, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + cpa.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClusterPrincipalAssignmentsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if cpa.Response.Response, err = future.GetResult(sender); err == nil && cpa.Response.Response.StatusCode != http.StatusNoContent { + cpa, err = client.CreateOrUpdateResponder(cpa.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsCreateOrUpdateFuture", "Result", cpa.Response.Response, "Failure responding to request") + } + } + return +} + +// ClusterPrincipalAssignmentsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ClusterPrincipalAssignmentsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClusterPrincipalAssignmentsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClusterPrincipalAssignmentsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClusterPrincipalAssignmentsDeleteFuture.Result. +func (future *ClusterPrincipalAssignmentsDeleteFuture) result(client ClusterPrincipalAssignmentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClusterPrincipalAssignmentsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ClusterPrincipalProperties a class representing cluster principal property. +type ClusterPrincipalProperties struct { + // PrincipalID - The principal ID assigned to the cluster principal. It can be a user email, application ID, or security group name. + PrincipalID *string `json:"principalId,omitempty"` + // Role - Cluster principal role. Possible values include: 'ClusterPrincipalRoleAllDatabasesAdmin', 'ClusterPrincipalRoleAllDatabasesViewer' + Role ClusterPrincipalRole `json:"role,omitempty"` + // TenantID - The tenant id of the principal + TenantID *string `json:"tenantId,omitempty"` + // PrincipalType - Principal type. Possible values include: 'PrincipalTypeApp', 'PrincipalTypeGroup', 'PrincipalTypeUser' + PrincipalType PrincipalType `json:"principalType,omitempty"` + // TenantName - READ-ONLY; The tenant name of the principal + TenantName *string `json:"tenantName,omitempty"` + // PrincipalName - READ-ONLY; The principal name + PrincipalName *string `json:"principalName,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // AadObjectID - READ-ONLY; The service principal object id in AAD (Azure active directory) + AadObjectID *string `json:"aadObjectId,omitempty"` +} + +// MarshalJSON is the custom marshaler for ClusterPrincipalProperties. +func (cpp ClusterPrincipalProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cpp.PrincipalID != nil { + objectMap["principalId"] = cpp.PrincipalID + } + if cpp.Role != "" { + objectMap["role"] = cpp.Role + } + if cpp.TenantID != nil { + objectMap["tenantId"] = cpp.TenantID + } + if cpp.PrincipalType != "" { + objectMap["principalType"] = cpp.PrincipalType + } + return json.Marshal(objectMap) +} + +// ClusterProperties class representing the Kusto cluster properties. +type ClusterProperties struct { + // State - READ-ONLY; The state of the resource. Possible values include: 'StateCreating', 'StateUnavailable', 'StateRunning', 'StateDeleting', 'StateDeleted', 'StateStopping', 'StateStopped', 'StateStarting', 'StateUpdating' + State State `json:"state,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // URI - READ-ONLY; The cluster URI. + URI *string `json:"uri,omitempty"` + // DataIngestionURI - READ-ONLY; The cluster data ingestion URI. + DataIngestionURI *string `json:"dataIngestionUri,omitempty"` + // StateReason - READ-ONLY; The reason for the cluster's current state. + StateReason *string `json:"stateReason,omitempty"` + // TrustedExternalTenants - The cluster's external tenants. + TrustedExternalTenants *[]TrustedExternalTenant `json:"trustedExternalTenants,omitempty"` + // OptimizedAutoscale - Optimized auto scale definition. + OptimizedAutoscale *OptimizedAutoscale `json:"optimizedAutoscale,omitempty"` + // EnableDiskEncryption - A boolean value that indicates if the cluster's disks are encrypted. + EnableDiskEncryption *bool `json:"enableDiskEncryption,omitempty"` + // EnableStreamingIngest - A boolean value that indicates if the streaming ingest is enabled. + EnableStreamingIngest *bool `json:"enableStreamingIngest,omitempty"` + // VirtualNetworkConfiguration - Virtual network definition. + VirtualNetworkConfiguration *VirtualNetworkConfiguration `json:"virtualNetworkConfiguration,omitempty"` + // KeyVaultProperties - KeyVault properties for the cluster encryption. + KeyVaultProperties *KeyVaultProperties `json:"keyVaultProperties,omitempty"` + // EnablePurge - A boolean value that indicates if the purge operations are enabled. + EnablePurge *bool `json:"enablePurge,omitempty"` + // LanguageExtensions - READ-ONLY; List of the cluster's language extensions. + LanguageExtensions *LanguageExtensionsList `json:"languageExtensions,omitempty"` + // EnableDoubleEncryption - A boolean value that indicates if double encryption is enabled. + EnableDoubleEncryption *bool `json:"enableDoubleEncryption,omitempty"` + // PublicNetworkAccess - Public network access to the cluster is enabled by default. When disabled, only private endpoint connection to the cluster is allowed. Possible values include: 'PublicNetworkAccessEnabled', 'PublicNetworkAccessDisabled' + PublicNetworkAccess PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + // AllowedIPRangeList - The list of ips in the format of CIDR allowed to connect to the cluster. + AllowedIPRangeList *[]string `json:"allowedIpRangeList,omitempty"` + // EngineType - The engine type. Possible values include: 'EngineTypeV2', 'EngineTypeV3' + EngineType EngineType `json:"engineType,omitempty"` + // AcceptedAudiences - The cluster's accepted audiences. + AcceptedAudiences *[]AcceptedAudiences `json:"acceptedAudiences,omitempty"` + // EnableAutoStop - A boolean value that indicates if the cluster could be automatically stopped (due to lack of data or no activity for many days). + EnableAutoStop *bool `json:"enableAutoStop,omitempty"` + // RestrictOutboundNetworkAccess - Whether or not to restrict outbound network access. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: 'ClusterNetworkAccessFlagEnabled', 'ClusterNetworkAccessFlagDisabled' + RestrictOutboundNetworkAccess ClusterNetworkAccessFlag `json:"restrictOutboundNetworkAccess,omitempty"` + // AllowedFqdnList - List of allowed FQDNs(Fully Qualified Domain Name) for egress from Cluster. + AllowedFqdnList *[]string `json:"allowedFqdnList,omitempty"` + // PublicIPType - Indicates what public IP type to create - IPv4 (default), or DualStack (both IPv4 and IPv6). Possible values include: 'PublicIPTypeIPv4', 'PublicIPTypeDualStack' + PublicIPType PublicIPType `json:"publicIPType,omitempty"` + // VirtualClusterGraduationProperties - Virtual Cluster graduation properties + VirtualClusterGraduationProperties *string `json:"virtualClusterGraduationProperties,omitempty"` + // PrivateEndpointConnections - READ-ONLY; A list of private endpoint connections. + PrivateEndpointConnections *[]PrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` +} + +// MarshalJSON is the custom marshaler for ClusterProperties. +func (cp ClusterProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cp.TrustedExternalTenants != nil { + objectMap["trustedExternalTenants"] = cp.TrustedExternalTenants + } + if cp.OptimizedAutoscale != nil { + objectMap["optimizedAutoscale"] = cp.OptimizedAutoscale + } + if cp.EnableDiskEncryption != nil { + objectMap["enableDiskEncryption"] = cp.EnableDiskEncryption + } + if cp.EnableStreamingIngest != nil { + objectMap["enableStreamingIngest"] = cp.EnableStreamingIngest + } + if cp.VirtualNetworkConfiguration != nil { + objectMap["virtualNetworkConfiguration"] = cp.VirtualNetworkConfiguration + } + if cp.KeyVaultProperties != nil { + objectMap["keyVaultProperties"] = cp.KeyVaultProperties + } + if cp.EnablePurge != nil { + objectMap["enablePurge"] = cp.EnablePurge + } + if cp.EnableDoubleEncryption != nil { + objectMap["enableDoubleEncryption"] = cp.EnableDoubleEncryption + } + if cp.PublicNetworkAccess != "" { + objectMap["publicNetworkAccess"] = cp.PublicNetworkAccess + } + if cp.AllowedIPRangeList != nil { + objectMap["allowedIpRangeList"] = cp.AllowedIPRangeList + } + if cp.EngineType != "" { + objectMap["engineType"] = cp.EngineType + } + if cp.AcceptedAudiences != nil { + objectMap["acceptedAudiences"] = cp.AcceptedAudiences + } + if cp.EnableAutoStop != nil { + objectMap["enableAutoStop"] = cp.EnableAutoStop + } + if cp.RestrictOutboundNetworkAccess != "" { + objectMap["restrictOutboundNetworkAccess"] = cp.RestrictOutboundNetworkAccess + } + if cp.AllowedFqdnList != nil { + objectMap["allowedFqdnList"] = cp.AllowedFqdnList + } + if cp.PublicIPType != "" { + objectMap["publicIPType"] = cp.PublicIPType + } + if cp.VirtualClusterGraduationProperties != nil { + objectMap["virtualClusterGraduationProperties"] = cp.VirtualClusterGraduationProperties + } + return json.Marshal(objectMap) +} + +// ClustersAddLanguageExtensionsFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ClustersAddLanguageExtensionsFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClustersClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClustersAddLanguageExtensionsFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClustersAddLanguageExtensionsFuture.Result. +func (future *ClustersAddLanguageExtensionsFuture) result(client ClustersClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersAddLanguageExtensionsFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClustersAddLanguageExtensionsFuture") + return + } + ar.Response = future.Response() + return +} + +// ClustersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ClustersCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClustersClient) (Cluster, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClustersCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClustersCreateOrUpdateFuture.Result. +func (future *ClustersCreateOrUpdateFuture) result(client ClustersClient) (c Cluster, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + c.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClustersCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if c.Response.Response, err = future.GetResult(sender); err == nil && c.Response.Response.StatusCode != http.StatusNoContent { + c, err = client.CreateOrUpdateResponder(c.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersCreateOrUpdateFuture", "Result", c.Response.Response, "Failure responding to request") + } + } + return +} + +// ClustersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ClustersDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClustersClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClustersDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClustersDeleteFuture.Result. +func (future *ClustersDeleteFuture) result(client ClustersClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClustersDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ClustersDetachFollowerDatabasesFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ClustersDetachFollowerDatabasesFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClustersClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClustersDetachFollowerDatabasesFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClustersDetachFollowerDatabasesFuture.Result. +func (future *ClustersDetachFollowerDatabasesFuture) result(client ClustersClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersDetachFollowerDatabasesFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClustersDetachFollowerDatabasesFuture") + return + } + ar.Response = future.Response() + return +} + +// ClustersDiagnoseVirtualNetworkFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ClustersDiagnoseVirtualNetworkFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClustersClient) (DiagnoseVirtualNetworkResult, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClustersDiagnoseVirtualNetworkFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClustersDiagnoseVirtualNetworkFuture.Result. +func (future *ClustersDiagnoseVirtualNetworkFuture) result(client ClustersClient) (dvnr DiagnoseVirtualNetworkResult, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersDiagnoseVirtualNetworkFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + dvnr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClustersDiagnoseVirtualNetworkFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dvnr.Response.Response, err = future.GetResult(sender); err == nil && dvnr.Response.Response.StatusCode != http.StatusNoContent { + dvnr, err = client.DiagnoseVirtualNetworkResponder(dvnr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersDiagnoseVirtualNetworkFuture", "Result", dvnr.Response.Response, "Failure responding to request") + } + } + return +} + +// ClustersRemoveLanguageExtensionsFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ClustersRemoveLanguageExtensionsFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClustersClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClustersRemoveLanguageExtensionsFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClustersRemoveLanguageExtensionsFuture.Result. +func (future *ClustersRemoveLanguageExtensionsFuture) result(client ClustersClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersRemoveLanguageExtensionsFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClustersRemoveLanguageExtensionsFuture") + return + } + ar.Response = future.Response() + return +} + +// ClustersStartFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ClustersStartFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClustersClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClustersStartFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClustersStartFuture.Result. +func (future *ClustersStartFuture) result(client ClustersClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersStartFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClustersStartFuture") + return + } + ar.Response = future.Response() + return +} + +// ClustersStopFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ClustersStopFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClustersClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClustersStopFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClustersStopFuture.Result. +func (future *ClustersStopFuture) result(client ClustersClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersStopFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClustersStopFuture") + return + } + ar.Response = future.Response() + return +} + +// ClustersUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ClustersUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ClustersClient) (Cluster, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ClustersUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ClustersUpdateFuture.Result. +func (future *ClustersUpdateFuture) result(client ClustersClient) (c Cluster, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + c.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ClustersUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if c.Response.Response, err = future.GetResult(sender); err == nil && c.Response.Response.StatusCode != http.StatusNoContent { + c, err = client.UpdateResponder(c.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ClustersUpdateFuture", "Result", c.Response.Response, "Failure responding to request") + } + } + return +} + +// ClusterUpdate class representing an update to a Kusto cluster. +type ClusterUpdate struct { + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Sku - The SKU of the cluster. + Sku *AzureSku `json:"sku,omitempty"` + // Identity - The identity of the cluster, if configured. + Identity *Identity `json:"identity,omitempty"` + // ClusterProperties - The cluster properties. + *ClusterProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ClusterUpdate. +func (cu ClusterUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cu.Tags != nil { + objectMap["tags"] = cu.Tags + } + if cu.Location != nil { + objectMap["location"] = cu.Location + } + if cu.Sku != nil { + objectMap["sku"] = cu.Sku + } + if cu.Identity != nil { + objectMap["identity"] = cu.Identity + } + if cu.ClusterProperties != nil { + objectMap["properties"] = cu.ClusterProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ClusterUpdate struct. +func (cu *ClusterUpdate) 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 "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + cu.Tags = tags + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + cu.Location = &location + } + case "sku": + if v != nil { + var sku AzureSku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + cu.Sku = &sku + } + case "identity": + if v != nil { + var identity Identity + err = json.Unmarshal(*v, &identity) + if err != nil { + return err + } + cu.Identity = &identity + } + case "properties": + if v != nil { + var clusterProperties ClusterProperties + err = json.Unmarshal(*v, &clusterProperties) + if err != nil { + return err + } + cu.ClusterProperties = &clusterProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + cu.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + cu.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + cu.Type = &typeVar + } + } + } + + return nil +} + +// BasicDatabase class representing a Kusto database. +type BasicDatabase interface { + AsReadWriteDatabase() (*ReadWriteDatabase, bool) + AsReadOnlyFollowingDatabase() (*ReadOnlyFollowingDatabase, bool) + AsDatabase() (*Database, bool) +} + +// Database class representing a Kusto database. +type Database struct { + autorest.Response `json:"-"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Kind - Possible values include: 'KindDatabase', 'KindReadWrite', 'KindReadOnlyFollowing' + Kind Kind `json:"kind,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +func unmarshalBasicDatabase(body []byte) (BasicDatabase, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["kind"] { + case string(KindReadWrite): + var rwd ReadWriteDatabase + err := json.Unmarshal(body, &rwd) + return rwd, err + case string(KindReadOnlyFollowing): + var rofd ReadOnlyFollowingDatabase + err := json.Unmarshal(body, &rofd) + return rofd, err + default: + var d Database + err := json.Unmarshal(body, &d) + return d, err + } +} +func unmarshalBasicDatabaseArray(body []byte) ([]BasicDatabase, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + dArray := make([]BasicDatabase, len(rawMessages)) + + for index, rawMessage := range rawMessages { + d, err := unmarshalBasicDatabase(*rawMessage) + if err != nil { + return nil, err + } + dArray[index] = d + } + return dArray, nil +} + +// MarshalJSON is the custom marshaler for Database. +func (d Database) MarshalJSON() ([]byte, error) { + d.Kind = KindDatabase + objectMap := make(map[string]interface{}) + if d.Location != nil { + objectMap["location"] = d.Location + } + if d.Kind != "" { + objectMap["kind"] = d.Kind + } + return json.Marshal(objectMap) +} + +// AsReadWriteDatabase is the BasicDatabase implementation for Database. +func (d Database) AsReadWriteDatabase() (*ReadWriteDatabase, bool) { + return nil, false +} + +// AsReadOnlyFollowingDatabase is the BasicDatabase implementation for Database. +func (d Database) AsReadOnlyFollowingDatabase() (*ReadOnlyFollowingDatabase, bool) { + return nil, false +} + +// AsDatabase is the BasicDatabase implementation for Database. +func (d Database) AsDatabase() (*Database, bool) { + return &d, true +} + +// AsBasicDatabase is the BasicDatabase implementation for Database. +func (d Database) AsBasicDatabase() (BasicDatabase, bool) { + return &d, true +} + +// DatabaseListResult the list Kusto databases operation response. +type DatabaseListResult struct { + autorest.Response `json:"-"` + // Value - The list of Kusto databases. + Value *[]BasicDatabase `json:"value,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for DatabaseListResult struct. +func (dlr *DatabaseListResult) 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 "value": + if v != nil { + value, err := unmarshalBasicDatabaseArray(*v) + if err != nil { + return err + } + dlr.Value = &value + } + } + } + + return nil +} + +// DatabaseModel ... +type DatabaseModel struct { + autorest.Response `json:"-"` + Value BasicDatabase `json:"value,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for DatabaseModel struct. +func (dm *DatabaseModel) UnmarshalJSON(body []byte) error { + d, err := unmarshalBasicDatabase(body) + if err != nil { + return err + } + dm.Value = d + + return nil +} + +// DatabasePrincipal a class representing database principal entity. +type DatabasePrincipal struct { + // Role - Database principal role. Possible values include: 'DatabasePrincipalRoleAdmin', 'DatabasePrincipalRoleIngestor', 'DatabasePrincipalRoleMonitor', 'DatabasePrincipalRoleUser', 'DatabasePrincipalRoleUnrestrictedViewer', 'DatabasePrincipalRoleViewer' + Role DatabasePrincipalRole `json:"role,omitempty"` + // Name - Database principal name. + Name *string `json:"name,omitempty"` + // Type - Database principal type. Possible values include: 'DatabasePrincipalTypeApp', 'DatabasePrincipalTypeGroup', 'DatabasePrincipalTypeUser' + Type DatabasePrincipalType `json:"type,omitempty"` + // Fqn - Database principal fully qualified name. + Fqn *string `json:"fqn,omitempty"` + // Email - Database principal email if exists. + Email *string `json:"email,omitempty"` + // AppID - Application id - relevant only for application principal type. + AppID *string `json:"appId,omitempty"` + // TenantName - READ-ONLY; The tenant name of the principal + TenantName *string `json:"tenantName,omitempty"` +} + +// MarshalJSON is the custom marshaler for DatabasePrincipal. +func (dp DatabasePrincipal) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if dp.Role != "" { + objectMap["role"] = dp.Role + } + if dp.Name != nil { + objectMap["name"] = dp.Name + } + if dp.Type != "" { + objectMap["type"] = dp.Type + } + if dp.Fqn != nil { + objectMap["fqn"] = dp.Fqn + } + if dp.Email != nil { + objectMap["email"] = dp.Email + } + if dp.AppID != nil { + objectMap["appId"] = dp.AppID + } + return json.Marshal(objectMap) +} + +// DatabasePrincipalAssignment class representing a database principal assignment. +type DatabasePrincipalAssignment struct { + autorest.Response `json:"-"` + // DatabasePrincipalProperties - The database principal. + *DatabasePrincipalProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for DatabasePrincipalAssignment. +func (dpa DatabasePrincipalAssignment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if dpa.DatabasePrincipalProperties != nil { + objectMap["properties"] = dpa.DatabasePrincipalProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DatabasePrincipalAssignment struct. +func (dpa *DatabasePrincipalAssignment) 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 databasePrincipalProperties DatabasePrincipalProperties + err = json.Unmarshal(*v, &databasePrincipalProperties) + if err != nil { + return err + } + dpa.DatabasePrincipalProperties = &databasePrincipalProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + dpa.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + dpa.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + dpa.Type = &typeVar + } + } + } + + return nil +} + +// DatabasePrincipalAssignmentCheckNameRequest a principal assignment check name availability request. +type DatabasePrincipalAssignmentCheckNameRequest struct { + // Name - Principal Assignment resource name. + Name *string `json:"name,omitempty"` + // Type - The type of resource, Microsoft.Kusto/clusters/databases/principalAssignments. + Type *string `json:"type,omitempty"` +} + +// DatabasePrincipalAssignmentListResult the list Kusto database principal assignments operation response. +type DatabasePrincipalAssignmentListResult struct { + autorest.Response `json:"-"` + // Value - The list of Kusto database principal assignments. + Value *[]DatabasePrincipalAssignment `json:"value,omitempty"` +} + +// DatabasePrincipalAssignmentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the +// results of a long-running operation. +type DatabasePrincipalAssignmentsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DatabasePrincipalAssignmentsClient) (DatabasePrincipalAssignment, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DatabasePrincipalAssignmentsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DatabasePrincipalAssignmentsCreateOrUpdateFuture.Result. +func (future *DatabasePrincipalAssignmentsCreateOrUpdateFuture) result(client DatabasePrincipalAssignmentsClient) (dpa DatabasePrincipalAssignment, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + dpa.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.DatabasePrincipalAssignmentsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dpa.Response.Response, err = future.GetResult(sender); err == nil && dpa.Response.Response.StatusCode != http.StatusNoContent { + dpa, err = client.CreateOrUpdateResponder(dpa.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsCreateOrUpdateFuture", "Result", dpa.Response.Response, "Failure responding to request") + } + } + return +} + +// DatabasePrincipalAssignmentsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type DatabasePrincipalAssignmentsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DatabasePrincipalAssignmentsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DatabasePrincipalAssignmentsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DatabasePrincipalAssignmentsDeleteFuture.Result. +func (future *DatabasePrincipalAssignmentsDeleteFuture) result(client DatabasePrincipalAssignmentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.DatabasePrincipalAssignmentsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// DatabasePrincipalListRequest the list Kusto database principals operation request. +type DatabasePrincipalListRequest struct { + // Value - The list of Kusto database principals. + Value *[]DatabasePrincipal `json:"value,omitempty"` +} + +// DatabasePrincipalListResult the list Kusto database principals operation response. +type DatabasePrincipalListResult struct { + autorest.Response `json:"-"` + // Value - The list of Kusto database principals. + Value *[]DatabasePrincipal `json:"value,omitempty"` +} + +// DatabasePrincipalProperties a class representing database principal property. +type DatabasePrincipalProperties struct { + // PrincipalID - The principal ID assigned to the database principal. It can be a user email, application ID, or security group name. + PrincipalID *string `json:"principalId,omitempty"` + // Role - Database principal role. Possible values include: 'DatabasePrincipalRoleAdmin', 'DatabasePrincipalRoleIngestor', 'DatabasePrincipalRoleMonitor', 'DatabasePrincipalRoleUser', 'DatabasePrincipalRoleUnrestrictedViewer', 'DatabasePrincipalRoleViewer' + Role DatabasePrincipalRole `json:"role,omitempty"` + // TenantID - The tenant id of the principal + TenantID *string `json:"tenantId,omitempty"` + // PrincipalType - Principal type. Possible values include: 'PrincipalTypeApp', 'PrincipalTypeGroup', 'PrincipalTypeUser' + PrincipalType PrincipalType `json:"principalType,omitempty"` + // TenantName - READ-ONLY; The tenant name of the principal + TenantName *string `json:"tenantName,omitempty"` + // PrincipalName - READ-ONLY; The principal name + PrincipalName *string `json:"principalName,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // AadObjectID - READ-ONLY; The service principal object id in AAD (Azure active directory) + AadObjectID *string `json:"aadObjectId,omitempty"` +} + +// MarshalJSON is the custom marshaler for DatabasePrincipalProperties. +func (dpp DatabasePrincipalProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if dpp.PrincipalID != nil { + objectMap["principalId"] = dpp.PrincipalID + } + if dpp.Role != "" { + objectMap["role"] = dpp.Role + } + if dpp.TenantID != nil { + objectMap["tenantId"] = dpp.TenantID + } + if dpp.PrincipalType != "" { + objectMap["principalType"] = dpp.PrincipalType + } + return json.Marshal(objectMap) +} + +// DatabasesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DatabasesCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DatabasesClient) (DatabaseModel, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DatabasesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DatabasesCreateOrUpdateFuture.Result. +func (future *DatabasesCreateOrUpdateFuture) result(client DatabasesClient) (dm DatabaseModel, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + dm.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.DatabasesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dm.Response.Response, err = future.GetResult(sender); err == nil && dm.Response.Response.StatusCode != http.StatusNoContent { + dm, err = client.CreateOrUpdateResponder(dm.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesCreateOrUpdateFuture", "Result", dm.Response.Response, "Failure responding to request") + } + } + return +} + +// DatabasesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DatabasesDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DatabasesClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DatabasesDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DatabasesDeleteFuture.Result. +func (future *DatabasesDeleteFuture) result(client DatabasesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.DatabasesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// DatabaseStatistics a class that contains database statistics information. +type DatabaseStatistics struct { + // Size - The database size - the total size of compressed data and index in bytes. + Size *float64 `json:"size,omitempty"` +} + +// DatabasesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DatabasesUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DatabasesClient) (DatabaseModel, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DatabasesUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DatabasesUpdateFuture.Result. +func (future *DatabasesUpdateFuture) result(client DatabasesClient) (dm DatabaseModel, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + dm.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.DatabasesUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dm.Response.Response, err = future.GetResult(sender); err == nil && dm.Response.Response.StatusCode != http.StatusNoContent { + dm, err = client.UpdateResponder(dm.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DatabasesUpdateFuture", "Result", dm.Response.Response, "Failure responding to request") + } + } + return +} + +// BasicDataConnection class representing an data connection. +type BasicDataConnection interface { + AsEventHubDataConnection() (*EventHubDataConnection, bool) + AsIotHubDataConnection() (*IotHubDataConnection, bool) + AsEventGridDataConnection() (*EventGridDataConnection, bool) + AsDataConnection() (*DataConnection, bool) +} + +// DataConnection class representing an data connection. +type DataConnection struct { + autorest.Response `json:"-"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Kind - Possible values include: 'KindBasicDataConnectionKindDataConnection', 'KindBasicDataConnectionKindEventHub', 'KindBasicDataConnectionKindIotHub', 'KindBasicDataConnectionKindEventGrid' + Kind KindBasicDataConnection `json:"kind,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +func unmarshalBasicDataConnection(body []byte) (BasicDataConnection, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["kind"] { + case string(KindBasicDataConnectionKindEventHub): + var ehdc EventHubDataConnection + err := json.Unmarshal(body, &ehdc) + return ehdc, err + case string(KindBasicDataConnectionKindIotHub): + var ihdc IotHubDataConnection + err := json.Unmarshal(body, &ihdc) + return ihdc, err + case string(KindBasicDataConnectionKindEventGrid): + var egdc EventGridDataConnection + err := json.Unmarshal(body, &egdc) + return egdc, err + default: + var dc DataConnection + err := json.Unmarshal(body, &dc) + return dc, err + } +} +func unmarshalBasicDataConnectionArray(body []byte) ([]BasicDataConnection, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + dcArray := make([]BasicDataConnection, len(rawMessages)) + + for index, rawMessage := range rawMessages { + dc, err := unmarshalBasicDataConnection(*rawMessage) + if err != nil { + return nil, err + } + dcArray[index] = dc + } + return dcArray, nil +} + +// MarshalJSON is the custom marshaler for DataConnection. +func (dc DataConnection) MarshalJSON() ([]byte, error) { + dc.Kind = KindBasicDataConnectionKindDataConnection + objectMap := make(map[string]interface{}) + if dc.Location != nil { + objectMap["location"] = dc.Location + } + if dc.Kind != "" { + objectMap["kind"] = dc.Kind + } + return json.Marshal(objectMap) +} + +// AsEventHubDataConnection is the BasicDataConnection implementation for DataConnection. +func (dc DataConnection) AsEventHubDataConnection() (*EventHubDataConnection, bool) { + return nil, false +} + +// AsIotHubDataConnection is the BasicDataConnection implementation for DataConnection. +func (dc DataConnection) AsIotHubDataConnection() (*IotHubDataConnection, bool) { + return nil, false +} + +// AsEventGridDataConnection is the BasicDataConnection implementation for DataConnection. +func (dc DataConnection) AsEventGridDataConnection() (*EventGridDataConnection, bool) { + return nil, false +} + +// AsDataConnection is the BasicDataConnection implementation for DataConnection. +func (dc DataConnection) AsDataConnection() (*DataConnection, bool) { + return &dc, true +} + +// AsBasicDataConnection is the BasicDataConnection implementation for DataConnection. +func (dc DataConnection) AsBasicDataConnection() (BasicDataConnection, bool) { + return &dc, true +} + +// DataConnectionCheckNameRequest a data connection check name availability request. +type DataConnectionCheckNameRequest struct { + // Name - Data Connection name. + Name *string `json:"name,omitempty"` + // Type - The type of resource, Microsoft.Kusto/clusters/databases/dataConnections. + Type *string `json:"type,omitempty"` +} + +// DataConnectionListResult the list Kusto data connections operation response. +type DataConnectionListResult struct { + autorest.Response `json:"-"` + // Value - The list of Kusto data connections. + Value *[]BasicDataConnection `json:"value,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for DataConnectionListResult struct. +func (dclr *DataConnectionListResult) 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 "value": + if v != nil { + value, err := unmarshalBasicDataConnectionArray(*v) + if err != nil { + return err + } + dclr.Value = &value + } + } + } + + return nil +} + +// DataConnectionModel ... +type DataConnectionModel struct { + autorest.Response `json:"-"` + Value BasicDataConnection `json:"value,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for DataConnectionModel struct. +func (dcm *DataConnectionModel) UnmarshalJSON(body []byte) error { + dc, err := unmarshalBasicDataConnection(body) + if err != nil { + return err + } + dcm.Value = dc + + return nil +} + +// DataConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type DataConnectionsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DataConnectionsClient) (DataConnectionModel, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DataConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DataConnectionsCreateOrUpdateFuture.Result. +func (future *DataConnectionsCreateOrUpdateFuture) result(client DataConnectionsClient) (dcm DataConnectionModel, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + dcm.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.DataConnectionsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dcm.Response.Response, err = future.GetResult(sender); err == nil && dcm.Response.Response.StatusCode != http.StatusNoContent { + dcm, err = client.CreateOrUpdateResponder(dcm.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsCreateOrUpdateFuture", "Result", dcm.Response.Response, "Failure responding to request") + } + } + return +} + +// DataConnectionsDataConnectionValidationMethodFuture an abstraction for monitoring and retrieving the +// results of a long-running operation. +type DataConnectionsDataConnectionValidationMethodFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DataConnectionsClient) (DataConnectionValidationListResult, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DataConnectionsDataConnectionValidationMethodFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DataConnectionsDataConnectionValidationMethodFuture.Result. +func (future *DataConnectionsDataConnectionValidationMethodFuture) result(client DataConnectionsClient) (dcvlr DataConnectionValidationListResult, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsDataConnectionValidationMethodFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + dcvlr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.DataConnectionsDataConnectionValidationMethodFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dcvlr.Response.Response, err = future.GetResult(sender); err == nil && dcvlr.Response.Response.StatusCode != http.StatusNoContent { + dcvlr, err = client.DataConnectionValidationMethodResponder(dcvlr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsDataConnectionValidationMethodFuture", "Result", dcvlr.Response.Response, "Failure responding to request") + } + } + return +} + +// DataConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DataConnectionsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DataConnectionsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DataConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DataConnectionsDeleteFuture.Result. +func (future *DataConnectionsDeleteFuture) result(client DataConnectionsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.DataConnectionsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// DataConnectionsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DataConnectionsUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DataConnectionsClient) (DataConnectionModel, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DataConnectionsUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DataConnectionsUpdateFuture.Result. +func (future *DataConnectionsUpdateFuture) result(client DataConnectionsClient) (dcm DataConnectionModel, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + dcm.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.DataConnectionsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dcm.Response.Response, err = future.GetResult(sender); err == nil && dcm.Response.Response.StatusCode != http.StatusNoContent { + dcm, err = client.UpdateResponder(dcm.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.DataConnectionsUpdateFuture", "Result", dcm.Response.Response, "Failure responding to request") + } + } + return +} + +// DataConnectionValidation class representing an data connection validation. +type DataConnectionValidation struct { + // DataConnectionName - The name of the data connection. + DataConnectionName *string `json:"dataConnectionName,omitempty"` + // Properties - The data connection properties to validate. + Properties BasicDataConnection `json:"properties,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for DataConnectionValidation struct. +func (dcv *DataConnectionValidation) 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 "dataConnectionName": + if v != nil { + var dataConnectionName string + err = json.Unmarshal(*v, &dataConnectionName) + if err != nil { + return err + } + dcv.DataConnectionName = &dataConnectionName + } + case "properties": + if v != nil { + properties, err := unmarshalBasicDataConnection(*v) + if err != nil { + return err + } + dcv.Properties = properties + } + } + } + + return nil +} + +// DataConnectionValidationListResult the list Kusto data connection validation result. +type DataConnectionValidationListResult struct { + autorest.Response `json:"-"` + // Value - The list of Kusto data connection validation errors. + Value *[]DataConnectionValidationResult `json:"value,omitempty"` +} + +// DataConnectionValidationResult the result returned from a data connection validation request. +type DataConnectionValidationResult struct { + // ErrorMessage - A message which indicates a problem in data connection validation. + ErrorMessage *string `json:"errorMessage,omitempty"` +} + +// DiagnoseVirtualNetworkResult ... +type DiagnoseVirtualNetworkResult struct { + autorest.Response `json:"-"` + // Findings - The list of network connectivity diagnostic finding + Findings *[]string `json:"findings,omitempty"` +} + +// EndpointDependency a domain name that a service is reached at, including details of the current +// connection status. +type EndpointDependency struct { + // DomainName - The domain name of the dependency. + DomainName *string `json:"domainName,omitempty"` + // EndpointDetails - The ports used when connecting to DomainName. + EndpointDetails *[]EndpointDetail `json:"endpointDetails,omitempty"` +} + +// EndpointDetail current TCP connectivity information from the Kusto cluster to a single endpoint. +type EndpointDetail struct { + // Port - The port an endpoint is connected to. + Port *int32 `json:"port,omitempty"` +} + +// EventGridConnectionProperties class representing the Kusto event grid connection properties. +type EventGridConnectionProperties struct { + // StorageAccountResourceID - The resource ID of the storage account where the data resides. + StorageAccountResourceID *string `json:"storageAccountResourceId,omitempty"` + // EventGridResourceID - The resource ID of the event grid that is subscribed to the storage account events. + EventGridResourceID *string `json:"eventGridResourceId,omitempty"` + // EventHubResourceID - The resource ID where the event grid is configured to send events. + EventHubResourceID *string `json:"eventHubResourceId,omitempty"` + // ConsumerGroup - The event hub consumer group. + ConsumerGroup *string `json:"consumerGroup,omitempty"` + // TableName - The table where the data should be ingested. Optionally the table information can be added to each message. + TableName *string `json:"tableName,omitempty"` + // MappingRuleName - The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. + MappingRuleName *string `json:"mappingRuleName,omitempty"` + // DataFormat - The data format of the message. Optionally the data format can be added to each message. Possible values include: 'EventGridDataFormatMULTIJSON', 'EventGridDataFormatJSON', 'EventGridDataFormatCSV', 'EventGridDataFormatTSV', 'EventGridDataFormatSCSV', 'EventGridDataFormatSOHSV', 'EventGridDataFormatPSV', 'EventGridDataFormatTXT', 'EventGridDataFormatRAW', 'EventGridDataFormatSINGLEJSON', 'EventGridDataFormatAVRO', 'EventGridDataFormatTSVE', 'EventGridDataFormatPARQUET', 'EventGridDataFormatORC', 'EventGridDataFormatAPACHEAVRO', 'EventGridDataFormatW3CLOGFILE' + DataFormat EventGridDataFormat `json:"dataFormat,omitempty"` + // IgnoreFirstRecord - A Boolean value that, if set to true, indicates that ingestion should ignore the first record of every file + IgnoreFirstRecord *bool `json:"ignoreFirstRecord,omitempty"` + // BlobStorageEventType - The name of blob storage event type to process. Possible values include: 'BlobStorageEventTypeMicrosoftStorageBlobCreated', 'BlobStorageEventTypeMicrosoftStorageBlobRenamed' + BlobStorageEventType BlobStorageEventType `json:"blobStorageEventType,omitempty"` + // ManagedIdentityResourceID - The resource ID of a managed identity (system or user assigned) to be used to authenticate with event hub and storage account. + ManagedIdentityResourceID *string `json:"managedIdentityResourceId,omitempty"` + // ManagedIdentityObjectID - READ-ONLY; The object ID of managedIdentityResourceId + ManagedIdentityObjectID *string `json:"managedIdentityObjectId,omitempty"` + // DatabaseRouting - Indication for database routing information from the data connection, by default only database routing information is allowed. Possible values include: 'DatabaseRoutingSingle', 'DatabaseRoutingMulti' + DatabaseRouting DatabaseRouting `json:"databaseRouting,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` +} + +// MarshalJSON is the custom marshaler for EventGridConnectionProperties. +func (egcp EventGridConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if egcp.StorageAccountResourceID != nil { + objectMap["storageAccountResourceId"] = egcp.StorageAccountResourceID + } + if egcp.EventGridResourceID != nil { + objectMap["eventGridResourceId"] = egcp.EventGridResourceID + } + if egcp.EventHubResourceID != nil { + objectMap["eventHubResourceId"] = egcp.EventHubResourceID + } + if egcp.ConsumerGroup != nil { + objectMap["consumerGroup"] = egcp.ConsumerGroup + } + if egcp.TableName != nil { + objectMap["tableName"] = egcp.TableName + } + if egcp.MappingRuleName != nil { + objectMap["mappingRuleName"] = egcp.MappingRuleName + } + if egcp.DataFormat != "" { + objectMap["dataFormat"] = egcp.DataFormat + } + if egcp.IgnoreFirstRecord != nil { + objectMap["ignoreFirstRecord"] = egcp.IgnoreFirstRecord + } + if egcp.BlobStorageEventType != "" { + objectMap["blobStorageEventType"] = egcp.BlobStorageEventType + } + if egcp.ManagedIdentityResourceID != nil { + objectMap["managedIdentityResourceId"] = egcp.ManagedIdentityResourceID + } + if egcp.DatabaseRouting != "" { + objectMap["databaseRouting"] = egcp.DatabaseRouting + } + return json.Marshal(objectMap) +} + +// EventGridDataConnection class representing an Event Grid data connection. +type EventGridDataConnection struct { + // EventGridConnectionProperties - The properties of the Event Grid data connection. + *EventGridConnectionProperties `json:"properties,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Kind - Possible values include: 'KindBasicDataConnectionKindDataConnection', 'KindBasicDataConnectionKindEventHub', 'KindBasicDataConnectionKindIotHub', 'KindBasicDataConnectionKindEventGrid' + Kind KindBasicDataConnection `json:"kind,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for EventGridDataConnection. +func (egdc EventGridDataConnection) MarshalJSON() ([]byte, error) { + egdc.Kind = KindBasicDataConnectionKindEventGrid + objectMap := make(map[string]interface{}) + if egdc.EventGridConnectionProperties != nil { + objectMap["properties"] = egdc.EventGridConnectionProperties + } + if egdc.Location != nil { + objectMap["location"] = egdc.Location + } + if egdc.Kind != "" { + objectMap["kind"] = egdc.Kind + } + return json.Marshal(objectMap) +} + +// AsEventHubDataConnection is the BasicDataConnection implementation for EventGridDataConnection. +func (egdc EventGridDataConnection) AsEventHubDataConnection() (*EventHubDataConnection, bool) { + return nil, false +} + +// AsIotHubDataConnection is the BasicDataConnection implementation for EventGridDataConnection. +func (egdc EventGridDataConnection) AsIotHubDataConnection() (*IotHubDataConnection, bool) { + return nil, false +} + +// AsEventGridDataConnection is the BasicDataConnection implementation for EventGridDataConnection. +func (egdc EventGridDataConnection) AsEventGridDataConnection() (*EventGridDataConnection, bool) { + return &egdc, true +} + +// AsDataConnection is the BasicDataConnection implementation for EventGridDataConnection. +func (egdc EventGridDataConnection) AsDataConnection() (*DataConnection, bool) { + return nil, false +} + +// AsBasicDataConnection is the BasicDataConnection implementation for EventGridDataConnection. +func (egdc EventGridDataConnection) AsBasicDataConnection() (BasicDataConnection, bool) { + return &egdc, true +} + +// UnmarshalJSON is the custom unmarshaler for EventGridDataConnection struct. +func (egdc *EventGridDataConnection) 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 eventGridConnectionProperties EventGridConnectionProperties + err = json.Unmarshal(*v, &eventGridConnectionProperties) + if err != nil { + return err + } + egdc.EventGridConnectionProperties = &eventGridConnectionProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + egdc.Location = &location + } + case "kind": + if v != nil { + var kind KindBasicDataConnection + err = json.Unmarshal(*v, &kind) + if err != nil { + return err + } + egdc.Kind = kind + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + egdc.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + egdc.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + egdc.Type = &typeVar + } + } + } + + return nil +} + +// EventHubConnectionProperties class representing the Kusto event hub connection properties. +type EventHubConnectionProperties struct { + // EventHubResourceID - The resource ID of the event hub to be used to create a data connection. + EventHubResourceID *string `json:"eventHubResourceId,omitempty"` + // ConsumerGroup - The event hub consumer group. + ConsumerGroup *string `json:"consumerGroup,omitempty"` + // TableName - The table where the data should be ingested. Optionally the table information can be added to each message. + TableName *string `json:"tableName,omitempty"` + // MappingRuleName - The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. + MappingRuleName *string `json:"mappingRuleName,omitempty"` + // DataFormat - The data format of the message. Optionally the data format can be added to each message. Possible values include: 'EventHubDataFormatMULTIJSON', 'EventHubDataFormatJSON', 'EventHubDataFormatCSV', 'EventHubDataFormatTSV', 'EventHubDataFormatSCSV', 'EventHubDataFormatSOHSV', 'EventHubDataFormatPSV', 'EventHubDataFormatTXT', 'EventHubDataFormatRAW', 'EventHubDataFormatSINGLEJSON', 'EventHubDataFormatAVRO', 'EventHubDataFormatTSVE', 'EventHubDataFormatPARQUET', 'EventHubDataFormatORC', 'EventHubDataFormatAPACHEAVRO', 'EventHubDataFormatW3CLOGFILE' + DataFormat EventHubDataFormat `json:"dataFormat,omitempty"` + // EventSystemProperties - System properties of the event hub + EventSystemProperties *[]string `json:"eventSystemProperties,omitempty"` + // Compression - The event hub messages compression type. Possible values include: 'CompressionNone', 'CompressionGZip' + Compression Compression `json:"compression,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // ManagedIdentityResourceID - Empty for non-managed identity based data connection. For system assigned identity, provide cluster resource Id. For user assigned identity (UAI) provide the UAI resource Id. + ManagedIdentityResourceID *string `json:"managedIdentityResourceId,omitempty"` + // ManagedIdentityObjectID - READ-ONLY; The object ID of the managedIdentityResourceId + ManagedIdentityObjectID *string `json:"managedIdentityObjectId,omitempty"` + // DatabaseRouting - Indication for database routing information from the data connection, by default only database routing information is allowed. Possible values include: 'DatabaseRoutingSingle', 'DatabaseRoutingMulti' + DatabaseRouting DatabaseRouting `json:"databaseRouting,omitempty"` +} + +// MarshalJSON is the custom marshaler for EventHubConnectionProperties. +func (ehcp EventHubConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ehcp.EventHubResourceID != nil { + objectMap["eventHubResourceId"] = ehcp.EventHubResourceID + } + if ehcp.ConsumerGroup != nil { + objectMap["consumerGroup"] = ehcp.ConsumerGroup + } + if ehcp.TableName != nil { + objectMap["tableName"] = ehcp.TableName + } + if ehcp.MappingRuleName != nil { + objectMap["mappingRuleName"] = ehcp.MappingRuleName + } + if ehcp.DataFormat != "" { + objectMap["dataFormat"] = ehcp.DataFormat + } + if ehcp.EventSystemProperties != nil { + objectMap["eventSystemProperties"] = ehcp.EventSystemProperties + } + if ehcp.Compression != "" { + objectMap["compression"] = ehcp.Compression + } + if ehcp.ManagedIdentityResourceID != nil { + objectMap["managedIdentityResourceId"] = ehcp.ManagedIdentityResourceID + } + if ehcp.DatabaseRouting != "" { + objectMap["databaseRouting"] = ehcp.DatabaseRouting + } + return json.Marshal(objectMap) +} + +// EventHubDataConnection class representing an event hub data connection. +type EventHubDataConnection struct { + // EventHubConnectionProperties - The Event Hub data connection properties to validate. + *EventHubConnectionProperties `json:"properties,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Kind - Possible values include: 'KindBasicDataConnectionKindDataConnection', 'KindBasicDataConnectionKindEventHub', 'KindBasicDataConnectionKindIotHub', 'KindBasicDataConnectionKindEventGrid' + Kind KindBasicDataConnection `json:"kind,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for EventHubDataConnection. +func (ehdc EventHubDataConnection) MarshalJSON() ([]byte, error) { + ehdc.Kind = KindBasicDataConnectionKindEventHub + objectMap := make(map[string]interface{}) + if ehdc.EventHubConnectionProperties != nil { + objectMap["properties"] = ehdc.EventHubConnectionProperties + } + if ehdc.Location != nil { + objectMap["location"] = ehdc.Location + } + if ehdc.Kind != "" { + objectMap["kind"] = ehdc.Kind + } + return json.Marshal(objectMap) +} + +// AsEventHubDataConnection is the BasicDataConnection implementation for EventHubDataConnection. +func (ehdc EventHubDataConnection) AsEventHubDataConnection() (*EventHubDataConnection, bool) { + return &ehdc, true +} + +// AsIotHubDataConnection is the BasicDataConnection implementation for EventHubDataConnection. +func (ehdc EventHubDataConnection) AsIotHubDataConnection() (*IotHubDataConnection, bool) { + return nil, false +} + +// AsEventGridDataConnection is the BasicDataConnection implementation for EventHubDataConnection. +func (ehdc EventHubDataConnection) AsEventGridDataConnection() (*EventGridDataConnection, bool) { + return nil, false +} + +// AsDataConnection is the BasicDataConnection implementation for EventHubDataConnection. +func (ehdc EventHubDataConnection) AsDataConnection() (*DataConnection, bool) { + return nil, false +} + +// AsBasicDataConnection is the BasicDataConnection implementation for EventHubDataConnection. +func (ehdc EventHubDataConnection) AsBasicDataConnection() (BasicDataConnection, bool) { + return &ehdc, true +} + +// UnmarshalJSON is the custom unmarshaler for EventHubDataConnection struct. +func (ehdc *EventHubDataConnection) 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 eventHubConnectionProperties EventHubConnectionProperties + err = json.Unmarshal(*v, &eventHubConnectionProperties) + if err != nil { + return err + } + ehdc.EventHubConnectionProperties = &eventHubConnectionProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + ehdc.Location = &location + } + case "kind": + if v != nil { + var kind KindBasicDataConnection + err = json.Unmarshal(*v, &kind) + if err != nil { + return err + } + ehdc.Kind = kind + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ehdc.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ehdc.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ehdc.Type = &typeVar + } + } + } + + return nil +} + +// FollowerDatabaseDefinition a class representing follower database request. +type FollowerDatabaseDefinition struct { + // ClusterResourceID - Resource id of the cluster that follows a database owned by this cluster. + ClusterResourceID *string `json:"clusterResourceId,omitempty"` + // AttachedDatabaseConfigurationName - Resource name of the attached database configuration in the follower cluster. + AttachedDatabaseConfigurationName *string `json:"attachedDatabaseConfigurationName,omitempty"` + // DatabaseName - READ-ONLY; The database name owned by this cluster that was followed. * in case following all databases. + DatabaseName *string `json:"databaseName,omitempty"` +} + +// MarshalJSON is the custom marshaler for FollowerDatabaseDefinition. +func (fdd FollowerDatabaseDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if fdd.ClusterResourceID != nil { + objectMap["clusterResourceId"] = fdd.ClusterResourceID + } + if fdd.AttachedDatabaseConfigurationName != nil { + objectMap["attachedDatabaseConfigurationName"] = fdd.AttachedDatabaseConfigurationName + } + return json.Marshal(objectMap) +} + +// FollowerDatabaseListResult the list Kusto database principals operation response. +type FollowerDatabaseListResult struct { + autorest.Response `json:"-"` + // Value - The list of follower database result. + Value *[]FollowerDatabaseDefinition `json:"value,omitempty"` +} + +// Identity identity for the resource. +type Identity struct { + // PrincipalID - READ-ONLY; The principal ID of resource identity. + PrincipalID *string `json:"principalId,omitempty"` + // TenantID - READ-ONLY; The tenant ID of resource. + TenantID *string `json:"tenantId,omitempty"` + // Type - The type of managed identity used. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user-assigned identities. The type 'None' will remove all identities. Possible values include: 'IdentityTypeNone', 'IdentityTypeSystemAssigned', 'IdentityTypeUserAssigned', 'IdentityTypeSystemAssignedUserAssigned' + Type IdentityType `json:"type,omitempty"` + // UserAssignedIdentities - The list of user identities associated with the Kusto cluster. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + UserAssignedIdentities map[string]*IdentityUserAssignedIdentitiesValue `json:"userAssignedIdentities"` +} + +// MarshalJSON is the custom marshaler for Identity. +func (i Identity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if i.Type != "" { + objectMap["type"] = i.Type + } + if i.UserAssignedIdentities != nil { + objectMap["userAssignedIdentities"] = i.UserAssignedIdentities + } + return json.Marshal(objectMap) +} + +// IdentityUserAssignedIdentitiesValue ... +type IdentityUserAssignedIdentitiesValue struct { + // PrincipalID - READ-ONLY; The principal id of user assigned identity. + PrincipalID *string `json:"principalId,omitempty"` + // ClientID - READ-ONLY; The client id of user assigned identity. + ClientID *string `json:"clientId,omitempty"` +} + +// MarshalJSON is the custom marshaler for IdentityUserAssignedIdentitiesValue. +func (iAiv IdentityUserAssignedIdentitiesValue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// IotHubConnectionProperties class representing the Kusto Iot hub connection properties. +type IotHubConnectionProperties struct { + // IotHubResourceID - The resource ID of the Iot hub to be used to create a data connection. + IotHubResourceID *string `json:"iotHubResourceId,omitempty"` + // ConsumerGroup - The iot hub consumer group. + ConsumerGroup *string `json:"consumerGroup,omitempty"` + // TableName - The table where the data should be ingested. Optionally the table information can be added to each message. + TableName *string `json:"tableName,omitempty"` + // MappingRuleName - The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. + MappingRuleName *string `json:"mappingRuleName,omitempty"` + // DataFormat - The data format of the message. Optionally the data format can be added to each message. Possible values include: 'IotHubDataFormatMULTIJSON', 'IotHubDataFormatJSON', 'IotHubDataFormatCSV', 'IotHubDataFormatTSV', 'IotHubDataFormatSCSV', 'IotHubDataFormatSOHSV', 'IotHubDataFormatPSV', 'IotHubDataFormatTXT', 'IotHubDataFormatRAW', 'IotHubDataFormatSINGLEJSON', 'IotHubDataFormatAVRO', 'IotHubDataFormatTSVE', 'IotHubDataFormatPARQUET', 'IotHubDataFormatORC', 'IotHubDataFormatAPACHEAVRO', 'IotHubDataFormatW3CLOGFILE' + DataFormat IotHubDataFormat `json:"dataFormat,omitempty"` + // EventSystemProperties - System properties of the iot hub + EventSystemProperties *[]string `json:"eventSystemProperties,omitempty"` + // SharedAccessPolicyName - The name of the share access policy + SharedAccessPolicyName *string `json:"sharedAccessPolicyName,omitempty"` + // DatabaseRouting - Indication for database routing information from the data connection, by default only database routing information is allowed. Possible values include: 'DatabaseRoutingSingle', 'DatabaseRoutingMulti' + DatabaseRouting DatabaseRouting `json:"databaseRouting,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` +} + +// MarshalJSON is the custom marshaler for IotHubConnectionProperties. +func (ihcp IotHubConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ihcp.IotHubResourceID != nil { + objectMap["iotHubResourceId"] = ihcp.IotHubResourceID + } + if ihcp.ConsumerGroup != nil { + objectMap["consumerGroup"] = ihcp.ConsumerGroup + } + if ihcp.TableName != nil { + objectMap["tableName"] = ihcp.TableName + } + if ihcp.MappingRuleName != nil { + objectMap["mappingRuleName"] = ihcp.MappingRuleName + } + if ihcp.DataFormat != "" { + objectMap["dataFormat"] = ihcp.DataFormat + } + if ihcp.EventSystemProperties != nil { + objectMap["eventSystemProperties"] = ihcp.EventSystemProperties + } + if ihcp.SharedAccessPolicyName != nil { + objectMap["sharedAccessPolicyName"] = ihcp.SharedAccessPolicyName + } + if ihcp.DatabaseRouting != "" { + objectMap["databaseRouting"] = ihcp.DatabaseRouting + } + return json.Marshal(objectMap) +} + +// IotHubDataConnection class representing an iot hub data connection. +type IotHubDataConnection struct { + // IotHubConnectionProperties - The Iot Hub data connection properties. + *IotHubConnectionProperties `json:"properties,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Kind - Possible values include: 'KindBasicDataConnectionKindDataConnection', 'KindBasicDataConnectionKindEventHub', 'KindBasicDataConnectionKindIotHub', 'KindBasicDataConnectionKindEventGrid' + Kind KindBasicDataConnection `json:"kind,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for IotHubDataConnection. +func (ihdc IotHubDataConnection) MarshalJSON() ([]byte, error) { + ihdc.Kind = KindBasicDataConnectionKindIotHub + objectMap := make(map[string]interface{}) + if ihdc.IotHubConnectionProperties != nil { + objectMap["properties"] = ihdc.IotHubConnectionProperties + } + if ihdc.Location != nil { + objectMap["location"] = ihdc.Location + } + if ihdc.Kind != "" { + objectMap["kind"] = ihdc.Kind + } + return json.Marshal(objectMap) +} + +// AsEventHubDataConnection is the BasicDataConnection implementation for IotHubDataConnection. +func (ihdc IotHubDataConnection) AsEventHubDataConnection() (*EventHubDataConnection, bool) { + return nil, false +} + +// AsIotHubDataConnection is the BasicDataConnection implementation for IotHubDataConnection. +func (ihdc IotHubDataConnection) AsIotHubDataConnection() (*IotHubDataConnection, bool) { + return &ihdc, true +} + +// AsEventGridDataConnection is the BasicDataConnection implementation for IotHubDataConnection. +func (ihdc IotHubDataConnection) AsEventGridDataConnection() (*EventGridDataConnection, bool) { + return nil, false +} + +// AsDataConnection is the BasicDataConnection implementation for IotHubDataConnection. +func (ihdc IotHubDataConnection) AsDataConnection() (*DataConnection, bool) { + return nil, false +} + +// AsBasicDataConnection is the BasicDataConnection implementation for IotHubDataConnection. +func (ihdc IotHubDataConnection) AsBasicDataConnection() (BasicDataConnection, bool) { + return &ihdc, true +} + +// UnmarshalJSON is the custom unmarshaler for IotHubDataConnection struct. +func (ihdc *IotHubDataConnection) 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 iotHubConnectionProperties IotHubConnectionProperties + err = json.Unmarshal(*v, &iotHubConnectionProperties) + if err != nil { + return err + } + ihdc.IotHubConnectionProperties = &iotHubConnectionProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + ihdc.Location = &location + } + case "kind": + if v != nil { + var kind KindBasicDataConnection + err = json.Unmarshal(*v, &kind) + if err != nil { + return err + } + ihdc.Kind = kind + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ihdc.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ihdc.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ihdc.Type = &typeVar + } + } + } + + return nil +} + +// KeyVaultProperties properties of the key vault. +type KeyVaultProperties struct { + // KeyName - The name of the key vault key. + KeyName *string `json:"keyName,omitempty"` + // KeyVersion - The version of the key vault key. + KeyVersion *string `json:"keyVersion,omitempty"` + // KeyVaultURI - The Uri of the key vault. + KeyVaultURI *string `json:"keyVaultUri,omitempty"` + // UserIdentity - The user assigned identity (ARM resource id) that has access to the key. + UserIdentity *string `json:"userIdentity,omitempty"` +} + +// LanguageExtension the language extension object. +type LanguageExtension struct { + // LanguageExtensionName - The language extension name. Possible values include: 'LanguageExtensionNamePYTHON', 'LanguageExtensionNameR' + LanguageExtensionName LanguageExtensionName `json:"languageExtensionName,omitempty"` +} + +// LanguageExtensionsList the list of language extension objects. +type LanguageExtensionsList struct { + autorest.Response `json:"-"` + // Value - The list of language extensions. + Value *[]LanguageExtension `json:"value,omitempty"` +} + +// ListResourceSkusResult list of available SKUs for a Kusto Cluster. +type ListResourceSkusResult struct { + autorest.Response `json:"-"` + // Value - The collection of available SKUs for an existing resource. + Value *[]AzureResourceSku `json:"value,omitempty"` +} + +// ManagedPrivateEndpoint class representing a managed private endpoint. +type ManagedPrivateEndpoint struct { + autorest.Response `json:"-"` + // ManagedPrivateEndpointProperties - A managed private endpoint. + *ManagedPrivateEndpointProperties `json:"properties,omitempty"` + // SystemData - READ-ONLY + SystemData *SystemData `json:"systemData,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ManagedPrivateEndpoint. +func (mpe ManagedPrivateEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if mpe.ManagedPrivateEndpointProperties != nil { + objectMap["properties"] = mpe.ManagedPrivateEndpointProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ManagedPrivateEndpoint struct. +func (mpe *ManagedPrivateEndpoint) 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 managedPrivateEndpointProperties ManagedPrivateEndpointProperties + err = json.Unmarshal(*v, &managedPrivateEndpointProperties) + if err != nil { + return err + } + mpe.ManagedPrivateEndpointProperties = &managedPrivateEndpointProperties + } + case "systemData": + if v != nil { + var systemData SystemData + err = json.Unmarshal(*v, &systemData) + if err != nil { + return err + } + mpe.SystemData = &systemData + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + mpe.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + mpe.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + mpe.Type = &typeVar + } + } + } + + return nil +} + +// ManagedPrivateEndpointListResult the list managed private endpoints operation response. +type ManagedPrivateEndpointListResult struct { + autorest.Response `json:"-"` + // Value - The list of managed private endpoints. + Value *[]ManagedPrivateEndpoint `json:"value,omitempty"` +} + +// ManagedPrivateEndpointProperties a class representing the properties of a managed private endpoint +// object. +type ManagedPrivateEndpointProperties struct { + // PrivateLinkResourceID - The ARM resource ID of the resource for which the managed private endpoint is created. + PrivateLinkResourceID *string `json:"privateLinkResourceId,omitempty"` + // PrivateLinkResourceRegion - The region of the resource to which the managed private endpoint is created. + PrivateLinkResourceRegion *string `json:"privateLinkResourceRegion,omitempty"` + // GroupID - The groupId in which the managed private endpoint is created. + GroupID *string `json:"groupId,omitempty"` + // RequestMessage - The user request message. + RequestMessage *string `json:"requestMessage,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` +} + +// MarshalJSON is the custom marshaler for ManagedPrivateEndpointProperties. +func (mpep ManagedPrivateEndpointProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if mpep.PrivateLinkResourceID != nil { + objectMap["privateLinkResourceId"] = mpep.PrivateLinkResourceID + } + if mpep.PrivateLinkResourceRegion != nil { + objectMap["privateLinkResourceRegion"] = mpep.PrivateLinkResourceRegion + } + if mpep.GroupID != nil { + objectMap["groupId"] = mpep.GroupID + } + if mpep.RequestMessage != nil { + objectMap["requestMessage"] = mpep.RequestMessage + } + return json.Marshal(objectMap) +} + +// ManagedPrivateEndpointsCheckNameRequest the result returned from a managedPrivateEndpoints check name +// availability request. +type ManagedPrivateEndpointsCheckNameRequest struct { + // Name - Managed private endpoint resource name. + Name *string `json:"name,omitempty"` + // Type - The type of resource, for instance Microsoft.Kusto/clusters/managedPrivateEndpoints. + Type *string `json:"type,omitempty"` +} + +// ManagedPrivateEndpointsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of +// a long-running operation. +type ManagedPrivateEndpointsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ManagedPrivateEndpointsClient) (ManagedPrivateEndpoint, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ManagedPrivateEndpointsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ManagedPrivateEndpointsCreateOrUpdateFuture.Result. +func (future *ManagedPrivateEndpointsCreateOrUpdateFuture) result(client ManagedPrivateEndpointsClient) (mpe ManagedPrivateEndpoint, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + mpe.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ManagedPrivateEndpointsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if mpe.Response.Response, err = future.GetResult(sender); err == nil && mpe.Response.Response.StatusCode != http.StatusNoContent { + mpe, err = client.CreateOrUpdateResponder(mpe.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsCreateOrUpdateFuture", "Result", mpe.Response.Response, "Failure responding to request") + } + } + return +} + +// ManagedPrivateEndpointsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ManagedPrivateEndpointsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ManagedPrivateEndpointsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ManagedPrivateEndpointsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ManagedPrivateEndpointsDeleteFuture.Result. +func (future *ManagedPrivateEndpointsDeleteFuture) result(client ManagedPrivateEndpointsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ManagedPrivateEndpointsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ManagedPrivateEndpointsUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ManagedPrivateEndpointsUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ManagedPrivateEndpointsClient) (ManagedPrivateEndpoint, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ManagedPrivateEndpointsUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ManagedPrivateEndpointsUpdateFuture.Result. +func (future *ManagedPrivateEndpointsUpdateFuture) result(client ManagedPrivateEndpointsClient) (mpe ManagedPrivateEndpoint, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + mpe.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ManagedPrivateEndpointsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if mpe.Response.Response, err = future.GetResult(sender); err == nil && mpe.Response.Response.StatusCode != http.StatusNoContent { + mpe, err = client.UpdateResponder(mpe.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsUpdateFuture", "Result", mpe.Response.Response, "Failure responding to request") + } + } + return +} + +// Operation ... +type Operation struct { + // Name - This is of the format {provider}/{resource}/{operation}. + Name *string `json:"name,omitempty"` + Display *OperationDisplay `json:"display,omitempty"` + Origin *string `json:"origin,omitempty"` + Properties interface{} `json:"properties,omitempty"` +} + +// OperationDisplay ... +type OperationDisplay struct { + Provider *string `json:"provider,omitempty"` + // Operation - For example: read, write, delete. + Operation *string `json:"operation,omitempty"` + Resource *string `json:"resource,omitempty"` + Description *string `json:"description,omitempty"` +} + +// OperationListResult ... +type OperationListResult struct { + autorest.Response `json:"-"` + Value *[]Operation `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// OperationListResultIterator provides access to a complete listing of Operation values. +type OperationListResultIterator struct { + i int + page OperationListResultPage +} + +// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *OperationListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// 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] +} + +// Creates a new instance of the OperationListResultIterator type. +func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator { + return OperationListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (olr OperationListResult) IsEmpty() bool { + return olr.Value == nil || len(*olr.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (olr OperationListResult) hasNextLink() bool { + return olr.NextLink != nil && len(*olr.NextLink) != 0 +} + +// operationListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (olr OperationListResult) operationListResultPreparer(ctx context.Context) (*http.Request, error) { + if !olr.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(olr.NextLink))) +} + +// OperationListResultPage contains a page of Operation values. +type OperationListResultPage struct { + fn func(context.Context, OperationListResult) (OperationListResult, error) + olr OperationListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.olr) + if err != nil { + return err + } + page.olr = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *OperationListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// 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 +} + +// Creates a new instance of the OperationListResultPage type. +func NewOperationListResultPage(cur OperationListResult, getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage { + return OperationListResultPage{ + fn: getNextPage, + olr: cur, + } +} + +// OperationResult operation Result Entity. +type OperationResult struct { + autorest.Response `json:"-"` + // ID - READ-ONLY; ID of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource. + Name *string `json:"name,omitempty"` + // Status - status of the Operation result. Possible values include: 'StatusSucceeded', 'StatusCanceled', 'StatusFailed', 'StatusRunning' + Status Status `json:"status,omitempty"` + // StartTime - The operation start time + StartTime *date.Time `json:"startTime,omitempty"` + // EndTime - The operation end time + EndTime *date.Time `json:"endTime,omitempty"` + // PercentComplete - Percentage completed. + PercentComplete *float64 `json:"percentComplete,omitempty"` + // OperationResultProperties - Properties of the operation results + *OperationResultProperties `json:"properties,omitempty"` + // OperationResultErrorProperties - Object that contains the error code and message if the operation failed. + *OperationResultErrorProperties `json:"error,omitempty"` +} + +// MarshalJSON is the custom marshaler for OperationResult. +func (or OperationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if or.Status != "" { + objectMap["status"] = or.Status + } + if or.StartTime != nil { + objectMap["startTime"] = or.StartTime + } + if or.EndTime != nil { + objectMap["endTime"] = or.EndTime + } + if or.PercentComplete != nil { + objectMap["percentComplete"] = or.PercentComplete + } + if or.OperationResultProperties != nil { + objectMap["properties"] = or.OperationResultProperties + } + if or.OperationResultErrorProperties != nil { + objectMap["error"] = or.OperationResultErrorProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for OperationResult struct. +func (or *OperationResult) 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 "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + or.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + or.Name = &name + } + case "status": + if v != nil { + var status Status + err = json.Unmarshal(*v, &status) + if err != nil { + return err + } + or.Status = status + } + case "startTime": + if v != nil { + var startTime date.Time + err = json.Unmarshal(*v, &startTime) + if err != nil { + return err + } + or.StartTime = &startTime + } + case "endTime": + if v != nil { + var endTime date.Time + err = json.Unmarshal(*v, &endTime) + if err != nil { + return err + } + or.EndTime = &endTime + } + case "percentComplete": + if v != nil { + var percentComplete float64 + err = json.Unmarshal(*v, &percentComplete) + if err != nil { + return err + } + or.PercentComplete = &percentComplete + } + case "properties": + if v != nil { + var operationResultProperties OperationResultProperties + err = json.Unmarshal(*v, &operationResultProperties) + if err != nil { + return err + } + or.OperationResultProperties = &operationResultProperties + } + case "error": + if v != nil { + var operationResultErrorProperties OperationResultErrorProperties + err = json.Unmarshal(*v, &operationResultErrorProperties) + if err != nil { + return err + } + or.OperationResultErrorProperties = &operationResultErrorProperties + } + } + } + + return nil +} + +// OperationResultErrorProperties operation result error properties +type OperationResultErrorProperties struct { + // Code - The code of the error. + Code *string `json:"code,omitempty"` + // Message - The error message. + Message *string `json:"message,omitempty"` +} + +// OperationResultProperties operation result properties +type OperationResultProperties struct { + // OperationKind - The kind of the operation. + OperationKind *string `json:"operationKind,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // OperationState - The state of the operation. + OperationState *string `json:"operationState,omitempty"` +} + +// MarshalJSON is the custom marshaler for OperationResultProperties. +func (orp OperationResultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if orp.OperationKind != nil { + objectMap["operationKind"] = orp.OperationKind + } + if orp.OperationState != nil { + objectMap["operationState"] = orp.OperationState + } + return json.Marshal(objectMap) +} + +// OptimizedAutoscale a class that contains the optimized auto scale definition. +type OptimizedAutoscale struct { + // Version - The version of the template defined, for instance 1. + Version *int32 `json:"version,omitempty"` + // IsEnabled - A boolean value that indicate if the optimized autoscale feature is enabled or not. + IsEnabled *bool `json:"isEnabled,omitempty"` + // Minimum - Minimum allowed instances count. + Minimum *int32 `json:"minimum,omitempty"` + // Maximum - Maximum allowed instances count. + Maximum *int32 `json:"maximum,omitempty"` +} + +// OutboundNetworkDependenciesEndpoint endpoints accessed for a common purpose that the Kusto Service +// Environment requires outbound network access to. +type OutboundNetworkDependenciesEndpoint struct { + // OutboundNetworkDependenciesEndpointProperties - The outbound environment endpoint properties. + *OutboundNetworkDependenciesEndpointProperties `json:"properties,omitempty"` + // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. + Etag *string `json:"etag,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for OutboundNetworkDependenciesEndpoint. +func (onde OutboundNetworkDependenciesEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if onde.OutboundNetworkDependenciesEndpointProperties != nil { + objectMap["properties"] = onde.OutboundNetworkDependenciesEndpointProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for OutboundNetworkDependenciesEndpoint struct. +func (onde *OutboundNetworkDependenciesEndpoint) 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 outboundNetworkDependenciesEndpointProperties OutboundNetworkDependenciesEndpointProperties + err = json.Unmarshal(*v, &outboundNetworkDependenciesEndpointProperties) + if err != nil { + return err + } + onde.OutboundNetworkDependenciesEndpointProperties = &outboundNetworkDependenciesEndpointProperties + } + case "etag": + if v != nil { + var etag string + err = json.Unmarshal(*v, &etag) + if err != nil { + return err + } + onde.Etag = &etag + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + onde.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + onde.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + onde.Type = &typeVar + } + } + } + + return nil +} + +// OutboundNetworkDependenciesEndpointListResult collection of Outbound Environment Endpoints +type OutboundNetworkDependenciesEndpointListResult struct { + autorest.Response `json:"-"` + // Value - Collection of resources. + Value *[]OutboundNetworkDependenciesEndpoint `json:"value,omitempty"` + // NextLink - READ-ONLY; Link to next page of resources. + NextLink *string `json:"nextLink,omitempty"` +} + +// MarshalJSON is the custom marshaler for OutboundNetworkDependenciesEndpointListResult. +func (ondelr OutboundNetworkDependenciesEndpointListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ondelr.Value != nil { + objectMap["value"] = ondelr.Value + } + return json.Marshal(objectMap) +} + +// OutboundNetworkDependenciesEndpointListResultIterator provides access to a complete listing of +// OutboundNetworkDependenciesEndpoint values. +type OutboundNetworkDependenciesEndpointListResultIterator struct { + i int + page OutboundNetworkDependenciesEndpointListResultPage +} + +// NextWithContext 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 *OutboundNetworkDependenciesEndpointListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OutboundNetworkDependenciesEndpointListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *OutboundNetworkDependenciesEndpointListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter OutboundNetworkDependenciesEndpointListResultIterator) 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 OutboundNetworkDependenciesEndpointListResultIterator) Response() OutboundNetworkDependenciesEndpointListResult { + 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 OutboundNetworkDependenciesEndpointListResultIterator) Value() OutboundNetworkDependenciesEndpoint { + if !iter.page.NotDone() { + return OutboundNetworkDependenciesEndpoint{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the OutboundNetworkDependenciesEndpointListResultIterator type. +func NewOutboundNetworkDependenciesEndpointListResultIterator(page OutboundNetworkDependenciesEndpointListResultPage) OutboundNetworkDependenciesEndpointListResultIterator { + return OutboundNetworkDependenciesEndpointListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (ondelr OutboundNetworkDependenciesEndpointListResult) IsEmpty() bool { + return ondelr.Value == nil || len(*ondelr.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (ondelr OutboundNetworkDependenciesEndpointListResult) hasNextLink() bool { + return ondelr.NextLink != nil && len(*ondelr.NextLink) != 0 +} + +// outboundNetworkDependenciesEndpointListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ondelr OutboundNetworkDependenciesEndpointListResult) outboundNetworkDependenciesEndpointListResultPreparer(ctx context.Context) (*http.Request, error) { + if !ondelr.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ondelr.NextLink))) +} + +// OutboundNetworkDependenciesEndpointListResultPage contains a page of OutboundNetworkDependenciesEndpoint +// values. +type OutboundNetworkDependenciesEndpointListResultPage struct { + fn func(context.Context, OutboundNetworkDependenciesEndpointListResult) (OutboundNetworkDependenciesEndpointListResult, error) + ondelr OutboundNetworkDependenciesEndpointListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *OutboundNetworkDependenciesEndpointListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OutboundNetworkDependenciesEndpointListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.ondelr) + if err != nil { + return err + } + page.ondelr = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *OutboundNetworkDependenciesEndpointListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page OutboundNetworkDependenciesEndpointListResultPage) NotDone() bool { + return !page.ondelr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page OutboundNetworkDependenciesEndpointListResultPage) Response() OutboundNetworkDependenciesEndpointListResult { + return page.ondelr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page OutboundNetworkDependenciesEndpointListResultPage) Values() []OutboundNetworkDependenciesEndpoint { + if page.ondelr.IsEmpty() { + return nil + } + return *page.ondelr.Value +} + +// Creates a new instance of the OutboundNetworkDependenciesEndpointListResultPage type. +func NewOutboundNetworkDependenciesEndpointListResultPage(cur OutboundNetworkDependenciesEndpointListResult, getNextPage func(context.Context, OutboundNetworkDependenciesEndpointListResult) (OutboundNetworkDependenciesEndpointListResult, error)) OutboundNetworkDependenciesEndpointListResultPage { + return OutboundNetworkDependenciesEndpointListResultPage{ + fn: getNextPage, + ondelr: cur, + } +} + +// OutboundNetworkDependenciesEndpointProperties endpoints accessed for a common purpose that the Kusto +// Service Environment requires outbound network access to. +type OutboundNetworkDependenciesEndpointProperties struct { + // Category - The type of service accessed by the Kusto Service Environment, e.g., Azure Storage, Azure SQL Database, and Azure Active Directory. + Category *string `json:"category,omitempty"` + // Endpoints - The endpoints that the Kusto Service Environment reaches the service at. + Endpoints *[]EndpointDependency `json:"endpoints,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` +} + +// MarshalJSON is the custom marshaler for OutboundNetworkDependenciesEndpointProperties. +func (ondep OutboundNetworkDependenciesEndpointProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ondep.Category != nil { + objectMap["category"] = ondep.Category + } + if ondep.Endpoints != nil { + objectMap["endpoints"] = ondep.Endpoints + } + return json.Marshal(objectMap) +} + +// PrivateEndpointConnection a private endpoint connection +type PrivateEndpointConnection struct { + autorest.Response `json:"-"` + // PrivateEndpointConnectionProperties - Resource properties. + *PrivateEndpointConnectionProperties `json:"properties,omitempty"` + // SystemData - READ-ONLY + SystemData *SystemData `json:"systemData,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for PrivateEndpointConnection. +func (pec PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pec.PrivateEndpointConnectionProperties != nil { + objectMap["properties"] = pec.PrivateEndpointConnectionProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PrivateEndpointConnection struct. +func (pec *PrivateEndpointConnection) 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 privateEndpointConnectionProperties PrivateEndpointConnectionProperties + err = json.Unmarshal(*v, &privateEndpointConnectionProperties) + if err != nil { + return err + } + pec.PrivateEndpointConnectionProperties = &privateEndpointConnectionProperties + } + case "systemData": + if v != nil { + var systemData SystemData + err = json.Unmarshal(*v, &systemData) + if err != nil { + return err + } + pec.SystemData = &systemData + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + pec.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + pec.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + pec.Type = &typeVar + } + } + } + + return nil +} + +// PrivateEndpointConnectionListResult a list of private endpoint connections +type PrivateEndpointConnectionListResult struct { + autorest.Response `json:"-"` + // Value - Array of private endpoint connections + Value *[]PrivateEndpointConnection `json:"value,omitempty"` +} + +// PrivateEndpointConnectionProperties properties of a private endpoint connection. +type PrivateEndpointConnectionProperties struct { + // PrivateEndpoint - READ-ONLY; Private endpoint which the connection belongs to. + PrivateEndpoint *PrivateEndpointProperty `json:"privateEndpoint,omitempty"` + // PrivateLinkServiceConnectionState - Connection State of the Private Endpoint Connection. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionStateProperty `json:"privateLinkServiceConnectionState,omitempty"` + // GroupID - READ-ONLY; Group id of the private endpoint. + GroupID *string `json:"groupId,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the private endpoint. + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// MarshalJSON is the custom marshaler for PrivateEndpointConnectionProperties. +func (pecp PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pecp.PrivateLinkServiceConnectionState != nil { + objectMap["privateLinkServiceConnectionState"] = pecp.PrivateLinkServiceConnectionState + } + return json.Marshal(objectMap) +} + +// PrivateEndpointConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results +// of a long-running operation. +type PrivateEndpointConnectionsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(PrivateEndpointConnectionsClient) (PrivateEndpointConnection, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *PrivateEndpointConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for PrivateEndpointConnectionsCreateOrUpdateFuture.Result. +func (future *PrivateEndpointConnectionsCreateOrUpdateFuture) result(client PrivateEndpointConnectionsClient) (pec PrivateEndpointConnection, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + pec.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.PrivateEndpointConnectionsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if pec.Response.Response, err = future.GetResult(sender); err == nil && pec.Response.Response.StatusCode != http.StatusNoContent { + pec, err = client.CreateOrUpdateResponder(pec.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsCreateOrUpdateFuture", "Result", pec.Response.Response, "Failure responding to request") + } + } + return +} + +// PrivateEndpointConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type PrivateEndpointConnectionsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(PrivateEndpointConnectionsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *PrivateEndpointConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for PrivateEndpointConnectionsDeleteFuture.Result. +func (future *PrivateEndpointConnectionsDeleteFuture) result(client PrivateEndpointConnectionsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.PrivateEndpointConnectionsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// PrivateEndpointProperty private endpoint which the connection belongs to. +type PrivateEndpointProperty struct { + // ID - READ-ONLY; Resource id of the private endpoint. + ID *string `json:"id,omitempty"` +} + +// MarshalJSON is the custom marshaler for PrivateEndpointProperty. +func (pep PrivateEndpointProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// PrivateLinkResource a private link resource +type PrivateLinkResource struct { + autorest.Response `json:"-"` + // PrivateLinkResourceProperties - Resource properties. + *PrivateLinkResourceProperties `json:"properties,omitempty"` + // SystemData - READ-ONLY + SystemData *SystemData `json:"systemData,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for PrivateLinkResource. +func (plr PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if plr.PrivateLinkResourceProperties != nil { + objectMap["properties"] = plr.PrivateLinkResourceProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PrivateLinkResource struct. +func (plr *PrivateLinkResource) 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 privateLinkResourceProperties PrivateLinkResourceProperties + err = json.Unmarshal(*v, &privateLinkResourceProperties) + if err != nil { + return err + } + plr.PrivateLinkResourceProperties = &privateLinkResourceProperties + } + case "systemData": + if v != nil { + var systemData SystemData + err = json.Unmarshal(*v, &systemData) + if err != nil { + return err + } + plr.SystemData = &systemData + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + plr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + plr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + plr.Type = &typeVar + } + } + } + + return nil +} + +// PrivateLinkResourceListResult a list of private link resources +type PrivateLinkResourceListResult struct { + autorest.Response `json:"-"` + // Value - Array of private link resources + Value *[]PrivateLinkResource `json:"value,omitempty"` +} + +// PrivateLinkResourceProperties properties of a private link resource. +type PrivateLinkResourceProperties struct { + // GroupID - READ-ONLY; The private link resource group id. + GroupID *string `json:"groupId,omitempty"` + // RequiredMembers - READ-ONLY; The private link resource required member names. + RequiredMembers *[]string `json:"requiredMembers,omitempty"` + // RequiredZoneNames - READ-ONLY; The private link resource required zone names. + RequiredZoneNames *[]string `json:"requiredZoneNames,omitempty"` +} + +// MarshalJSON is the custom marshaler for PrivateLinkResourceProperties. +func (plrp PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// PrivateLinkServiceConnectionStateProperty connection State of the Private Endpoint Connection. +type PrivateLinkServiceConnectionStateProperty struct { + // Status - The private link service connection status. + Status *string `json:"status,omitempty"` + // Description - The private link service connection description. + Description *string `json:"description,omitempty"` + // ActionsRequired - READ-ONLY; Any action that is required beyond basic workflow (approve/ reject/ disconnect) + ActionsRequired *string `json:"actionsRequired,omitempty"` +} + +// MarshalJSON is the custom marshaler for PrivateLinkServiceConnectionStateProperty. +func (plscsp PrivateLinkServiceConnectionStateProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if plscsp.Status != nil { + objectMap["status"] = plscsp.Status + } + if plscsp.Description != nil { + objectMap["description"] = plscsp.Description + } + return json.Marshal(objectMap) +} + +// ProxyResource the resource model definition for a Azure Resource Manager proxy resource. It will not +// have tags and a location +type ProxyResource struct { + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ProxyResource. +func (pr ProxyResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// ReadOnlyFollowingDatabase class representing a read only following database. +type ReadOnlyFollowingDatabase struct { + // ReadOnlyFollowingDatabaseProperties - The database properties. + *ReadOnlyFollowingDatabaseProperties `json:"properties,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Kind - Possible values include: 'KindDatabase', 'KindReadWrite', 'KindReadOnlyFollowing' + Kind Kind `json:"kind,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ReadOnlyFollowingDatabase. +func (rofd ReadOnlyFollowingDatabase) MarshalJSON() ([]byte, error) { + rofd.Kind = KindReadOnlyFollowing + objectMap := make(map[string]interface{}) + if rofd.ReadOnlyFollowingDatabaseProperties != nil { + objectMap["properties"] = rofd.ReadOnlyFollowingDatabaseProperties + } + if rofd.Location != nil { + objectMap["location"] = rofd.Location + } + if rofd.Kind != "" { + objectMap["kind"] = rofd.Kind + } + return json.Marshal(objectMap) +} + +// AsReadWriteDatabase is the BasicDatabase implementation for ReadOnlyFollowingDatabase. +func (rofd ReadOnlyFollowingDatabase) AsReadWriteDatabase() (*ReadWriteDatabase, bool) { + return nil, false +} + +// AsReadOnlyFollowingDatabase is the BasicDatabase implementation for ReadOnlyFollowingDatabase. +func (rofd ReadOnlyFollowingDatabase) AsReadOnlyFollowingDatabase() (*ReadOnlyFollowingDatabase, bool) { + return &rofd, true +} + +// AsDatabase is the BasicDatabase implementation for ReadOnlyFollowingDatabase. +func (rofd ReadOnlyFollowingDatabase) AsDatabase() (*Database, bool) { + return nil, false +} + +// AsBasicDatabase is the BasicDatabase implementation for ReadOnlyFollowingDatabase. +func (rofd ReadOnlyFollowingDatabase) AsBasicDatabase() (BasicDatabase, bool) { + return &rofd, true +} + +// UnmarshalJSON is the custom unmarshaler for ReadOnlyFollowingDatabase struct. +func (rofd *ReadOnlyFollowingDatabase) 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 readOnlyFollowingDatabaseProperties ReadOnlyFollowingDatabaseProperties + err = json.Unmarshal(*v, &readOnlyFollowingDatabaseProperties) + if err != nil { + return err + } + rofd.ReadOnlyFollowingDatabaseProperties = &readOnlyFollowingDatabaseProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + rofd.Location = &location + } + case "kind": + if v != nil { + var kind Kind + err = json.Unmarshal(*v, &kind) + if err != nil { + return err + } + rofd.Kind = kind + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + rofd.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + rofd.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + rofd.Type = &typeVar + } + } + } + + return nil +} + +// ReadOnlyFollowingDatabaseProperties class representing the Kusto database properties. +type ReadOnlyFollowingDatabaseProperties struct { + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // SoftDeletePeriod - READ-ONLY; The time the data should be kept before it stops being accessible to queries in TimeSpan. + SoftDeletePeriod *string `json:"softDeletePeriod,omitempty"` + // HotCachePeriod - The time the data should be kept in cache for fast queries in TimeSpan. + HotCachePeriod *string `json:"hotCachePeriod,omitempty"` + // Statistics - READ-ONLY; The statistics of the database. + Statistics *DatabaseStatistics `json:"statistics,omitempty"` + // LeaderClusterResourceID - READ-ONLY; The name of the leader cluster + LeaderClusterResourceID *string `json:"leaderClusterResourceId,omitempty"` + // AttachedDatabaseConfigurationName - READ-ONLY; The name of the attached database configuration cluster + AttachedDatabaseConfigurationName *string `json:"attachedDatabaseConfigurationName,omitempty"` + // PrincipalsModificationKind - READ-ONLY; The principals modification kind of the database. Possible values include: 'PrincipalsModificationKindUnion', 'PrincipalsModificationKindReplace', 'PrincipalsModificationKindNone' + PrincipalsModificationKind PrincipalsModificationKind `json:"principalsModificationKind,omitempty"` +} + +// MarshalJSON is the custom marshaler for ReadOnlyFollowingDatabaseProperties. +func (rofdp ReadOnlyFollowingDatabaseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if rofdp.HotCachePeriod != nil { + objectMap["hotCachePeriod"] = rofdp.HotCachePeriod + } + return json.Marshal(objectMap) +} + +// ReadWriteDatabase class representing a read write database. +type ReadWriteDatabase struct { + // ReadWriteDatabaseProperties - The database properties. + *ReadWriteDatabaseProperties `json:"properties,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Kind - Possible values include: 'KindDatabase', 'KindReadWrite', 'KindReadOnlyFollowing' + Kind Kind `json:"kind,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ReadWriteDatabase. +func (rwd ReadWriteDatabase) MarshalJSON() ([]byte, error) { + rwd.Kind = KindReadWrite + objectMap := make(map[string]interface{}) + if rwd.ReadWriteDatabaseProperties != nil { + objectMap["properties"] = rwd.ReadWriteDatabaseProperties + } + if rwd.Location != nil { + objectMap["location"] = rwd.Location + } + if rwd.Kind != "" { + objectMap["kind"] = rwd.Kind + } + return json.Marshal(objectMap) +} + +// AsReadWriteDatabase is the BasicDatabase implementation for ReadWriteDatabase. +func (rwd ReadWriteDatabase) AsReadWriteDatabase() (*ReadWriteDatabase, bool) { + return &rwd, true +} + +// AsReadOnlyFollowingDatabase is the BasicDatabase implementation for ReadWriteDatabase. +func (rwd ReadWriteDatabase) AsReadOnlyFollowingDatabase() (*ReadOnlyFollowingDatabase, bool) { + return nil, false +} + +// AsDatabase is the BasicDatabase implementation for ReadWriteDatabase. +func (rwd ReadWriteDatabase) AsDatabase() (*Database, bool) { + return nil, false +} + +// AsBasicDatabase is the BasicDatabase implementation for ReadWriteDatabase. +func (rwd ReadWriteDatabase) AsBasicDatabase() (BasicDatabase, bool) { + return &rwd, true +} + +// UnmarshalJSON is the custom unmarshaler for ReadWriteDatabase struct. +func (rwd *ReadWriteDatabase) 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 readWriteDatabaseProperties ReadWriteDatabaseProperties + err = json.Unmarshal(*v, &readWriteDatabaseProperties) + if err != nil { + return err + } + rwd.ReadWriteDatabaseProperties = &readWriteDatabaseProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + rwd.Location = &location + } + case "kind": + if v != nil { + var kind Kind + err = json.Unmarshal(*v, &kind) + if err != nil { + return err + } + rwd.Kind = kind + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + rwd.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + rwd.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + rwd.Type = &typeVar + } + } + } + + return nil +} + +// ReadWriteDatabaseProperties class representing the Kusto database properties. +type ReadWriteDatabaseProperties struct { + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // SoftDeletePeriod - The time the data should be kept before it stops being accessible to queries in TimeSpan. + SoftDeletePeriod *string `json:"softDeletePeriod,omitempty"` + // HotCachePeriod - The time the data should be kept in cache for fast queries in TimeSpan. + HotCachePeriod *string `json:"hotCachePeriod,omitempty"` + // Statistics - READ-ONLY; The statistics of the database. + Statistics *DatabaseStatistics `json:"statistics,omitempty"` + // IsFollowed - READ-ONLY; Indicates whether the database is followed. + IsFollowed *bool `json:"isFollowed,omitempty"` +} + +// MarshalJSON is the custom marshaler for ReadWriteDatabaseProperties. +func (rwdp ReadWriteDatabaseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if rwdp.SoftDeletePeriod != nil { + objectMap["softDeletePeriod"] = rwdp.SoftDeletePeriod + } + if rwdp.HotCachePeriod != nil { + objectMap["hotCachePeriod"] = rwdp.HotCachePeriod + } + return json.Marshal(objectMap) +} + +// Resource common fields that are returned in the response for all Azure Resource Manager resources +type Resource struct { + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// Script class representing a database script. +type Script struct { + autorest.Response `json:"-"` + // ScriptProperties - The database script. + *ScriptProperties `json:"properties,omitempty"` + // SystemData - READ-ONLY + SystemData *SystemData `json:"systemData,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Script. +func (s Script) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if s.ScriptProperties != nil { + objectMap["properties"] = s.ScriptProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Script struct. +func (s *Script) 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 scriptProperties ScriptProperties + err = json.Unmarshal(*v, &scriptProperties) + if err != nil { + return err + } + s.ScriptProperties = &scriptProperties + } + case "systemData": + if v != nil { + var systemData SystemData + err = json.Unmarshal(*v, &systemData) + if err != nil { + return err + } + s.SystemData = &systemData + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + s.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + s.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + s.Type = &typeVar + } + } + } + + return nil +} + +// ScriptCheckNameRequest a script name availability request. +type ScriptCheckNameRequest struct { + // Name - Script name. + Name *string `json:"name,omitempty"` + // Type - The type of resource, Microsoft.Kusto/clusters/databases/scripts. + Type *string `json:"type,omitempty"` +} + +// ScriptListResult the list Kusto database script operation response. +type ScriptListResult struct { + autorest.Response `json:"-"` + // Value - The list of Kusto scripts. + Value *[]Script `json:"value,omitempty"` +} + +// ScriptProperties a class representing database script property. +type ScriptProperties struct { + // ScriptURL - The url to the KQL script blob file. Must not be used together with scriptContent property + ScriptURL *string `json:"scriptUrl,omitempty"` + // ScriptURLSasToken - The SaS token that provide read access to the file which contain the script. Must be provided when using scriptUrl property. + ScriptURLSasToken *string `json:"scriptUrlSasToken,omitempty"` + // ScriptContent - The script content. This property should be used when the script is provide inline and not through file in a SA. Must not be used together with scriptUrl and scriptUrlSasToken properties. + ScriptContent *string `json:"scriptContent,omitempty"` + // ForceUpdateTag - A unique string. If changed the script will be applied again. + ForceUpdateTag *string `json:"forceUpdateTag,omitempty"` + // ContinueOnErrors - Flag that indicates whether to continue if one of the command fails. + ContinueOnErrors *bool `json:"continueOnErrors,omitempty"` + // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` +} + +// MarshalJSON is the custom marshaler for ScriptProperties. +func (sp ScriptProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sp.ScriptURL != nil { + objectMap["scriptUrl"] = sp.ScriptURL + } + if sp.ScriptURLSasToken != nil { + objectMap["scriptUrlSasToken"] = sp.ScriptURLSasToken + } + if sp.ScriptContent != nil { + objectMap["scriptContent"] = sp.ScriptContent + } + if sp.ForceUpdateTag != nil { + objectMap["forceUpdateTag"] = sp.ForceUpdateTag + } + if sp.ContinueOnErrors != nil { + objectMap["continueOnErrors"] = sp.ContinueOnErrors + } + return json.Marshal(objectMap) +} + +// ScriptsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ScriptsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ScriptsClient) (Script, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ScriptsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ScriptsCreateOrUpdateFuture.Result. +func (future *ScriptsCreateOrUpdateFuture) result(client ScriptsClient) (s Script, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + s.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ScriptsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { + s, err = client.CreateOrUpdateResponder(s.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsCreateOrUpdateFuture", "Result", s.Response.Response, "Failure responding to request") + } + } + return +} + +// ScriptsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ScriptsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ScriptsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ScriptsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ScriptsDeleteFuture.Result. +func (future *ScriptsDeleteFuture) result(client ScriptsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ScriptsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ScriptsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ScriptsUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ScriptsClient) (Script, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ScriptsUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ScriptsUpdateFuture.Result. +func (future *ScriptsUpdateFuture) result(client ScriptsClient) (s Script, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + s.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("kusto.ScriptsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { + s, err = client.UpdateResponder(s.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsUpdateFuture", "Result", s.Response.Response, "Failure responding to request") + } + } + return +} + +// SkuDescription the Kusto SKU description of given resource type +type SkuDescription struct { + // ResourceType - READ-ONLY; The resource type + ResourceType *string `json:"resourceType,omitempty"` + // Name - READ-ONLY; The name of the SKU + Name *string `json:"name,omitempty"` + // Tier - READ-ONLY; The tier of the SKU + Tier *string `json:"tier,omitempty"` + // Locations - READ-ONLY; The set of locations that the SKU is available + Locations *[]string `json:"locations,omitempty"` + // LocationInfo - READ-ONLY; Locations and zones + LocationInfo *[]SkuLocationInfoItem `json:"locationInfo,omitempty"` + // Restrictions - READ-ONLY; The restrictions because of which SKU cannot be used + Restrictions *[]interface{} `json:"restrictions,omitempty"` +} + +// MarshalJSON is the custom marshaler for SkuDescription. +func (sd SkuDescription) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// SkuDescriptionList the list of the EngagementFabric SKU descriptions +type SkuDescriptionList struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; SKU descriptions + Value *[]SkuDescription `json:"value,omitempty"` +} + +// MarshalJSON is the custom marshaler for SkuDescriptionList. +func (sdl SkuDescriptionList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// SkuLocationInfoItem the locations and zones info for SKU. +type SkuLocationInfoItem struct { + // Location - The available location of the SKU. + Location *string `json:"location,omitempty"` + // Zones - The available zone of the SKU. + Zones *[]string `json:"zones,omitempty"` +} + +// SystemData metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // CreatedBy - The identity that created the resource. + CreatedBy *string `json:"createdBy,omitempty"` + // CreatedByType - The type of identity that created the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' + CreatedByType CreatedByType `json:"createdByType,omitempty"` + // CreatedAt - The timestamp of resource creation (UTC). + CreatedAt *date.Time `json:"createdAt,omitempty"` + // LastModifiedBy - The identity that last modified the resource. + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + // LastModifiedByType - The type of identity that last modified the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' + LastModifiedByType CreatedByType `json:"lastModifiedByType,omitempty"` + // LastModifiedAt - The timestamp of resource last modification (UTC) + LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` +} + +// TableLevelSharingProperties tables that will be included and excluded in the follower database +type TableLevelSharingProperties struct { + // TablesToInclude - List of tables to include in the follower database + TablesToInclude *[]string `json:"tablesToInclude,omitempty"` + // TablesToExclude - List of tables to exclude from the follower database + TablesToExclude *[]string `json:"tablesToExclude,omitempty"` + // ExternalTablesToInclude - List of external tables to include in the follower database + ExternalTablesToInclude *[]string `json:"externalTablesToInclude,omitempty"` + // ExternalTablesToExclude - List of external tables exclude from the follower database + ExternalTablesToExclude *[]string `json:"externalTablesToExclude,omitempty"` + // MaterializedViewsToInclude - List of materialized views to include in the follower database + MaterializedViewsToInclude *[]string `json:"materializedViewsToInclude,omitempty"` + // MaterializedViewsToExclude - List of materialized views exclude from the follower database + MaterializedViewsToExclude *[]string `json:"materializedViewsToExclude,omitempty"` +} + +// TrackedResource the resource model definition for an Azure Resource Manager tracked top level resource +// which has 'tags' and a 'location' +type TrackedResource struct { + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // Location - The geo-location where the resource lives + Location *string `json:"location,omitempty"` + // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + 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.Tags != nil { + objectMap["tags"] = tr.Tags + } + if tr.Location != nil { + objectMap["location"] = tr.Location + } + return json.Marshal(objectMap) +} + +// TrustedExternalTenant represents a tenant ID that is trusted by the cluster. +type TrustedExternalTenant struct { + // Value - GUID representing an external tenant. + Value *string `json:"value,omitempty"` +} + +// VirtualNetworkConfiguration a class that contains virtual network definition. +type VirtualNetworkConfiguration struct { + // SubnetID - The subnet resource id. + SubnetID *string `json:"subnetId,omitempty"` + // EnginePublicIPID - Engine service's public IP address resource id. + EnginePublicIPID *string `json:"enginePublicIpId,omitempty"` + // DataManagementPublicIPID - Data management's service public IP address resource id. + DataManagementPublicIPID *string `json:"dataManagementPublicIpId,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operations.go new file mode 100644 index 000000000000..5b278fc19145 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operations.go @@ -0,0 +1,142 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// OperationsClient is the the Azure Kusto management API provides a RESTful set of web services that interact with +// Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete +// clusters and databases. +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 using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists available operations for the Microsoft.Kusto provider. +func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") + defer func() { + sc := -1 + if result.olr.Response.Response != nil { + sc = result.olr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.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, "kusto.OperationsClient", "List", resp, "Failure sending request") + return + } + + result.olr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.OperationsClient", "List", resp, "Failure responding to request") + return + } + if result.olr.hasNextLink() && result.olr.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.Kusto/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 client.Send(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, + 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(ctx context.Context, lastResults OperationListResult) (result OperationListResult, err error) { + req, err := lastResults.operationListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "kusto.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, "kusto.OperationsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.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) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operationsresults.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operationsresults.go new file mode 100644 index 000000000000..7c02aa4dfe59 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operationsresults.go @@ -0,0 +1,110 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// OperationsResultsClient is the the Azure Kusto management API provides a RESTful set of web services that interact +// with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete +// clusters and databases. +type OperationsResultsClient struct { + BaseClient +} + +// NewOperationsResultsClient creates an instance of the OperationsResultsClient client. +func NewOperationsResultsClient(subscriptionID string) OperationsResultsClient { + return NewOperationsResultsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsResultsClientWithBaseURI creates an instance of the OperationsResultsClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewOperationsResultsClientWithBaseURI(baseURI string, subscriptionID string) OperationsResultsClient { + return OperationsResultsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get returns operation results. +// Parameters: +// location - azure location (region) name. +// operationID - the Guid of the operation ID +func (client OperationsResultsClient) Get(ctx context.Context, location string, operationID string) (result OperationResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsResultsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, location, operationID) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.OperationsResultsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.OperationsResultsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.OperationsResultsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client OperationsResultsClient) GetPreparer(ctx context.Context, location string, operationID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "operationId": autorest.Encode("path", operationID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Kusto/locations/{location}/operationResults/{operationId}", 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 OperationsResultsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client OperationsResultsClient) GetResponder(resp *http.Response) (result OperationResult, err error) { + err = autorest.Respond( + resp, + 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/kusto/mgmt/2022-02-01/kusto/operationsresultslocation.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operationsresultslocation.go new file mode 100644 index 000000000000..5e116cbeb48b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/operationsresultslocation.go @@ -0,0 +1,109 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// OperationsResultsLocationClient is the the Azure Kusto management API provides a RESTful set of web services that +// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and +// delete clusters and databases. +type OperationsResultsLocationClient struct { + BaseClient +} + +// NewOperationsResultsLocationClient creates an instance of the OperationsResultsLocationClient client. +func NewOperationsResultsLocationClient(subscriptionID string) OperationsResultsLocationClient { + return NewOperationsResultsLocationClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsResultsLocationClientWithBaseURI creates an instance of the OperationsResultsLocationClient client +// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign +// clouds, Azure stack). +func NewOperationsResultsLocationClientWithBaseURI(baseURI string, subscriptionID string) OperationsResultsLocationClient { + return OperationsResultsLocationClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get returns operation results. +// Parameters: +// location - azure location (region) name. +// operationID - the Guid of the operation ID +func (client OperationsResultsLocationClient) Get(ctx context.Context, location string, operationID string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsResultsLocationClient.Get") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, location, operationID) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.OperationsResultsLocationClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "kusto.OperationsResultsLocationClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.OperationsResultsLocationClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client OperationsResultsLocationClient) GetPreparer(ctx context.Context, location string, operationID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "operationId": autorest.Encode("path", operationID), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Kusto/locations/{location}/operationResults/{operationId}", 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 OperationsResultsLocationClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client OperationsResultsLocationClient) GetResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/privateendpointconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/privateendpointconnections.go new file mode 100644 index 000000000000..33f54414b236 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/privateendpointconnections.go @@ -0,0 +1,360 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// PrivateEndpointConnectionsClient is the the Azure Kusto management API provides a RESTful set of web services that +// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and +// delete clusters and databases. +type PrivateEndpointConnectionsClient struct { + BaseClient +} + +// NewPrivateEndpointConnectionsClient creates an instance of the PrivateEndpointConnectionsClient client. +func NewPrivateEndpointConnectionsClient(subscriptionID string) PrivateEndpointConnectionsClient { + return NewPrivateEndpointConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPrivateEndpointConnectionsClientWithBaseURI creates an instance of the PrivateEndpointConnectionsClient client +// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign +// clouds, Azure stack). +func NewPrivateEndpointConnectionsClientWithBaseURI(baseURI string, subscriptionID string) PrivateEndpointConnectionsClient { + return PrivateEndpointConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate approve or reject a private endpoint connection with a given name. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// privateEndpointConnectionName - the name of the private endpoint connection. +func (client PrivateEndpointConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string, parameters PrivateEndpointConnection) (result PrivateEndpointConnectionsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.PrivateEndpointConnectionProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PrivateEndpointConnectionProperties.PrivateLinkServiceConnectionState", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("kusto.PrivateEndpointConnectionsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, privateEndpointConnectionName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client PrivateEndpointConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string, parameters PrivateEndpointConnection) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + parameters.SystemData = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) CreateOrUpdateSender(req *http.Request) (future PrivateEndpointConnectionsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client PrivateEndpointConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a private endpoint connection with a given name. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// privateEndpointConnectionName - the name of the private endpoint connection. +func (client PrivateEndpointConnectionsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string) (result PrivateEndpointConnectionsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, privateEndpointConnectionName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PrivateEndpointConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) DeleteSender(req *http.Request) (future PrivateEndpointConnectionsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client PrivateEndpointConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a private endpoint connection. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// privateEndpointConnectionName - the name of the private endpoint connection. +func (client PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string) (result PrivateEndpointConnection, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, privateEndpointConnectionName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client PrivateEndpointConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PrivateEndpointConnectionsClient) GetResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List returns the list of private endpoint connections. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client PrivateEndpointConnectionsClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result PrivateEndpointConnectionListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "List", resp, "Failure responding to request") + return + } + + return +} + +// ListPreparer prepares the List request. +func (client PrivateEndpointConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/privateEndpointConnections", 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 PrivateEndpointConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client PrivateEndpointConnectionsClient) ListResponder(resp *http.Response) (result PrivateEndpointConnectionListResult, err error) { + err = autorest.Respond( + resp, + 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/kusto/mgmt/2022-02-01/kusto/privatelinkresources.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/privatelinkresources.go new file mode 100644 index 000000000000..d964b03a46c4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/privatelinkresources.go @@ -0,0 +1,188 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// PrivateLinkResourcesClient is the the Azure Kusto management API provides a RESTful set of web services that +// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and +// delete clusters and databases. +type PrivateLinkResourcesClient struct { + BaseClient +} + +// NewPrivateLinkResourcesClient creates an instance of the PrivateLinkResourcesClient client. +func NewPrivateLinkResourcesClient(subscriptionID string) PrivateLinkResourcesClient { + return NewPrivateLinkResourcesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPrivateLinkResourcesClientWithBaseURI creates an instance of the PrivateLinkResourcesClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewPrivateLinkResourcesClientWithBaseURI(baseURI string, subscriptionID string) PrivateLinkResourcesClient { + return PrivateLinkResourcesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get gets a private link resource. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// privateLinkResourceName - the name of the private link resource. +func (client PrivateLinkResourcesClient) Get(ctx context.Context, resourceGroupName string, clusterName string, privateLinkResourceName string) (result PrivateLinkResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, privateLinkResourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client PrivateLinkResourcesClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, privateLinkResourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "privateLinkResourceName": autorest.Encode("path", privateLinkResourceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/privateLinkResources/{privateLinkResourceName}", 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 PrivateLinkResourcesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PrivateLinkResourcesClient) GetResponder(resp *http.Response) (result PrivateLinkResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List returns the list of private link resources. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +func (client PrivateLinkResourcesClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result PrivateLinkResourceListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "List", resp, "Failure responding to request") + return + } + + return +} + +// ListPreparer prepares the List request. +func (client PrivateLinkResourcesClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/privateLinkResources", 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 PrivateLinkResourcesClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client PrivateLinkResourcesClient) ListResponder(resp *http.Response) (result PrivateLinkResourceListResult, err error) { + err = autorest.Respond( + resp, + 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/kusto/mgmt/2022-02-01/kusto/scripts.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/scripts.go new file mode 100644 index 000000000000..d9589145b4b7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/scripts.go @@ -0,0 +1,536 @@ +package kusto + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ScriptsClient is the the Azure Kusto management API provides a RESTful set of web services that interact with Azure +// Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and +// databases. +type ScriptsClient struct { + BaseClient +} + +// NewScriptsClient creates an instance of the ScriptsClient client. +func NewScriptsClient(subscriptionID string) ScriptsClient { + return NewScriptsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewScriptsClientWithBaseURI creates an instance of the ScriptsClient client using a custom endpoint. Use this when +// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewScriptsClientWithBaseURI(baseURI string, subscriptionID string) ScriptsClient { + return ScriptsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability checks that the script name is valid and is not already in use. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// scriptName - the name of the script. +func (client ScriptsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName ScriptCheckNameRequest) (result CheckNameResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: scriptName, + Constraints: []validation.Constraint{{Target: "scriptName.Name", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "scriptName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("kusto.ScriptsClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CheckNameAvailability", resp, "Failure responding to request") + return + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client ScriptsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName ScriptCheckNameRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/scriptsCheckNameAvailability", pathParameters), + autorest.WithJSON(scriptName), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client ScriptsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client ScriptsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate creates a Kusto database script. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// scriptName - the name of the Kusto database script. +// parameters - the Kusto Script parameters contains the KQL to run. +func (client ScriptsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string, parameters Script) (result ScriptsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ScriptsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string, parameters Script) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scriptName": autorest.Encode("path", scriptName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + parameters.SystemData = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts/{scriptName}", 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 ScriptsClient) CreateOrUpdateSender(req *http.Request) (future ScriptsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ScriptsClient) CreateOrUpdateResponder(resp *http.Response) (result Script, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a Kusto principalAssignment. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// scriptName - the name of the Kusto database script. +func (client ScriptsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string) (result ScriptsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ScriptsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scriptName": autorest.Encode("path", scriptName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts/{scriptName}", 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 ScriptsClient) DeleteSender(req *http.Request) (future ScriptsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ScriptsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a Kusto cluster database script. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// scriptName - the name of the Kusto database script. +func (client ScriptsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string) (result Script, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client ScriptsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scriptName": autorest.Encode("path", scriptName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts/{scriptName}", 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 ScriptsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ScriptsClient) GetResponder(resp *http.Response) (result Script, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByDatabase returns the list of database scripts for given database. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +func (client ScriptsClient) ListByDatabase(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result ScriptListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.ListByDatabase") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, clusterName, databaseName) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "ListByDatabase", nil, "Failure preparing request") + return + } + + resp, err := client.ListByDatabaseSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "ListByDatabase", resp, "Failure sending request") + return + } + + result, err = client.ListByDatabaseResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "ListByDatabase", resp, "Failure responding to request") + return + } + + return +} + +// ListByDatabasePreparer prepares the ListByDatabase request. +func (client ScriptsClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-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.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByDatabaseSender sends the ListByDatabase request. The method will close the +// http.Response Body if it receives an error. +func (client ScriptsClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByDatabaseResponder handles the response to the ListByDatabase request. The method always +// closes the http.Response Body. +func (client ScriptsClient) ListByDatabaseResponder(resp *http.Response) (result ScriptListResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update updates a database script. +// Parameters: +// resourceGroupName - the name of the resource group containing the Kusto cluster. +// clusterName - the name of the Kusto cluster. +// databaseName - the name of the database in the Kusto cluster. +// scriptName - the name of the Kusto database script. +// parameters - the Kusto Script parameters contains to the KQL to run. +func (client ScriptsClient) Update(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string, parameters Script) (result ScriptsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ScriptsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string, parameters Script) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterName": autorest.Encode("path", clusterName), + "databaseName": autorest.Encode("path", databaseName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "scriptName": autorest.Encode("path", scriptName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + parameters.SystemData = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts/{scriptName}", 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 ScriptsClient) UpdateSender(req *http.Request) (future ScriptsUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ScriptsClient) UpdateResponder(resp *http.Response) (result Script, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, 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/kusto/mgmt/2022-02-01/kusto/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/version.go new file mode 100644 index 000000000000..a436f90cb245 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto/version.go @@ -0,0 +1,19 @@ +package kusto + +import "github.com/Azure/azure-sdk-for-go/version" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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() + " kusto/2022-02-01" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/CHANGELOG.md index 52911e4cc5e4..93fd201bfc3e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/CHANGELOG.md +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/CHANGELOG.md @@ -1,2 +1,9 @@ # Change History +## Additive Changes + +### Struct Changes + +#### New Struct Fields + +1. ApplicationGatewayRoutingRulePropertiesFormat.Priority diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/_meta.json index 0ec66d609829..9b636be005b5 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/_meta.json +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/_meta.json @@ -1,5 +1,5 @@ { - "commit": "50ed15bd61ac79f2368d769df0c207a00b9e099f", + "commit": "a8a52b9e6c305f03c3a4c5411d59fc4454b5b372", "readme": "/_/azure-rest-api-specs/specification/network/resource-manager/readme.md", "tag": "package-2021-08", "use": "@microsoft.azure/autorest.go@2.1.187", diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/client.go index 43ef46f2f709..47c958e96bb1 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/client.go @@ -1,4 +1,4 @@ -// Package network implements the Azure ARM Network service API version . +// Package network implements the Azure ARM Network service API version 2021-08-01. // // Network Client package network diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/interfacesgroup.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/interfacesgroup.go index d7152bb3fd78..2ace149c5a5f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/interfacesgroup.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/interfacesgroup.go @@ -321,7 +321,7 @@ func (client InterfacesClient) GetCloudServiceNetworkInterfacePreparer(ctx conte "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2021-08-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -487,7 +487,7 @@ func (client InterfacesClient) GetVirtualMachineScaleSetIPConfigurationPreparer( "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } - const APIVersion = "2018-10-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -571,7 +571,7 @@ func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfacePreparer "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } - const APIVersion = "2018-10-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -884,7 +884,7 @@ func (client InterfacesClient) ListCloudServiceNetworkInterfacesPreparer(ctx con "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2021-08-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1005,7 +1005,7 @@ func (client InterfacesClient) ListCloudServiceRoleInstanceNetworkInterfacesPrep "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2021-08-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1208,7 +1208,7 @@ func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurationsPrepare "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } - const APIVersion = "2018-10-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1329,7 +1329,7 @@ func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesPrepar "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } - const APIVersion = "2018-10-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1450,7 +1450,7 @@ func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesPrep "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } - const APIVersion = "2018-10-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/models.go index ee35642a9804..fc6475f7f815 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/models.go @@ -4068,6 +4068,8 @@ func (agrr *ApplicationGatewayRoutingRule) UnmarshalJSON(body []byte) error { type ApplicationGatewayRoutingRulePropertiesFormat struct { // RuleType - Rule type. Possible values include: 'ApplicationGatewayRequestRoutingRuleTypeBasic', 'ApplicationGatewayRequestRoutingRuleTypePathBasedRouting' RuleType ApplicationGatewayRequestRoutingRuleType `json:"ruleType,omitempty"` + // Priority - Priority of the routing rule. + Priority *int32 `json:"priority,omitempty"` // BackendAddressPool - Backend address pool resource of the application gateway. BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` // BackendSettings - Backend settings resource of the application gateway. @@ -4084,6 +4086,9 @@ func (agrrpf ApplicationGatewayRoutingRulePropertiesFormat) MarshalJSON() ([]byt if agrrpf.RuleType != "" { objectMap["ruleType"] = agrrpf.RuleType } + if agrrpf.Priority != nil { + objectMap["priority"] = agrrpf.Priority + } if agrrpf.BackendAddressPool != nil { objectMap["backendAddressPool"] = agrrpf.BackendAddressPool } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/publicipaddresses.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/publicipaddresses.go index 952baf08a4c0..6056b28902b1 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/publicipaddresses.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network/publicipaddresses.go @@ -340,7 +340,7 @@ func (client PublicIPAddressesClient) GetCloudServicePublicIPAddressPreparer(ctx "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2021-08-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -428,7 +428,7 @@ func (client PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddressPr "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } - const APIVersion = "2018-10-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -741,7 +741,7 @@ func (client PublicIPAddressesClient) ListCloudServicePublicIPAddressesPreparer( "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2021-08-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -866,7 +866,7 @@ func (client PublicIPAddressesClient) ListCloudServiceRoleInstancePublicIPAddres "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2021-08-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -985,7 +985,7 @@ func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddresse "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } - const APIVersion = "2018-10-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1110,7 +1110,7 @@ func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddres "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } - const APIVersion = "2018-10-01" + const APIVersion = "2017-03-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/CHANGELOG.md new file mode 100644 index 000000000000..52911e4cc5e4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/CHANGELOG.md @@ -0,0 +1,2 @@ +# Change History + diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/_meta.json new file mode 100644 index 000000000000..179e834e9167 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/_meta.json @@ -0,0 +1,11 @@ +{ + "commit": "a8a52b9e6c305f03c3a4c5411d59fc4454b5b372", + "readme": "/_/azure-rest-api-specs/specification/appplatform/resource-manager/readme.md", + "tag": "package-preview-2022-05", + "use": "@microsoft.azure/autorest.go@2.1.187", + "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", + "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-preview-2022-05 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix /_/azure-rest-api-specs/specification/appplatform/resource-manager/readme.md", + "additional_properties": { + "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix" + } +} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apiportalcustomdomains.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apiportalcustomdomains.go new file mode 100644 index 000000000000..7db1905ef2e6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apiportalcustomdomains.go @@ -0,0 +1,404 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// APIPortalCustomDomainsClient is the REST API for Azure Spring Apps +type APIPortalCustomDomainsClient struct { + BaseClient +} + +// NewAPIPortalCustomDomainsClient creates an instance of the APIPortalCustomDomainsClient client. +func NewAPIPortalCustomDomainsClient(subscriptionID string) APIPortalCustomDomainsClient { + return NewAPIPortalCustomDomainsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewAPIPortalCustomDomainsClientWithBaseURI creates an instance of the APIPortalCustomDomainsClient client using a +// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, +// Azure stack). +func NewAPIPortalCustomDomainsClientWithBaseURI(baseURI string, subscriptionID string) APIPortalCustomDomainsClient { + return APIPortalCustomDomainsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or update the API portal custom domain. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// APIPortalName - the name of API portal. +// domainName - the name of the API portal custom domain. +// APIPortalCustomDomainResource - the API portal custom domain for the create or update operation +func (client APIPortalCustomDomainsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string, APIPortalCustomDomainResource APIPortalCustomDomainResource) (result APIPortalCustomDomainsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, APIPortalName, domainName, APIPortalCustomDomainResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client APIPortalCustomDomainsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string, APIPortalCustomDomainResource APIPortalCustomDomainResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "apiPortalName": autorest.Encode("path", APIPortalName), + "domainName": autorest.Encode("path", domainName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/domains/{domainName}", pathParameters), + autorest.WithJSON(APIPortalCustomDomainResource), + 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 APIPortalCustomDomainsClient) CreateOrUpdateSender(req *http.Request) (future APIPortalCustomDomainsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client APIPortalCustomDomainsClient) CreateOrUpdateResponder(resp *http.Response) (result APIPortalCustomDomainResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete the API portal custom domain. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// APIPortalName - the name of API portal. +// domainName - the name of the API portal custom domain. +func (client APIPortalCustomDomainsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string) (result APIPortalCustomDomainsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, APIPortalName, domainName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client APIPortalCustomDomainsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "apiPortalName": autorest.Encode("path", APIPortalName), + "domainName": autorest.Encode("path", domainName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/domains/{domainName}", 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 APIPortalCustomDomainsClient) DeleteSender(req *http.Request) (future APIPortalCustomDomainsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client APIPortalCustomDomainsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the API portal custom domain. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// APIPortalName - the name of API portal. +// domainName - the name of the API portal custom domain. +func (client APIPortalCustomDomainsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string) (result APIPortalCustomDomainResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, APIPortalName, domainName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client APIPortalCustomDomainsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "apiPortalName": autorest.Encode("path", APIPortalName), + "domainName": autorest.Encode("path", domainName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/domains/{domainName}", 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 APIPortalCustomDomainsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client APIPortalCustomDomainsClient) GetResponder(resp *http.Response) (result APIPortalCustomDomainResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handle requests to list all API portal custom domains. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// APIPortalName - the name of API portal. +func (client APIPortalCustomDomainsClient) List(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (result APIPortalCustomDomainResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.List") + defer func() { + sc := -1 + if result.apcdrc.Response.Response != nil { + sc = result.apcdrc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, APIPortalName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.apcdrc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "List", resp, "Failure sending request") + return + } + + result.apcdrc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "List", resp, "Failure responding to request") + return + } + if result.apcdrc.hasNextLink() && result.apcdrc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client APIPortalCustomDomainsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "apiPortalName": autorest.Encode("path", APIPortalName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/domains", 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 APIPortalCustomDomainsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client APIPortalCustomDomainsClient) ListResponder(resp *http.Response) (result APIPortalCustomDomainResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 APIPortalCustomDomainsClient) listNextResults(ctx context.Context, lastResults APIPortalCustomDomainResourceCollection) (result APIPortalCustomDomainResourceCollection, err error) { + req, err := lastResults.aPIPortalCustomDomainResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "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, "appplatform.APIPortalCustomDomainsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client APIPortalCustomDomainsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (result APIPortalCustomDomainResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName, APIPortalName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apiportals.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apiportals.go new file mode 100644 index 000000000000..95fc3eda6bf6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apiportals.go @@ -0,0 +1,484 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// APIPortalsClient is the REST API for Azure Spring Apps +type APIPortalsClient struct { + BaseClient +} + +// NewAPIPortalsClient creates an instance of the APIPortalsClient client. +func NewAPIPortalsClient(subscriptionID string) APIPortalsClient { + return NewAPIPortalsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewAPIPortalsClientWithBaseURI creates an instance of the APIPortalsClient client using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewAPIPortalsClientWithBaseURI(baseURI string, subscriptionID string) APIPortalsClient { + return APIPortalsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create the default API portal or update the existing API portal. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// APIPortalName - the name of API portal. +// APIPortalResource - the API portal for the create or update operation +func (client APIPortalsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, APIPortalResource APIPortalResource) (result APIPortalsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, APIPortalName, APIPortalResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client APIPortalsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, APIPortalResource APIPortalResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "apiPortalName": autorest.Encode("path", APIPortalName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}", pathParameters), + autorest.WithJSON(APIPortalResource), + 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 APIPortalsClient) CreateOrUpdateSender(req *http.Request) (future APIPortalsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client APIPortalsClient) CreateOrUpdateResponder(resp *http.Response) (result APIPortalResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete the default API portal. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// APIPortalName - the name of API portal. +func (client APIPortalsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (result APIPortalsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, APIPortalName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client APIPortalsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "apiPortalName": autorest.Encode("path", APIPortalName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}", 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 APIPortalsClient) DeleteSender(req *http.Request) (future APIPortalsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client APIPortalsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the API portal and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// APIPortalName - the name of API portal. +func (client APIPortalsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (result APIPortalResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, APIPortalName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client APIPortalsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "apiPortalName": autorest.Encode("path", APIPortalName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}", 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 APIPortalsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client APIPortalsClient) GetResponder(resp *http.Response) (result APIPortalResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handles requests to list all resources in a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client APIPortalsClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result APIPortalResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.List") + defer func() { + sc := -1 + if result.aprc.Response.Response != nil { + sc = result.aprc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.aprc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "List", resp, "Failure sending request") + return + } + + result.aprc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "List", resp, "Failure responding to request") + return + } + if result.aprc.hasNextLink() && result.aprc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client APIPortalsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals", 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 APIPortalsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client APIPortalsClient) ListResponder(resp *http.Response) (result APIPortalResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 APIPortalsClient) listNextResults(ctx context.Context, lastResults APIPortalResourceCollection) (result APIPortalResourceCollection, err error) { + req, err := lastResults.aPIPortalResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "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, "appplatform.APIPortalsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client APIPortalsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result APIPortalResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName) + return +} + +// ValidateDomain check the domains are valid as well as not in use. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// APIPortalName - the name of API portal. +// validatePayload - custom domain payload to be validated +func (client APIPortalsClient) ValidateDomain(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, validatePayload CustomDomainValidatePayload) (result CustomDomainValidateResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.ValidateDomain") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: validatePayload, + Constraints: []validation.Constraint{{Target: "validatePayload.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("appplatform.APIPortalsClient", "ValidateDomain", err.Error()) + } + + req, err := client.ValidateDomainPreparer(ctx, resourceGroupName, serviceName, APIPortalName, validatePayload) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "ValidateDomain", nil, "Failure preparing request") + return + } + + resp, err := client.ValidateDomainSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "ValidateDomain", resp, "Failure sending request") + return + } + + result, err = client.ValidateDomainResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "ValidateDomain", resp, "Failure responding to request") + return + } + + return +} + +// ValidateDomainPreparer prepares the ValidateDomain request. +func (client APIPortalsClient) ValidateDomainPreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, validatePayload CustomDomainValidatePayload) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "apiPortalName": autorest.Encode("path", APIPortalName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/validateDomain", pathParameters), + autorest.WithJSON(validatePayload), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ValidateDomainSender sends the ValidateDomain request. The method will close the +// http.Response Body if it receives an error. +func (client APIPortalsClient) ValidateDomainSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ValidateDomainResponder handles the response to the ValidateDomain request. The method always +// closes the http.Response Body. +func (client APIPortalsClient) ValidateDomainResponder(resp *http.Response) (result CustomDomainValidateResult, err error) { + err = autorest.Respond( + resp, + 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apps.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apps.go new file mode 100644 index 000000000000..a0340125baef --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/apps.go @@ -0,0 +1,760 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// AppsClient is the REST API for Azure Spring Apps +type AppsClient struct { + BaseClient +} + +// NewAppsClient creates an instance of the AppsClient client. +func NewAppsClient(subscriptionID string) AppsClient { + return NewAppsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewAppsClientWithBaseURI creates an instance of the AppsClient client using a custom endpoint. Use this when +// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewAppsClientWithBaseURI(baseURI string, subscriptionID string) AppsClient { + return AppsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create a new App or update an exiting App. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// appResource - parameters for the create or update operation +func (client AppsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, appName string, appResource AppResource) (result AppsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: appResource, + Constraints: []validation.Constraint{{Target: "appResource.Properties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "appResource.Properties.TemporaryDisk", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "appResource.Properties.TemporaryDisk.SizeInGB", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "appResource.Properties.TemporaryDisk.SizeInGB", Name: validation.InclusiveMaximum, Rule: int64(5), Chain: nil}, + {Target: "appResource.Properties.TemporaryDisk.SizeInGB", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, + }}, + }}, + {Target: "appResource.Properties.PersistentDisk", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "appResource.Properties.PersistentDisk.SizeInGB", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "appResource.Properties.PersistentDisk.SizeInGB", Name: validation.InclusiveMaximum, Rule: int64(50), Chain: nil}, + {Target: "appResource.Properties.PersistentDisk.SizeInGB", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, + }}, + {Target: "appResource.Properties.PersistentDisk.UsedInGB", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "appResource.Properties.PersistentDisk.UsedInGB", Name: validation.InclusiveMaximum, Rule: int64(50), Chain: nil}, + {Target: "appResource.Properties.PersistentDisk.UsedInGB", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, + }}, + }}, + }}}}}); err != nil { + return result, validation.NewError("appplatform.AppsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, appName, appResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client AppsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, appResource AppResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}", pathParameters), + autorest.WithJSON(appResource), + 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 AppsClient) CreateOrUpdateSender(req *http.Request) (future AppsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client AppsClient) CreateOrUpdateResponder(resp *http.Response) (result AppResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete operation to delete an App. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +func (client AppsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result AppsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, appName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client AppsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}", 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 AppsClient) DeleteSender(req *http.Request) (future AppsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client AppsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get an App and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// syncStatus - indicates whether sync status +func (client AppsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, appName string, syncStatus string) (result AppResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, appName, syncStatus) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client AppsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, syncStatus string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(syncStatus) > 0 { + queryParameters["syncStatus"] = autorest.Encode("query", syncStatus) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}", 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 AppsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client AppsClient) GetResponder(resp *http.Response) (result AppResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetResourceUploadURL get an resource upload URL for an App, which may be artifacts or source archive. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +func (client AppsClient) GetResourceUploadURL(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result ResourceUploadDefinition, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.GetResourceUploadURL") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetResourceUploadURLPreparer(ctx, resourceGroupName, serviceName, appName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "GetResourceUploadURL", nil, "Failure preparing request") + return + } + + resp, err := client.GetResourceUploadURLSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "GetResourceUploadURL", resp, "Failure sending request") + return + } + + result, err = client.GetResourceUploadURLResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "GetResourceUploadURL", resp, "Failure responding to request") + return + } + + return +} + +// GetResourceUploadURLPreparer prepares the GetResourceUploadURL request. +func (client AppsClient) GetResourceUploadURLPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/getResourceUploadUrl", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetResourceUploadURLSender sends the GetResourceUploadURL request. The method will close the +// http.Response Body if it receives an error. +func (client AppsClient) GetResourceUploadURLSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResourceUploadURLResponder handles the response to the GetResourceUploadURL request. The method always +// closes the http.Response Body. +func (client AppsClient) GetResourceUploadURLResponder(resp *http.Response) (result ResourceUploadDefinition, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handles requests to list all resources in a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client AppsClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result AppResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.List") + defer func() { + sc := -1 + if result.arc.Response.Response != nil { + sc = result.arc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.arc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "List", resp, "Failure sending request") + return + } + + result.arc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "List", resp, "Failure responding to request") + return + } + if result.arc.hasNextLink() && result.arc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client AppsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps", 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 AppsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client AppsClient) ListResponder(resp *http.Response) (result AppResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 AppsClient) listNextResults(ctx context.Context, lastResults AppResourceCollection) (result AppResourceCollection, err error) { + req, err := lastResults.appResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.AppsClient", "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, "appplatform.AppsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client AppsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result AppResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName) + return +} + +// SetActiveDeployments set existing Deployment under the app as active +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// activeDeploymentCollection - a list of Deployment name to be active. +func (client AppsClient) SetActiveDeployments(ctx context.Context, resourceGroupName string, serviceName string, appName string, activeDeploymentCollection ActiveDeploymentCollection) (result AppsSetActiveDeploymentsFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.SetActiveDeployments") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.SetActiveDeploymentsPreparer(ctx, resourceGroupName, serviceName, appName, activeDeploymentCollection) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "SetActiveDeployments", nil, "Failure preparing request") + return + } + + result, err = client.SetActiveDeploymentsSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "SetActiveDeployments", result.Response(), "Failure sending request") + return + } + + return +} + +// SetActiveDeploymentsPreparer prepares the SetActiveDeployments request. +func (client AppsClient) SetActiveDeploymentsPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, activeDeploymentCollection ActiveDeploymentCollection) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/setActiveDeployments", pathParameters), + autorest.WithJSON(activeDeploymentCollection), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// SetActiveDeploymentsSender sends the SetActiveDeployments request. The method will close the +// http.Response Body if it receives an error. +func (client AppsClient) SetActiveDeploymentsSender(req *http.Request) (future AppsSetActiveDeploymentsFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// SetActiveDeploymentsResponder handles the response to the SetActiveDeployments request. The method always +// closes the http.Response Body. +func (client AppsClient) SetActiveDeploymentsResponder(resp *http.Response) (result AppResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update operation to update an exiting App. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// appResource - parameters for the update operation +func (client AppsClient) Update(ctx context.Context, resourceGroupName string, serviceName string, appName string, appResource AppResource) (result AppsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, appName, appResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client AppsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, appResource AppResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}", pathParameters), + autorest.WithJSON(appResource), + 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 AppsClient) UpdateSender(req *http.Request) (future AppsUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client AppsClient) UpdateResponder(resp *http.Response) (result AppResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ValidateDomain check the resource name is valid as well as not in use. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// validatePayload - custom domain payload to be validated +func (client AppsClient) ValidateDomain(ctx context.Context, resourceGroupName string, serviceName string, appName string, validatePayload CustomDomainValidatePayload) (result CustomDomainValidateResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.ValidateDomain") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: validatePayload, + Constraints: []validation.Constraint{{Target: "validatePayload.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("appplatform.AppsClient", "ValidateDomain", err.Error()) + } + + req, err := client.ValidateDomainPreparer(ctx, resourceGroupName, serviceName, appName, validatePayload) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "ValidateDomain", nil, "Failure preparing request") + return + } + + resp, err := client.ValidateDomainSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "ValidateDomain", resp, "Failure sending request") + return + } + + result, err = client.ValidateDomainResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "ValidateDomain", resp, "Failure responding to request") + return + } + + return +} + +// ValidateDomainPreparer prepares the ValidateDomain request. +func (client AppsClient) ValidateDomainPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, validatePayload CustomDomainValidatePayload) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/validateDomain", pathParameters), + autorest.WithJSON(validatePayload), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ValidateDomainSender sends the ValidateDomain request. The method will close the +// http.Response Body if it receives an error. +func (client AppsClient) ValidateDomainSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ValidateDomainResponder handles the response to the ValidateDomain request. The method always +// closes the http.Response Body. +func (client AppsClient) ValidateDomainResponder(resp *http.Response) (result CustomDomainValidateResult, err error) { + err = autorest.Respond( + resp, + 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/bindings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/bindings.go new file mode 100644 index 000000000000..9b96c17bf86d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/bindings.go @@ -0,0 +1,490 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// BindingsClient is the REST API for Azure Spring Apps +type BindingsClient struct { + BaseClient +} + +// NewBindingsClient creates an instance of the BindingsClient client. +func NewBindingsClient(subscriptionID string) BindingsClient { + return NewBindingsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewBindingsClientWithBaseURI creates an instance of the BindingsClient client using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewBindingsClientWithBaseURI(baseURI string, subscriptionID string) BindingsClient { + return BindingsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create a new Binding or update an exiting Binding. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// bindingName - the name of the Binding resource. +// bindingResource - parameters for the create or update operation +func (client BindingsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string, bindingResource BindingResource) (result BindingsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, appName, bindingName, bindingResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client BindingsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string, bindingResource BindingResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "bindingName": autorest.Encode("path", bindingName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings/{bindingName}", pathParameters), + autorest.WithJSON(bindingResource), + 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 BindingsClient) CreateOrUpdateSender(req *http.Request) (future BindingsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client BindingsClient) CreateOrUpdateResponder(resp *http.Response) (result BindingResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete operation to delete a Binding. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// bindingName - the name of the Binding resource. +func (client BindingsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string) (result BindingsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, appName, bindingName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client BindingsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "bindingName": autorest.Encode("path", bindingName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings/{bindingName}", 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 BindingsClient) DeleteSender(req *http.Request) (future BindingsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client BindingsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get a Binding and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// bindingName - the name of the Binding resource. +func (client BindingsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string) (result BindingResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, appName, bindingName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client BindingsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "bindingName": autorest.Encode("path", bindingName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings/{bindingName}", 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 BindingsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client BindingsClient) GetResponder(resp *http.Response) (result BindingResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handles requests to list all resources in an App. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +func (client BindingsClient) List(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result BindingResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.List") + defer func() { + sc := -1 + if result.brc.Response.Response != nil { + sc = result.brc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, appName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.brc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "List", resp, "Failure sending request") + return + } + + result.brc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "List", resp, "Failure responding to request") + return + } + if result.brc.hasNextLink() && result.brc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client BindingsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings", 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 BindingsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client BindingsClient) ListResponder(resp *http.Response) (result BindingResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 BindingsClient) listNextResults(ctx context.Context, lastResults BindingResourceCollection) (result BindingResourceCollection, err error) { + req, err := lastResults.bindingResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.BindingsClient", "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, "appplatform.BindingsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client BindingsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result BindingResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName, appName) + return +} + +// Update operation to update an exiting Binding. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// bindingName - the name of the Binding resource. +// bindingResource - parameters for the update operation +func (client BindingsClient) Update(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string, bindingResource BindingResource) (result BindingsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, appName, bindingName, bindingResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client BindingsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string, bindingResource BindingResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "bindingName": autorest.Encode("path", bindingName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings/{bindingName}", pathParameters), + autorest.WithJSON(bindingResource), + 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 BindingsClient) UpdateSender(req *http.Request) (future BindingsUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client BindingsClient) UpdateResponder(resp *http.Response) (result BindingResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildpackbinding.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildpackbinding.go new file mode 100644 index 000000000000..3ec8827e1cef --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildpackbinding.go @@ -0,0 +1,412 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// BuildpackBindingClient is the REST API for Azure Spring Apps +type BuildpackBindingClient struct { + BaseClient +} + +// NewBuildpackBindingClient creates an instance of the BuildpackBindingClient client. +func NewBuildpackBindingClient(subscriptionID string) BuildpackBindingClient { + return NewBuildpackBindingClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewBuildpackBindingClientWithBaseURI creates an instance of the BuildpackBindingClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewBuildpackBindingClientWithBaseURI(baseURI string, subscriptionID string) BuildpackBindingClient { + return BuildpackBindingClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or update a buildpack binding. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// builderName - the name of the builder resource. +// buildpackBindingName - the name of the Buildpack Binding Name +// buildpackBinding - the target buildpack binding for the create or update operation +func (client BuildpackBindingClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string, buildpackBinding BuildpackBindingResource) (result BuildpackBindingCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName, buildpackBindingName, buildpackBinding) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client BuildpackBindingClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string, buildpackBinding BuildpackBindingResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "builderName": autorest.Encode("path", builderName), + "buildpackBindingName": autorest.Encode("path", buildpackBindingName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}/buildpackBindings/{buildpackBindingName}", pathParameters), + autorest.WithJSON(buildpackBinding), + 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 BuildpackBindingClient) CreateOrUpdateSender(req *http.Request) (future BuildpackBindingCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client BuildpackBindingClient) CreateOrUpdateResponder(resp *http.Response) (result BuildpackBindingResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete operation to delete a Buildpack Binding +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// builderName - the name of the builder resource. +// buildpackBindingName - the name of the Buildpack Binding Name +func (client BuildpackBindingClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string) (result BuildpackBindingDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName, buildpackBindingName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client BuildpackBindingClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "builderName": autorest.Encode("path", builderName), + "buildpackBindingName": autorest.Encode("path", buildpackBindingName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}/buildpackBindings/{buildpackBindingName}", 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 BuildpackBindingClient) DeleteSender(req *http.Request) (future BuildpackBindingDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client BuildpackBindingClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get a buildpack binding by name. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// builderName - the name of the builder resource. +// buildpackBindingName - the name of the Buildpack Binding Name +func (client BuildpackBindingClient) Get(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string) (result BuildpackBindingResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName, buildpackBindingName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client BuildpackBindingClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "builderName": autorest.Encode("path", builderName), + "buildpackBindingName": autorest.Encode("path", buildpackBindingName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}/buildpackBindings/{buildpackBindingName}", 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 BuildpackBindingClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client BuildpackBindingClient) GetResponder(resp *http.Response) (result BuildpackBindingResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handles requests to list all buildpack bindings in a builder. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// builderName - the name of the builder resource. +func (client BuildpackBindingClient) List(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (result BuildpackBindingResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.List") + defer func() { + sc := -1 + if result.bbrc.Response.Response != nil { + sc = result.bbrc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.bbrc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "List", resp, "Failure sending request") + return + } + + result.bbrc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "List", resp, "Failure responding to request") + return + } + if result.bbrc.hasNextLink() && result.bbrc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client BuildpackBindingClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "builderName": autorest.Encode("path", builderName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}/buildpackBindings", 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 BuildpackBindingClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client BuildpackBindingClient) ListResponder(resp *http.Response) (result BuildpackBindingResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 BuildpackBindingClient) listNextResults(ctx context.Context, lastResults BuildpackBindingResourceCollection) (result BuildpackBindingResourceCollection, err error) { + req, err := lastResults.buildpackBindingResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "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, "appplatform.BuildpackBindingClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client BuildpackBindingClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (result BuildpackBindingResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName, buildServiceName, builderName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildservice.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildservice.go new file mode 100644 index 000000000000..9df212a46cc5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildservice.go @@ -0,0 +1,1203 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// BuildServiceClient is the REST API for Azure Spring Apps +type BuildServiceClient struct { + BaseClient +} + +// NewBuildServiceClient creates an instance of the BuildServiceClient client. +func NewBuildServiceClient(subscriptionID string) BuildServiceClient { + return NewBuildServiceClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewBuildServiceClientWithBaseURI creates an instance of the BuildServiceClient client using a custom endpoint. Use +// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewBuildServiceClientWithBaseURI(baseURI string, subscriptionID string) BuildServiceClient { + return BuildServiceClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdateBuild create or update a KPack build. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// buildName - the name of the build resource. +// buildParameter - parameters for the create or update operation +func (client BuildServiceClient) CreateOrUpdateBuild(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildParameter Build) (result Build, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.CreateOrUpdateBuild") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdateBuildPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName, buildParameter) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "CreateOrUpdateBuild", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateBuildSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "CreateOrUpdateBuild", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateBuildResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "CreateOrUpdateBuild", resp, "Failure responding to request") + return + } + + return +} + +// CreateOrUpdateBuildPreparer prepares the CreateOrUpdateBuild request. +func (client BuildServiceClient) CreateOrUpdateBuildPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildParameter Build) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildName": autorest.Encode("path", buildName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}", pathParameters), + autorest.WithJSON(buildParameter), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateBuildSender sends the CreateOrUpdateBuild request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) CreateOrUpdateBuildSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateBuildResponder handles the response to the CreateOrUpdateBuild request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) CreateOrUpdateBuildResponder(resp *http.Response) (result Build, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetBuild get a KPack build. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// buildName - the name of the build resource. +func (client BuildServiceClient) GetBuild(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (result Build, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetBuild") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetBuildPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuild", nil, "Failure preparing request") + return + } + + resp, err := client.GetBuildSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuild", resp, "Failure sending request") + return + } + + result, err = client.GetBuildResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuild", resp, "Failure responding to request") + return + } + + return +} + +// GetBuildPreparer prepares the GetBuild request. +func (client BuildServiceClient) GetBuildPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildName": autorest.Encode("path", buildName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetBuildSender sends the GetBuild request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) GetBuildSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetBuildResponder handles the response to the GetBuild request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) GetBuildResponder(resp *http.Response) (result Build, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetBuildResult get a KPack build result. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// buildName - the name of the build resource. +// buildResultName - the name of the build result resource. +func (client BuildServiceClient) GetBuildResult(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildResultName string) (result BuildResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetBuildResult") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetBuildResultPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName, buildResultName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResult", nil, "Failure preparing request") + return + } + + resp, err := client.GetBuildResultSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResult", resp, "Failure sending request") + return + } + + result, err = client.GetBuildResultResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResult", resp, "Failure responding to request") + return + } + + return +} + +// GetBuildResultPreparer prepares the GetBuildResult request. +func (client BuildServiceClient) GetBuildResultPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildResultName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildName": autorest.Encode("path", buildName), + "buildResultName": autorest.Encode("path", buildResultName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}/results/{buildResultName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetBuildResultSender sends the GetBuildResult request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) GetBuildResultSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetBuildResultResponder handles the response to the GetBuildResult request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) GetBuildResultResponder(resp *http.Response) (result BuildResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetBuildResultLog get a KPack build result log download URL. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// buildName - the name of the build resource. +// buildResultName - the name of the build result resource. +func (client BuildServiceClient) GetBuildResultLog(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildResultName string) (result BuildResultLog, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetBuildResultLog") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetBuildResultLogPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName, buildResultName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResultLog", nil, "Failure preparing request") + return + } + + resp, err := client.GetBuildResultLogSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResultLog", resp, "Failure sending request") + return + } + + result, err = client.GetBuildResultLogResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResultLog", resp, "Failure responding to request") + return + } + + return +} + +// GetBuildResultLogPreparer prepares the GetBuildResultLog request. +func (client BuildServiceClient) GetBuildResultLogPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildResultName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildName": autorest.Encode("path", buildName), + "buildResultName": autorest.Encode("path", buildResultName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}/results/{buildResultName}/getLogFileUrl", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetBuildResultLogSender sends the GetBuildResultLog request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) GetBuildResultLogSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetBuildResultLogResponder handles the response to the GetBuildResultLog request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) GetBuildResultLogResponder(resp *http.Response) (result BuildResultLog, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetBuildService get a build service resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +func (client BuildServiceClient) GetBuildService(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildService, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetBuildService") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetBuildServicePreparer(ctx, resourceGroupName, serviceName, buildServiceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildService", nil, "Failure preparing request") + return + } + + resp, err := client.GetBuildServiceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildService", resp, "Failure sending request") + return + } + + result, err = client.GetBuildServiceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildService", resp, "Failure responding to request") + return + } + + return +} + +// GetBuildServicePreparer prepares the GetBuildService request. +func (client BuildServiceClient) GetBuildServicePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetBuildServiceSender sends the GetBuildService request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) GetBuildServiceSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetBuildServiceResponder handles the response to the GetBuildService request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) GetBuildServiceResponder(resp *http.Response) (result BuildService, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetResourceUploadURL get an resource upload URL for build service, which may be artifacts or source archive. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +func (client BuildServiceClient) GetResourceUploadURL(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result ResourceUploadDefinition, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetResourceUploadURL") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetResourceUploadURLPreparer(ctx, resourceGroupName, serviceName, buildServiceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetResourceUploadURL", nil, "Failure preparing request") + return + } + + resp, err := client.GetResourceUploadURLSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetResourceUploadURL", resp, "Failure sending request") + return + } + + result, err = client.GetResourceUploadURLResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetResourceUploadURL", resp, "Failure responding to request") + return + } + + return +} + +// GetResourceUploadURLPreparer prepares the GetResourceUploadURL request. +func (client BuildServiceClient) GetResourceUploadURLPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/getResourceUploadUrl", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetResourceUploadURLSender sends the GetResourceUploadURL request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) GetResourceUploadURLSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResourceUploadURLResponder handles the response to the GetResourceUploadURL request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) GetResourceUploadURLResponder(resp *http.Response) (result ResourceUploadDefinition, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetSupportedBuildpack get the supported buildpack resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// buildpackName - the name of the buildpack resource. +func (client BuildServiceClient) GetSupportedBuildpack(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildpackName string) (result SupportedBuildpackResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetSupportedBuildpack") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetSupportedBuildpackPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildpackName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedBuildpack", nil, "Failure preparing request") + return + } + + resp, err := client.GetSupportedBuildpackSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedBuildpack", resp, "Failure sending request") + return + } + + result, err = client.GetSupportedBuildpackResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedBuildpack", resp, "Failure responding to request") + return + } + + return +} + +// GetSupportedBuildpackPreparer prepares the GetSupportedBuildpack request. +func (client BuildServiceClient) GetSupportedBuildpackPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildpackName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildpackName": autorest.Encode("path", buildpackName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedBuildpacks/{buildpackName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSupportedBuildpackSender sends the GetSupportedBuildpack request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) GetSupportedBuildpackSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetSupportedBuildpackResponder handles the response to the GetSupportedBuildpack request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) GetSupportedBuildpackResponder(resp *http.Response) (result SupportedBuildpackResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetSupportedStack get the supported stack resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// stackName - the name of the stack resource. +func (client BuildServiceClient) GetSupportedStack(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, stackName string) (result SupportedStackResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetSupportedStack") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetSupportedStackPreparer(ctx, resourceGroupName, serviceName, buildServiceName, stackName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedStack", nil, "Failure preparing request") + return + } + + resp, err := client.GetSupportedStackSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedStack", resp, "Failure sending request") + return + } + + result, err = client.GetSupportedStackResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedStack", resp, "Failure responding to request") + return + } + + return +} + +// GetSupportedStackPreparer prepares the GetSupportedStack request. +func (client BuildServiceClient) GetSupportedStackPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, stackName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "stackName": autorest.Encode("path", stackName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedStacks/{stackName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSupportedStackSender sends the GetSupportedStack request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) GetSupportedStackSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetSupportedStackResponder handles the response to the GetSupportedStack request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) GetSupportedStackResponder(resp *http.Response) (result SupportedStackResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListBuildResults list KPack build results. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// buildName - the name of the build resource. +func (client BuildServiceClient) ListBuildResults(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (result BuildResultCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuildResults") + defer func() { + sc := -1 + if result.brc.Response.Response != nil { + sc = result.brc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBuildResultsNextResults + req, err := client.ListBuildResultsPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildResults", nil, "Failure preparing request") + return + } + + resp, err := client.ListBuildResultsSender(req) + if err != nil { + result.brc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildResults", resp, "Failure sending request") + return + } + + result.brc, err = client.ListBuildResultsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildResults", resp, "Failure responding to request") + return + } + if result.brc.hasNextLink() && result.brc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListBuildResultsPreparer prepares the ListBuildResults request. +func (client BuildServiceClient) ListBuildResultsPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildName": autorest.Encode("path", buildName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}/results", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBuildResultsSender sends the ListBuildResults request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) ListBuildResultsSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBuildResultsResponder handles the response to the ListBuildResults request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) ListBuildResultsResponder(resp *http.Response) (result BuildResultCollection, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBuildResultsNextResults retrieves the next set of results, if any. +func (client BuildServiceClient) listBuildResultsNextResults(ctx context.Context, lastResults BuildResultCollection) (result BuildResultCollection, err error) { + req, err := lastResults.buildResultCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildResultsNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBuildResultsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildResultsNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBuildResultsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildResultsNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBuildResultsComplete enumerates all values, automatically crossing page boundaries as required. +func (client BuildServiceClient) ListBuildResultsComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (result BuildResultCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuildResults") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListBuildResults(ctx, resourceGroupName, serviceName, buildServiceName, buildName) + return +} + +// ListBuilds list KPack builds. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +func (client BuildServiceClient) ListBuilds(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuilds") + defer func() { + sc := -1 + if result.bc.Response.Response != nil { + sc = result.bc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBuildsNextResults + req, err := client.ListBuildsPreparer(ctx, resourceGroupName, serviceName, buildServiceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuilds", nil, "Failure preparing request") + return + } + + resp, err := client.ListBuildsSender(req) + if err != nil { + result.bc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuilds", resp, "Failure sending request") + return + } + + result.bc, err = client.ListBuildsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuilds", resp, "Failure responding to request") + return + } + if result.bc.hasNextLink() && result.bc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListBuildsPreparer prepares the ListBuilds request. +func (client BuildServiceClient) ListBuildsPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBuildsSender sends the ListBuilds request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) ListBuildsSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBuildsResponder handles the response to the ListBuilds request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) ListBuildsResponder(resp *http.Response) (result BuildCollection, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBuildsNextResults retrieves the next set of results, if any. +func (client BuildServiceClient) listBuildsNextResults(ctx context.Context, lastResults BuildCollection) (result BuildCollection, err error) { + req, err := lastResults.buildCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildsNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBuildsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildsNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBuildsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildsNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBuildsComplete enumerates all values, automatically crossing page boundaries as required. +func (client BuildServiceClient) ListBuildsComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuilds") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListBuilds(ctx, resourceGroupName, serviceName, buildServiceName) + return +} + +// ListBuildServices list build services resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client BuildServiceClient) ListBuildServices(ctx context.Context, resourceGroupName string, serviceName string) (result BuildServiceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuildServices") + defer func() { + sc := -1 + if result.bsc.Response.Response != nil { + sc = result.bsc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBuildServicesNextResults + req, err := client.ListBuildServicesPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildServices", nil, "Failure preparing request") + return + } + + resp, err := client.ListBuildServicesSender(req) + if err != nil { + result.bsc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildServices", resp, "Failure sending request") + return + } + + result.bsc, err = client.ListBuildServicesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildServices", resp, "Failure responding to request") + return + } + if result.bsc.hasNextLink() && result.bsc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListBuildServicesPreparer prepares the ListBuildServices request. +func (client BuildServiceClient) ListBuildServicesPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBuildServicesSender sends the ListBuildServices request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) ListBuildServicesSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBuildServicesResponder handles the response to the ListBuildServices request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) ListBuildServicesResponder(resp *http.Response) (result BuildServiceCollection, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBuildServicesNextResults retrieves the next set of results, if any. +func (client BuildServiceClient) listBuildServicesNextResults(ctx context.Context, lastResults BuildServiceCollection) (result BuildServiceCollection, err error) { + req, err := lastResults.buildServiceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildServicesNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBuildServicesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildServicesNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBuildServicesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildServicesNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBuildServicesComplete enumerates all values, automatically crossing page boundaries as required. +func (client BuildServiceClient) ListBuildServicesComplete(ctx context.Context, resourceGroupName string, serviceName string) (result BuildServiceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuildServices") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListBuildServices(ctx, resourceGroupName, serviceName) + return +} + +// ListSupportedBuildpacks get all supported buildpacks. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +func (client BuildServiceClient) ListSupportedBuildpacks(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result SupportedBuildpacksCollection, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListSupportedBuildpacks") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListSupportedBuildpacksPreparer(ctx, resourceGroupName, serviceName, buildServiceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedBuildpacks", nil, "Failure preparing request") + return + } + + resp, err := client.ListSupportedBuildpacksSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedBuildpacks", resp, "Failure sending request") + return + } + + result, err = client.ListSupportedBuildpacksResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedBuildpacks", resp, "Failure responding to request") + return + } + + return +} + +// ListSupportedBuildpacksPreparer prepares the ListSupportedBuildpacks request. +func (client BuildServiceClient) ListSupportedBuildpacksPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedBuildpacks", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSupportedBuildpacksSender sends the ListSupportedBuildpacks request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) ListSupportedBuildpacksSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListSupportedBuildpacksResponder handles the response to the ListSupportedBuildpacks request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) ListSupportedBuildpacksResponder(resp *http.Response) (result SupportedBuildpacksCollection, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListSupportedStacks get all supported stacks. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +func (client BuildServiceClient) ListSupportedStacks(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result SupportedStacksCollection, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListSupportedStacks") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListSupportedStacksPreparer(ctx, resourceGroupName, serviceName, buildServiceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedStacks", nil, "Failure preparing request") + return + } + + resp, err := client.ListSupportedStacksSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedStacks", resp, "Failure sending request") + return + } + + result, err = client.ListSupportedStacksResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedStacks", resp, "Failure responding to request") + return + } + + return +} + +// ListSupportedStacksPreparer prepares the ListSupportedStacks request. +func (client BuildServiceClient) ListSupportedStacksPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedStacks", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSupportedStacksSender sends the ListSupportedStacks request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceClient) ListSupportedStacksSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListSupportedStacksResponder handles the response to the ListSupportedStacks request. The method always +// closes the http.Response Body. +func (client BuildServiceClient) ListSupportedStacksResponder(resp *http.Response) (result SupportedStacksCollection, err error) { + err = autorest.Respond( + resp, + 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildserviceagentpool.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildserviceagentpool.go new file mode 100644 index 000000000000..e9ff56445997 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildserviceagentpool.go @@ -0,0 +1,321 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// BuildServiceAgentPoolClient is the REST API for Azure Spring Apps +type BuildServiceAgentPoolClient struct { + BaseClient +} + +// NewBuildServiceAgentPoolClient creates an instance of the BuildServiceAgentPoolClient client. +func NewBuildServiceAgentPoolClient(subscriptionID string) BuildServiceAgentPoolClient { + return NewBuildServiceAgentPoolClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewBuildServiceAgentPoolClientWithBaseURI creates an instance of the BuildServiceAgentPoolClient client using a +// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, +// Azure stack). +func NewBuildServiceAgentPoolClientWithBaseURI(baseURI string, subscriptionID string) BuildServiceAgentPoolClient { + return BuildServiceAgentPoolClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get get build service agent pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// agentPoolName - the name of the build service agent pool resource. +func (client BuildServiceAgentPoolClient) Get(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, agentPoolName string) (result BuildServiceAgentPoolResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, buildServiceName, agentPoolName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client BuildServiceAgentPoolClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, agentPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "agentPoolName": autorest.Encode("path", agentPoolName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/agentPools/{agentPoolName}", 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 BuildServiceAgentPoolClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client BuildServiceAgentPoolClient) GetResponder(resp *http.Response) (result BuildServiceAgentPoolResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List list build service agent pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +func (client BuildServiceAgentPoolClient) List(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildServiceAgentPoolResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolClient.List") + defer func() { + sc := -1 + if result.bsaprc.Response.Response != nil { + sc = result.bsaprc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, buildServiceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.bsaprc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "List", resp, "Failure sending request") + return + } + + result.bsaprc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "List", resp, "Failure responding to request") + return + } + if result.bsaprc.hasNextLink() && result.bsaprc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client BuildServiceAgentPoolClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/agentPools", 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 BuildServiceAgentPoolClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client BuildServiceAgentPoolClient) ListResponder(resp *http.Response) (result BuildServiceAgentPoolResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 BuildServiceAgentPoolClient) listNextResults(ctx context.Context, lastResults BuildServiceAgentPoolResourceCollection) (result BuildServiceAgentPoolResourceCollection, err error) { + req, err := lastResults.buildServiceAgentPoolResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "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, "appplatform.BuildServiceAgentPoolClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client BuildServiceAgentPoolClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildServiceAgentPoolResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName, buildServiceName) + return +} + +// UpdatePut create or update build service agent pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// agentPoolName - the name of the build service agent pool resource. +// agentPoolResource - parameters for the update operation +func (client BuildServiceAgentPoolClient) UpdatePut(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, agentPoolName string, agentPoolResource BuildServiceAgentPoolResource) (result BuildServiceAgentPoolUpdatePutFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolClient.UpdatePut") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePutPreparer(ctx, resourceGroupName, serviceName, buildServiceName, agentPoolName, agentPoolResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "UpdatePut", nil, "Failure preparing request") + return + } + + result, err = client.UpdatePutSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "UpdatePut", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePutPreparer prepares the UpdatePut request. +func (client BuildServiceAgentPoolClient) UpdatePutPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, agentPoolName string, agentPoolResource BuildServiceAgentPoolResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "agentPoolName": autorest.Encode("path", agentPoolName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/agentPools/{agentPoolName}", pathParameters), + autorest.WithJSON(agentPoolResource), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdatePutSender sends the UpdatePut request. The method will close the +// http.Response Body if it receives an error. +func (client BuildServiceAgentPoolClient) UpdatePutSender(req *http.Request) (future BuildServiceAgentPoolUpdatePutFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdatePutResponder handles the response to the UpdatePut request. The method always +// closes the http.Response Body. +func (client BuildServiceAgentPoolClient) UpdatePutResponder(resp *http.Response) (result BuildServiceAgentPoolResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildservicebuilder.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildservicebuilder.go new file mode 100644 index 000000000000..0af93994c57a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/buildservicebuilder.go @@ -0,0 +1,404 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// BuildServiceBuilderClient is the REST API for Azure Spring Apps +type BuildServiceBuilderClient struct { + BaseClient +} + +// NewBuildServiceBuilderClient creates an instance of the BuildServiceBuilderClient client. +func NewBuildServiceBuilderClient(subscriptionID string) BuildServiceBuilderClient { + return NewBuildServiceBuilderClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewBuildServiceBuilderClientWithBaseURI creates an instance of the BuildServiceBuilderClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewBuildServiceBuilderClientWithBaseURI(baseURI string, subscriptionID string) BuildServiceBuilderClient { + return BuildServiceBuilderClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or update a KPack builder. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// builderName - the name of the builder resource. +// builderResource - the target builder for the create or update operation +func (client BuildServiceBuilderClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, builderResource BuilderResource) (result BuildServiceBuilderCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName, builderResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client BuildServiceBuilderClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, builderResource BuilderResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "builderName": autorest.Encode("path", builderName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}", pathParameters), + autorest.WithJSON(builderResource), + 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 BuildServiceBuilderClient) CreateOrUpdateSender(req *http.Request) (future BuildServiceBuilderCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client BuildServiceBuilderClient) CreateOrUpdateResponder(resp *http.Response) (result BuilderResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete a KPack builder. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// builderName - the name of the builder resource. +func (client BuildServiceBuilderClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (result BuildServiceBuilderDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client BuildServiceBuilderClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "builderName": autorest.Encode("path", builderName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}", 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 BuildServiceBuilderClient) DeleteSender(req *http.Request) (future BuildServiceBuilderDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client BuildServiceBuilderClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get a KPack builder. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +// builderName - the name of the builder resource. +func (client BuildServiceBuilderClient) Get(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (result BuilderResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client BuildServiceBuilderClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "builderName": autorest.Encode("path", builderName), + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}", 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 BuildServiceBuilderClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client BuildServiceBuilderClient) GetResponder(resp *http.Response) (result BuilderResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List list KPack builders result. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// buildServiceName - the name of the build service resource. +func (client BuildServiceBuilderClient) List(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuilderResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.List") + defer func() { + sc := -1 + if result.brc.Response.Response != nil { + sc = result.brc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, buildServiceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.brc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "List", resp, "Failure sending request") + return + } + + result.brc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "List", resp, "Failure responding to request") + return + } + if result.brc.hasNextLink() && result.brc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client BuildServiceBuilderClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "buildServiceName": autorest.Encode("path", buildServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders", 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 BuildServiceBuilderClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client BuildServiceBuilderClient) ListResponder(resp *http.Response) (result BuilderResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 BuildServiceBuilderClient) listNextResults(ctx context.Context, lastResults BuilderResourceCollection) (result BuilderResourceCollection, err error) { + req, err := lastResults.builderResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "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, "appplatform.BuildServiceBuilderClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client BuildServiceBuilderClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuilderResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName, buildServiceName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/certificates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/certificates.go new file mode 100644 index 000000000000..28d323fcb2a9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/certificates.go @@ -0,0 +1,395 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// CertificatesClient is the REST API for Azure Spring Apps +type CertificatesClient struct { + BaseClient +} + +// NewCertificatesClient creates an instance of the CertificatesClient client. +func NewCertificatesClient(subscriptionID string) CertificatesClient { + return NewCertificatesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewCertificatesClientWithBaseURI creates an instance of the CertificatesClient client using a custom endpoint. Use +// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewCertificatesClientWithBaseURI(baseURI string, subscriptionID string) CertificatesClient { + return CertificatesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or update certificate resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// certificateName - the name of the certificate resource. +// certificateResource - parameters for the create or update operation +func (client CertificatesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, certificateName string, certificateResource CertificateResource) (result CertificatesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, certificateName, certificateResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client CertificatesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, certificateName string, certificateResource CertificateResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "certificateName": autorest.Encode("path", certificateName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/certificates/{certificateName}", pathParameters), + autorest.WithJSON(certificateResource), + 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 CertificatesClient) CreateOrUpdateSender(req *http.Request) (future CertificatesCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client CertificatesClient) CreateOrUpdateResponder(resp *http.Response) (result CertificateResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete the certificate resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// certificateName - the name of the certificate resource. +func (client CertificatesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, certificateName string) (result CertificatesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, certificateName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client CertificatesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, certificateName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "certificateName": autorest.Encode("path", certificateName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/certificates/{certificateName}", 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 CertificatesClient) DeleteSender(req *http.Request) (future CertificatesDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client CertificatesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the certificate resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// certificateName - the name of the certificate resource. +func (client CertificatesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, certificateName string) (result CertificateResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, certificateName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client CertificatesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, certificateName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "certificateName": autorest.Encode("path", certificateName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/certificates/{certificateName}", 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 CertificatesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client CertificatesClient) GetResponder(resp *http.Response) (result CertificateResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List list all the certificates of one user. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client CertificatesClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result CertificateResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.List") + defer func() { + sc := -1 + if result.crc.Response.Response != nil { + sc = result.crc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.crc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "List", resp, "Failure sending request") + return + } + + result.crc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "List", resp, "Failure responding to request") + return + } + if result.crc.hasNextLink() && result.crc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client CertificatesClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/certificates", 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 CertificatesClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client CertificatesClient) ListResponder(resp *http.Response) (result CertificateResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 CertificatesClient) listNextResults(ctx context.Context, lastResults CertificateResourceCollection) (result CertificateResourceCollection, err error) { + req, err := lastResults.certificateResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "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, "appplatform.CertificatesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client CertificatesClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result CertificateResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/client.go new file mode 100644 index 000000000000..1cea2e3bec92 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/client.go @@ -0,0 +1,41 @@ +// Package appplatform implements the Azure ARM Appplatform service API version 2022-05-01-preview. +// +// REST API for Azure Spring Apps +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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 Appplatform + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Appplatform. +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 using a custom endpoint. Use this when interacting with +// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/configservers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/configservers.go new file mode 100644 index 000000000000..d810a1543abc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/configservers.go @@ -0,0 +1,376 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ConfigServersClient is the REST API for Azure Spring Apps +type ConfigServersClient struct { + BaseClient +} + +// NewConfigServersClient creates an instance of the ConfigServersClient client. +func NewConfigServersClient(subscriptionID string) ConfigServersClient { + return NewConfigServersClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewConfigServersClientWithBaseURI creates an instance of the ConfigServersClient client using a custom endpoint. +// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewConfigServersClientWithBaseURI(baseURI string, subscriptionID string) ConfigServersClient { + return ConfigServersClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get get the config server and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ConfigServersClient) Get(ctx context.Context, resourceGroupName string, serviceName string) (result ConfigServerResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigServersClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client ConfigServersClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configServers/default", 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 ConfigServersClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ConfigServersClient) GetResponder(resp *http.Response) (result ConfigServerResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// UpdatePatch update the config server. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// configServerResource - parameters for the update operation +func (client ConfigServersClient) UpdatePatch(ctx context.Context, resourceGroupName string, serviceName string, configServerResource ConfigServerResource) (result ConfigServersUpdatePatchFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigServersClient.UpdatePatch") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePatchPreparer(ctx, resourceGroupName, serviceName, configServerResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "UpdatePatch", nil, "Failure preparing request") + return + } + + result, err = client.UpdatePatchSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "UpdatePatch", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePatchPreparer prepares the UpdatePatch request. +func (client ConfigServersClient) UpdatePatchPreparer(ctx context.Context, resourceGroupName string, serviceName string, configServerResource ConfigServerResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/configServers/default", pathParameters), + autorest.WithJSON(configServerResource), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdatePatchSender sends the UpdatePatch request. The method will close the +// http.Response Body if it receives an error. +func (client ConfigServersClient) UpdatePatchSender(req *http.Request) (future ConfigServersUpdatePatchFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdatePatchResponder handles the response to the UpdatePatch request. The method always +// closes the http.Response Body. +func (client ConfigServersClient) UpdatePatchResponder(resp *http.Response) (result ConfigServerResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// UpdatePut update the config server. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// configServerResource - parameters for the update operation +func (client ConfigServersClient) UpdatePut(ctx context.Context, resourceGroupName string, serviceName string, configServerResource ConfigServerResource) (result ConfigServersUpdatePutFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigServersClient.UpdatePut") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: configServerResource, + Constraints: []validation.Constraint{{Target: "configServerResource.Properties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "configServerResource.Properties.ConfigServer", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "configServerResource.Properties.ConfigServer.GitProperty", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "configServerResource.Properties.ConfigServer.GitProperty.URI", Name: validation.Null, Rule: true, Chain: nil}}}, + }}, + }}}}}); err != nil { + return result, validation.NewError("appplatform.ConfigServersClient", "UpdatePut", err.Error()) + } + + req, err := client.UpdatePutPreparer(ctx, resourceGroupName, serviceName, configServerResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "UpdatePut", nil, "Failure preparing request") + return + } + + result, err = client.UpdatePutSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "UpdatePut", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePutPreparer prepares the UpdatePut request. +func (client ConfigServersClient) UpdatePutPreparer(ctx context.Context, resourceGroupName string, serviceName string, configServerResource ConfigServerResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/configServers/default", pathParameters), + autorest.WithJSON(configServerResource), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdatePutSender sends the UpdatePut request. The method will close the +// http.Response Body if it receives an error. +func (client ConfigServersClient) UpdatePutSender(req *http.Request) (future ConfigServersUpdatePutFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdatePutResponder handles the response to the UpdatePut request. The method always +// closes the http.Response Body. +func (client ConfigServersClient) UpdatePutResponder(resp *http.Response) (result ConfigServerResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Validate check if the config server settings are valid. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// configServerSettings - config server settings to be validated +func (client ConfigServersClient) Validate(ctx context.Context, resourceGroupName string, serviceName string, configServerSettings ConfigServerSettings) (result ConfigServersValidateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigServersClient.Validate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: configServerSettings, + Constraints: []validation.Constraint{{Target: "configServerSettings.GitProperty", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "configServerSettings.GitProperty.URI", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("appplatform.ConfigServersClient", "Validate", err.Error()) + } + + req, err := client.ValidatePreparer(ctx, resourceGroupName, serviceName, configServerSettings) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Validate", nil, "Failure preparing request") + return + } + + result, err = client.ValidateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Validate", result.Response(), "Failure sending request") + return + } + + return +} + +// ValidatePreparer prepares the Validate request. +func (client ConfigServersClient) ValidatePreparer(ctx context.Context, resourceGroupName string, serviceName string, configServerSettings ConfigServerSettings) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/configServers/validate", pathParameters), + autorest.WithJSON(configServerSettings), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ValidateSender sends the Validate request. The method will close the +// http.Response Body if it receives an error. +func (client ConfigServersClient) ValidateSender(req *http.Request) (future ConfigServersValidateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// ValidateResponder handles the response to the Validate request. The method always +// closes the http.Response Body. +func (client ConfigServersClient) ValidateResponder(resp *http.Response) (result ConfigServerSettingsValidateResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/configurationservices.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/configurationservices.go new file mode 100644 index 000000000000..76e475672863 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/configurationservices.go @@ -0,0 +1,482 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// ConfigurationServicesClient is the REST API for Azure Spring Apps +type ConfigurationServicesClient struct { + BaseClient +} + +// NewConfigurationServicesClient creates an instance of the ConfigurationServicesClient client. +func NewConfigurationServicesClient(subscriptionID string) ConfigurationServicesClient { + return NewConfigurationServicesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewConfigurationServicesClientWithBaseURI creates an instance of the ConfigurationServicesClient client using a +// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, +// Azure stack). +func NewConfigurationServicesClientWithBaseURI(baseURI string, subscriptionID string) ConfigurationServicesClient { + return ConfigurationServicesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create the default Application Configuration Service or update the existing Application Configuration +// Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// configurationServiceName - the name of Application Configuration Service. +// configurationServiceResource - parameters for the update operation +func (client ConfigurationServicesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string, configurationServiceResource ConfigurationServiceResource) (result ConfigurationServicesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, configurationServiceName, configurationServiceResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ConfigurationServicesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string, configurationServiceResource ConfigurationServiceResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "configurationServiceName": autorest.Encode("path", configurationServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}", pathParameters), + autorest.WithJSON(configurationServiceResource), + 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 ConfigurationServicesClient) CreateOrUpdateSender(req *http.Request) (future ConfigurationServicesCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ConfigurationServicesClient) CreateOrUpdateResponder(resp *http.Response) (result ConfigurationServiceResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete disable the default Application Configuration Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// configurationServiceName - the name of Application Configuration Service. +func (client ConfigurationServicesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string) (result ConfigurationServicesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, configurationServiceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ConfigurationServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "configurationServiceName": autorest.Encode("path", configurationServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}", 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 ConfigurationServicesClient) DeleteSender(req *http.Request) (future ConfigurationServicesDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ConfigurationServicesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the Application Configuration Service and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// configurationServiceName - the name of Application Configuration Service. +func (client ConfigurationServicesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string) (result ConfigurationServiceResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, configurationServiceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client ConfigurationServicesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "configurationServiceName": autorest.Encode("path", configurationServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}", 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 ConfigurationServicesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ConfigurationServicesClient) GetResponder(resp *http.Response) (result ConfigurationServiceResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handles requests to list all resources in a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ConfigurationServicesClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result ConfigurationServiceResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.List") + defer func() { + sc := -1 + if result.csrc.Response.Response != nil { + sc = result.csrc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.csrc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "List", resp, "Failure sending request") + return + } + + result.csrc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "List", resp, "Failure responding to request") + return + } + if result.csrc.hasNextLink() && result.csrc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client ConfigurationServicesClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices", 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 ConfigurationServicesClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ConfigurationServicesClient) ListResponder(resp *http.Response) (result ConfigurationServiceResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 ConfigurationServicesClient) listNextResults(ctx context.Context, lastResults ConfigurationServiceResourceCollection) (result ConfigurationServiceResourceCollection, err error) { + req, err := lastResults.configurationServiceResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "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, "appplatform.ConfigurationServicesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ConfigurationServicesClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result ConfigurationServiceResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName) + return +} + +// Validate check if the Application Configuration Service settings are valid. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// configurationServiceName - the name of Application Configuration Service. +// settings - application Configuration Service settings to be validated +func (client ConfigurationServicesClient) Validate(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string, settings ConfigurationServiceSettings) (result ConfigurationServicesValidateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.Validate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ValidatePreparer(ctx, resourceGroupName, serviceName, configurationServiceName, settings) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Validate", nil, "Failure preparing request") + return + } + + result, err = client.ValidateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Validate", result.Response(), "Failure sending request") + return + } + + return +} + +// ValidatePreparer prepares the Validate request. +func (client ConfigurationServicesClient) ValidatePreparer(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string, settings ConfigurationServiceSettings) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "configurationServiceName": autorest.Encode("path", configurationServiceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}/validate", pathParameters), + autorest.WithJSON(settings), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ValidateSender sends the Validate request. The method will close the +// http.Response Body if it receives an error. +func (client ConfigurationServicesClient) ValidateSender(req *http.Request) (future ConfigurationServicesValidateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// ValidateResponder handles the response to the Validate request. The method always +// closes the http.Response Body. +func (client ConfigurationServicesClient) ValidateResponder(resp *http.Response) (result ConfigurationServiceSettingsValidateResult, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/customdomains.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/customdomains.go new file mode 100644 index 000000000000..7f628c6cd739 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/customdomains.go @@ -0,0 +1,490 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// CustomDomainsClient is the REST API for Azure Spring Apps +type CustomDomainsClient struct { + BaseClient +} + +// NewCustomDomainsClient creates an instance of the CustomDomainsClient client. +func NewCustomDomainsClient(subscriptionID string) CustomDomainsClient { + return NewCustomDomainsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewCustomDomainsClientWithBaseURI creates an instance of the CustomDomainsClient client using a custom endpoint. +// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewCustomDomainsClientWithBaseURI(baseURI string, subscriptionID string) CustomDomainsClient { + return CustomDomainsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or update custom domain of one lifecycle application. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// domainName - the name of the custom domain resource. +// domainResource - parameters for the create or update operation +func (client CustomDomainsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string, domainResource CustomDomainResource) (result CustomDomainsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, appName, domainName, domainResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client CustomDomainsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string, domainResource CustomDomainResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "domainName": autorest.Encode("path", domainName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/domains/{domainName}", pathParameters), + autorest.WithJSON(domainResource), + 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 CustomDomainsClient) CreateOrUpdateSender(req *http.Request) (future CustomDomainsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client CustomDomainsClient) CreateOrUpdateResponder(resp *http.Response) (result CustomDomainResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete the custom domain of one lifecycle application. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// domainName - the name of the custom domain resource. +func (client CustomDomainsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string) (result CustomDomainsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, appName, domainName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client CustomDomainsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "domainName": autorest.Encode("path", domainName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/domains/{domainName}", 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 CustomDomainsClient) DeleteSender(req *http.Request) (future CustomDomainsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client CustomDomainsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the custom domain of one lifecycle application. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// domainName - the name of the custom domain resource. +func (client CustomDomainsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string) (result CustomDomainResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, appName, domainName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client CustomDomainsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "domainName": autorest.Encode("path", domainName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/domains/{domainName}", 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 CustomDomainsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client CustomDomainsClient) GetResponder(resp *http.Response) (result CustomDomainResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List list the custom domains of one lifecycle application. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +func (client CustomDomainsClient) List(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result CustomDomainResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.List") + defer func() { + sc := -1 + if result.cdrc.Response.Response != nil { + sc = result.cdrc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, appName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.cdrc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "List", resp, "Failure sending request") + return + } + + result.cdrc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "List", resp, "Failure responding to request") + return + } + if result.cdrc.hasNextLink() && result.cdrc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client CustomDomainsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/domains", 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 CustomDomainsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client CustomDomainsClient) ListResponder(resp *http.Response) (result CustomDomainResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 CustomDomainsClient) listNextResults(ctx context.Context, lastResults CustomDomainResourceCollection) (result CustomDomainResourceCollection, err error) { + req, err := lastResults.customDomainResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "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, "appplatform.CustomDomainsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client CustomDomainsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result CustomDomainResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName, appName) + return +} + +// Update update custom domain of one lifecycle application. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// domainName - the name of the custom domain resource. +// domainResource - parameters for the create or update operation +func (client CustomDomainsClient) Update(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string, domainResource CustomDomainResource) (result CustomDomainsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, appName, domainName, domainResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client CustomDomainsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string, domainResource CustomDomainResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "domainName": autorest.Encode("path", domainName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/domains/{domainName}", pathParameters), + autorest.WithJSON(domainResource), + 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 CustomDomainsClient) UpdateSender(req *http.Request) (future CustomDomainsUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client CustomDomainsClient) UpdateResponder(resp *http.Response) (result CustomDomainResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/deployments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/deployments.go new file mode 100644 index 000000000000..e1a456e48c0e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/deployments.go @@ -0,0 +1,1221 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// DeploymentsClient is the REST API for Azure Spring Apps +type DeploymentsClient struct { + BaseClient +} + +// NewDeploymentsClient creates an instance of the DeploymentsClient client. +func NewDeploymentsClient(subscriptionID string) DeploymentsClient { + return NewDeploymentsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDeploymentsClientWithBaseURI creates an instance of the DeploymentsClient client using a custom endpoint. Use +// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewDeploymentsClientWithBaseURI(baseURI string, subscriptionID string) DeploymentsClient { + return DeploymentsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create a new Deployment or update an exiting Deployment. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +// deploymentResource - parameters for the create or update operation +func (client DeploymentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (result DeploymentsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: deploymentResource, + Constraints: []validation.Constraint{{Target: "deploymentResource.Properties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "deploymentResource.Properties.DeploymentSettings", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "deploymentResource.Properties.DeploymentSettings.LivenessProbe", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "deploymentResource.Properties.DeploymentSettings.LivenessProbe.DisableProbe", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "deploymentResource.Properties.DeploymentSettings.ReadinessProbe", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "deploymentResource.Properties.DeploymentSettings.ReadinessProbe.DisableProbe", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "deploymentResource.Properties.DeploymentSettings.StartupProbe", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "deploymentResource.Properties.DeploymentSettings.StartupProbe.DisableProbe", Name: validation.Null, Rule: true, Chain: nil}}}, + }}, + }}}}}); err != nil { + return result, validation.NewError("appplatform.DeploymentsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, deploymentResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DeploymentsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}", pathParameters), + autorest.WithJSON(deploymentResource), + 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 DeploymentsClient) CreateOrUpdateSender(req *http.Request) (future DeploymentsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) CreateOrUpdateResponder(resp *http.Response) (result DeploymentResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete operation to delete a Deployment. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +func (client DeploymentsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DeploymentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}", 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 DeploymentsClient) DeleteSender(req *http.Request) (future DeploymentsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// GenerateHeapDump generate Heap Dump +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +// diagnosticParameters - parameters for the diagnostic operation +func (client DeploymentsClient) GenerateHeapDump(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (result DeploymentsGenerateHeapDumpFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.GenerateHeapDump") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GenerateHeapDumpPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, diagnosticParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GenerateHeapDump", nil, "Failure preparing request") + return + } + + result, err = client.GenerateHeapDumpSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GenerateHeapDump", result.Response(), "Failure sending request") + return + } + + return +} + +// GenerateHeapDumpPreparer prepares the GenerateHeapDump request. +func (client DeploymentsClient) GenerateHeapDumpPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/generateHeapDump", pathParameters), + autorest.WithJSON(diagnosticParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GenerateHeapDumpSender sends the GenerateHeapDump request. The method will close the +// http.Response Body if it receives an error. +func (client DeploymentsClient) GenerateHeapDumpSender(req *http.Request) (future DeploymentsGenerateHeapDumpFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// GenerateHeapDumpResponder handles the response to the GenerateHeapDump request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) GenerateHeapDumpResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// GenerateThreadDump generate Thread Dump +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +// diagnosticParameters - parameters for the diagnostic operation +func (client DeploymentsClient) GenerateThreadDump(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (result DeploymentsGenerateThreadDumpFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.GenerateThreadDump") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GenerateThreadDumpPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, diagnosticParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GenerateThreadDump", nil, "Failure preparing request") + return + } + + result, err = client.GenerateThreadDumpSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GenerateThreadDump", result.Response(), "Failure sending request") + return + } + + return +} + +// GenerateThreadDumpPreparer prepares the GenerateThreadDump request. +func (client DeploymentsClient) GenerateThreadDumpPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/generateThreadDump", pathParameters), + autorest.WithJSON(diagnosticParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GenerateThreadDumpSender sends the GenerateThreadDump request. The method will close the +// http.Response Body if it receives an error. +func (client DeploymentsClient) GenerateThreadDumpSender(req *http.Request) (future DeploymentsGenerateThreadDumpFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// GenerateThreadDumpResponder handles the response to the GenerateThreadDump request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) GenerateThreadDumpResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get a Deployment and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +func (client DeploymentsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client DeploymentsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}", 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 DeploymentsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) GetResponder(resp *http.Response) (result DeploymentResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetLogFileURL get deployment log file URL +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +func (client DeploymentsClient) GetLogFileURL(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result LogFileURLResponse, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.GetLogFileURL") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetLogFileURLPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GetLogFileURL", nil, "Failure preparing request") + return + } + + resp, err := client.GetLogFileURLSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GetLogFileURL", resp, "Failure sending request") + return + } + + result, err = client.GetLogFileURLResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GetLogFileURL", resp, "Failure responding to request") + return + } + + return +} + +// GetLogFileURLPreparer prepares the GetLogFileURL request. +func (client DeploymentsClient) GetLogFileURLPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/getLogFileUrl", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetLogFileURLSender sends the GetLogFileURL request. The method will close the +// http.Response Body if it receives an error. +func (client DeploymentsClient) GetLogFileURLSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetLogFileURLResponder handles the response to the GetLogFileURL request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) GetLogFileURLResponder(resp *http.Response) (result LogFileURLResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handles requests to list all resources in an App. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// version - version of the deployments to be listed +func (client DeploymentsClient) List(ctx context.Context, resourceGroupName string, serviceName string, appName string, version []string) (result DeploymentResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.List") + defer func() { + sc := -1 + if result.drc.Response.Response != nil { + sc = result.drc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, appName, version) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.drc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "List", resp, "Failure sending request") + return + } + + result.drc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "List", resp, "Failure responding to request") + return + } + if result.drc.hasNextLink() && result.drc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client DeploymentsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, version []string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if version != nil && len(version) > 0 { + queryParameters["version"] = version + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments", 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 DeploymentsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) ListResponder(resp *http.Response) (result DeploymentResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 DeploymentsClient) listNextResults(ctx context.Context, lastResults DeploymentResourceCollection) (result DeploymentResourceCollection, err error) { + req, err := lastResults.deploymentResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "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, "appplatform.DeploymentsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client DeploymentsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, appName string, version []string) (result DeploymentResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName, appName, version) + return +} + +// ListForCluster list deployments for a certain service +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// version - version of the deployments to be listed +func (client DeploymentsClient) ListForCluster(ctx context.Context, resourceGroupName string, serviceName string, version []string) (result DeploymentResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.ListForCluster") + defer func() { + sc := -1 + if result.drc.Response.Response != nil { + sc = result.drc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listForClusterNextResults + req, err := client.ListForClusterPreparer(ctx, resourceGroupName, serviceName, version) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "ListForCluster", nil, "Failure preparing request") + return + } + + resp, err := client.ListForClusterSender(req) + if err != nil { + result.drc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "ListForCluster", resp, "Failure sending request") + return + } + + result.drc, err = client.ListForClusterResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "ListForCluster", resp, "Failure responding to request") + return + } + if result.drc.hasNextLink() && result.drc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListForClusterPreparer prepares the ListForCluster request. +func (client DeploymentsClient) ListForClusterPreparer(ctx context.Context, resourceGroupName string, serviceName string, version []string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if version != nil && len(version) > 0 { + queryParameters["version"] = version + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/deployments", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListForClusterSender sends the ListForCluster request. The method will close the +// http.Response Body if it receives an error. +func (client DeploymentsClient) ListForClusterSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListForClusterResponder handles the response to the ListForCluster request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) ListForClusterResponder(resp *http.Response) (result DeploymentResourceCollection, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listForClusterNextResults retrieves the next set of results, if any. +func (client DeploymentsClient) listForClusterNextResults(ctx context.Context, lastResults DeploymentResourceCollection) (result DeploymentResourceCollection, err error) { + req, err := lastResults.deploymentResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "listForClusterNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListForClusterSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "listForClusterNextResults", resp, "Failure sending next results request") + } + result, err = client.ListForClusterResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "listForClusterNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListForClusterComplete enumerates all values, automatically crossing page boundaries as required. +func (client DeploymentsClient) ListForClusterComplete(ctx context.Context, resourceGroupName string, serviceName string, version []string) (result DeploymentResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.ListForCluster") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListForCluster(ctx, resourceGroupName, serviceName, version) + return +} + +// Restart restart the deployment. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +func (client DeploymentsClient) Restart(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentsRestartFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Restart") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RestartPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Restart", nil, "Failure preparing request") + return + } + + result, err = client.RestartSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Restart", result.Response(), "Failure sending request") + return + } + + return +} + +// RestartPreparer prepares the Restart request. +func (client DeploymentsClient) RestartPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/restart", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RestartSender sends the Restart request. The method will close the +// http.Response Body if it receives an error. +func (client DeploymentsClient) RestartSender(req *http.Request) (future DeploymentsRestartFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// RestartResponder handles the response to the Restart request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Start start the deployment. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +func (client DeploymentsClient) Start(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentsStartFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Start") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StartPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Start", nil, "Failure preparing request") + return + } + + result, err = client.StartSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Start", result.Response(), "Failure sending request") + return + } + + return +} + +// StartPreparer prepares the Start request. +func (client DeploymentsClient) StartPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/start", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StartSender sends the Start request. The method will close the +// http.Response Body if it receives an error. +func (client DeploymentsClient) StartSender(req *http.Request) (future DeploymentsStartFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// StartResponder handles the response to the Start request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// StartJFR start JFR +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +// diagnosticParameters - parameters for the diagnostic operation +func (client DeploymentsClient) StartJFR(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (result DeploymentsStartJFRFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.StartJFR") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StartJFRPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, diagnosticParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "StartJFR", nil, "Failure preparing request") + return + } + + result, err = client.StartJFRSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "StartJFR", result.Response(), "Failure sending request") + return + } + + return +} + +// StartJFRPreparer prepares the StartJFR request. +func (client DeploymentsClient) StartJFRPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/startJFR", pathParameters), + autorest.WithJSON(diagnosticParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StartJFRSender sends the StartJFR request. The method will close the +// http.Response Body if it receives an error. +func (client DeploymentsClient) StartJFRSender(req *http.Request) (future DeploymentsStartJFRFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// StartJFRResponder handles the response to the StartJFR request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) StartJFRResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Stop stop the deployment. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +func (client DeploymentsClient) Stop(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentsStopFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Stop") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StopPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Stop", nil, "Failure preparing request") + return + } + + result, err = client.StopSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Stop", result.Response(), "Failure sending request") + return + } + + return +} + +// StopPreparer prepares the Stop request. +func (client DeploymentsClient) StopPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/stop", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StopSender sends the Stop request. The method will close the +// http.Response Body if it receives an error. +func (client DeploymentsClient) StopSender(req *http.Request) (future DeploymentsStopFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// StopResponder handles the response to the Stop request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update operation to update an exiting Deployment. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// appName - the name of the App resource. +// deploymentName - the name of the Deployment resource. +// deploymentResource - parameters for the update operation +func (client DeploymentsClient) Update(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (result DeploymentsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, deploymentResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client DeploymentsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "appName": autorest.Encode("path", appName), + "deploymentName": autorest.Encode("path", deploymentName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}", pathParameters), + autorest.WithJSON(deploymentResource), + 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 DeploymentsClient) UpdateSender(req *http.Request) (future DeploymentsUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client DeploymentsClient) UpdateResponder(resp *http.Response) (result DeploymentResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/enums.go new file mode 100644 index 000000000000..2408ff5bec74 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/enums.go @@ -0,0 +1,710 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// ActionType enumerates the values for action type. +type ActionType string + +const ( + // ActionTypeInternal ... + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns an array of possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ActionTypeInternal} +} + +// APIPortalProvisioningState enumerates the values for api portal provisioning state. +type APIPortalProvisioningState string + +const ( + // APIPortalProvisioningStateCreating ... + APIPortalProvisioningStateCreating APIPortalProvisioningState = "Creating" + // APIPortalProvisioningStateDeleting ... + APIPortalProvisioningStateDeleting APIPortalProvisioningState = "Deleting" + // APIPortalProvisioningStateFailed ... + APIPortalProvisioningStateFailed APIPortalProvisioningState = "Failed" + // APIPortalProvisioningStateSucceeded ... + APIPortalProvisioningStateSucceeded APIPortalProvisioningState = "Succeeded" + // APIPortalProvisioningStateUpdating ... + APIPortalProvisioningStateUpdating APIPortalProvisioningState = "Updating" +) + +// PossibleAPIPortalProvisioningStateValues returns an array of possible values for the APIPortalProvisioningState const type. +func PossibleAPIPortalProvisioningStateValues() []APIPortalProvisioningState { + return []APIPortalProvisioningState{APIPortalProvisioningStateCreating, APIPortalProvisioningStateDeleting, APIPortalProvisioningStateFailed, APIPortalProvisioningStateSucceeded, APIPortalProvisioningStateUpdating} +} + +// AppResourceProvisioningState enumerates the values for app resource provisioning state. +type AppResourceProvisioningState string + +const ( + // AppResourceProvisioningStateCreating ... + AppResourceProvisioningStateCreating AppResourceProvisioningState = "Creating" + // AppResourceProvisioningStateDeleting ... + AppResourceProvisioningStateDeleting AppResourceProvisioningState = "Deleting" + // AppResourceProvisioningStateFailed ... + AppResourceProvisioningStateFailed AppResourceProvisioningState = "Failed" + // AppResourceProvisioningStateSucceeded ... + AppResourceProvisioningStateSucceeded AppResourceProvisioningState = "Succeeded" + // AppResourceProvisioningStateUpdating ... + AppResourceProvisioningStateUpdating AppResourceProvisioningState = "Updating" +) + +// PossibleAppResourceProvisioningStateValues returns an array of possible values for the AppResourceProvisioningState const type. +func PossibleAppResourceProvisioningStateValues() []AppResourceProvisioningState { + return []AppResourceProvisioningState{AppResourceProvisioningStateCreating, AppResourceProvisioningStateDeleting, AppResourceProvisioningStateFailed, AppResourceProvisioningStateSucceeded, AppResourceProvisioningStateUpdating} +} + +// BindingType enumerates the values for binding type. +type BindingType string + +const ( + // BindingTypeApacheSkyWalking ... + BindingTypeApacheSkyWalking BindingType = "ApacheSkyWalking" + // BindingTypeAppDynamics ... + BindingTypeAppDynamics BindingType = "AppDynamics" + // BindingTypeApplicationInsights ... + BindingTypeApplicationInsights BindingType = "ApplicationInsights" + // BindingTypeDynatrace ... + BindingTypeDynatrace BindingType = "Dynatrace" + // BindingTypeElasticAPM ... + BindingTypeElasticAPM BindingType = "ElasticAPM" + // BindingTypeNewRelic ... + BindingTypeNewRelic BindingType = "NewRelic" +) + +// PossibleBindingTypeValues returns an array of possible values for the BindingType const type. +func PossibleBindingTypeValues() []BindingType { + return []BindingType{BindingTypeApacheSkyWalking, BindingTypeAppDynamics, BindingTypeApplicationInsights, BindingTypeDynatrace, BindingTypeElasticAPM, BindingTypeNewRelic} +} + +// BuilderProvisioningState enumerates the values for builder provisioning state. +type BuilderProvisioningState string + +const ( + // BuilderProvisioningStateCreating ... + BuilderProvisioningStateCreating BuilderProvisioningState = "Creating" + // BuilderProvisioningStateDeleting ... + BuilderProvisioningStateDeleting BuilderProvisioningState = "Deleting" + // BuilderProvisioningStateFailed ... + BuilderProvisioningStateFailed BuilderProvisioningState = "Failed" + // BuilderProvisioningStateSucceeded ... + BuilderProvisioningStateSucceeded BuilderProvisioningState = "Succeeded" + // BuilderProvisioningStateUpdating ... + BuilderProvisioningStateUpdating BuilderProvisioningState = "Updating" +) + +// PossibleBuilderProvisioningStateValues returns an array of possible values for the BuilderProvisioningState const type. +func PossibleBuilderProvisioningStateValues() []BuilderProvisioningState { + return []BuilderProvisioningState{BuilderProvisioningStateCreating, BuilderProvisioningStateDeleting, BuilderProvisioningStateFailed, BuilderProvisioningStateSucceeded, BuilderProvisioningStateUpdating} +} + +// BuildpackBindingProvisioningState enumerates the values for buildpack binding provisioning state. +type BuildpackBindingProvisioningState string + +const ( + // BuildpackBindingProvisioningStateCreating ... + BuildpackBindingProvisioningStateCreating BuildpackBindingProvisioningState = "Creating" + // BuildpackBindingProvisioningStateDeleting ... + BuildpackBindingProvisioningStateDeleting BuildpackBindingProvisioningState = "Deleting" + // BuildpackBindingProvisioningStateFailed ... + BuildpackBindingProvisioningStateFailed BuildpackBindingProvisioningState = "Failed" + // BuildpackBindingProvisioningStateSucceeded ... + BuildpackBindingProvisioningStateSucceeded BuildpackBindingProvisioningState = "Succeeded" + // BuildpackBindingProvisioningStateUpdating ... + BuildpackBindingProvisioningStateUpdating BuildpackBindingProvisioningState = "Updating" +) + +// PossibleBuildpackBindingProvisioningStateValues returns an array of possible values for the BuildpackBindingProvisioningState const type. +func PossibleBuildpackBindingProvisioningStateValues() []BuildpackBindingProvisioningState { + return []BuildpackBindingProvisioningState{BuildpackBindingProvisioningStateCreating, BuildpackBindingProvisioningStateDeleting, BuildpackBindingProvisioningStateFailed, BuildpackBindingProvisioningStateSucceeded, BuildpackBindingProvisioningStateUpdating} +} + +// BuildProvisioningState enumerates the values for build provisioning state. +type BuildProvisioningState string + +const ( + // BuildProvisioningStateCreating ... + BuildProvisioningStateCreating BuildProvisioningState = "Creating" + // BuildProvisioningStateDeleting ... + BuildProvisioningStateDeleting BuildProvisioningState = "Deleting" + // BuildProvisioningStateFailed ... + BuildProvisioningStateFailed BuildProvisioningState = "Failed" + // BuildProvisioningStateSucceeded ... + BuildProvisioningStateSucceeded BuildProvisioningState = "Succeeded" + // BuildProvisioningStateUpdating ... + BuildProvisioningStateUpdating BuildProvisioningState = "Updating" +) + +// PossibleBuildProvisioningStateValues returns an array of possible values for the BuildProvisioningState const type. +func PossibleBuildProvisioningStateValues() []BuildProvisioningState { + return []BuildProvisioningState{BuildProvisioningStateCreating, BuildProvisioningStateDeleting, BuildProvisioningStateFailed, BuildProvisioningStateSucceeded, BuildProvisioningStateUpdating} +} + +// BuildResultProvisioningState enumerates the values for build result provisioning state. +type BuildResultProvisioningState string + +const ( + // BuildResultProvisioningStateBuilding ... + BuildResultProvisioningStateBuilding BuildResultProvisioningState = "Building" + // BuildResultProvisioningStateDeleting ... + BuildResultProvisioningStateDeleting BuildResultProvisioningState = "Deleting" + // BuildResultProvisioningStateFailed ... + BuildResultProvisioningStateFailed BuildResultProvisioningState = "Failed" + // BuildResultProvisioningStateQueuing ... + BuildResultProvisioningStateQueuing BuildResultProvisioningState = "Queuing" + // BuildResultProvisioningStateSucceeded ... + BuildResultProvisioningStateSucceeded BuildResultProvisioningState = "Succeeded" +) + +// PossibleBuildResultProvisioningStateValues returns an array of possible values for the BuildResultProvisioningState const type. +func PossibleBuildResultProvisioningStateValues() []BuildResultProvisioningState { + return []BuildResultProvisioningState{BuildResultProvisioningStateBuilding, BuildResultProvisioningStateDeleting, BuildResultProvisioningStateFailed, BuildResultProvisioningStateQueuing, BuildResultProvisioningStateSucceeded} +} + +// BuildServiceProvisioningState enumerates the values for build service provisioning state. +type BuildServiceProvisioningState string + +const ( + // BuildServiceProvisioningStateCreating ... + BuildServiceProvisioningStateCreating BuildServiceProvisioningState = "Creating" + // BuildServiceProvisioningStateDeleting ... + BuildServiceProvisioningStateDeleting BuildServiceProvisioningState = "Deleting" + // BuildServiceProvisioningStateFailed ... + BuildServiceProvisioningStateFailed BuildServiceProvisioningState = "Failed" + // BuildServiceProvisioningStateSucceeded ... + BuildServiceProvisioningStateSucceeded BuildServiceProvisioningState = "Succeeded" + // BuildServiceProvisioningStateUpdating ... + BuildServiceProvisioningStateUpdating BuildServiceProvisioningState = "Updating" +) + +// PossibleBuildServiceProvisioningStateValues returns an array of possible values for the BuildServiceProvisioningState const type. +func PossibleBuildServiceProvisioningStateValues() []BuildServiceProvisioningState { + return []BuildServiceProvisioningState{BuildServiceProvisioningStateCreating, BuildServiceProvisioningStateDeleting, BuildServiceProvisioningStateFailed, BuildServiceProvisioningStateSucceeded, BuildServiceProvisioningStateUpdating} +} + +// CertificateResourceProvisioningState enumerates the values for certificate resource provisioning state. +type CertificateResourceProvisioningState string + +const ( + // CertificateResourceProvisioningStateCreating ... + CertificateResourceProvisioningStateCreating CertificateResourceProvisioningState = "Creating" + // CertificateResourceProvisioningStateDeleting ... + CertificateResourceProvisioningStateDeleting CertificateResourceProvisioningState = "Deleting" + // CertificateResourceProvisioningStateFailed ... + CertificateResourceProvisioningStateFailed CertificateResourceProvisioningState = "Failed" + // CertificateResourceProvisioningStateSucceeded ... + CertificateResourceProvisioningStateSucceeded CertificateResourceProvisioningState = "Succeeded" + // CertificateResourceProvisioningStateUpdating ... + CertificateResourceProvisioningStateUpdating CertificateResourceProvisioningState = "Updating" +) + +// PossibleCertificateResourceProvisioningStateValues returns an array of possible values for the CertificateResourceProvisioningState const type. +func PossibleCertificateResourceProvisioningStateValues() []CertificateResourceProvisioningState { + return []CertificateResourceProvisioningState{CertificateResourceProvisioningStateCreating, CertificateResourceProvisioningStateDeleting, CertificateResourceProvisioningStateFailed, CertificateResourceProvisioningStateSucceeded, CertificateResourceProvisioningStateUpdating} +} + +// ConfigServerState enumerates the values for config server state. +type ConfigServerState string + +const ( + // ConfigServerStateDeleted ... + ConfigServerStateDeleted ConfigServerState = "Deleted" + // ConfigServerStateFailed ... + ConfigServerStateFailed ConfigServerState = "Failed" + // ConfigServerStateNotAvailable ... + ConfigServerStateNotAvailable ConfigServerState = "NotAvailable" + // ConfigServerStateSucceeded ... + ConfigServerStateSucceeded ConfigServerState = "Succeeded" + // ConfigServerStateUpdating ... + ConfigServerStateUpdating ConfigServerState = "Updating" +) + +// PossibleConfigServerStateValues returns an array of possible values for the ConfigServerState const type. +func PossibleConfigServerStateValues() []ConfigServerState { + return []ConfigServerState{ConfigServerStateDeleted, ConfigServerStateFailed, ConfigServerStateNotAvailable, ConfigServerStateSucceeded, ConfigServerStateUpdating} +} + +// ConfigurationServiceProvisioningState enumerates the values for configuration service provisioning state. +type ConfigurationServiceProvisioningState string + +const ( + // ConfigurationServiceProvisioningStateCreating ... + ConfigurationServiceProvisioningStateCreating ConfigurationServiceProvisioningState = "Creating" + // ConfigurationServiceProvisioningStateDeleting ... + ConfigurationServiceProvisioningStateDeleting ConfigurationServiceProvisioningState = "Deleting" + // ConfigurationServiceProvisioningStateFailed ... + ConfigurationServiceProvisioningStateFailed ConfigurationServiceProvisioningState = "Failed" + // ConfigurationServiceProvisioningStateSucceeded ... + ConfigurationServiceProvisioningStateSucceeded ConfigurationServiceProvisioningState = "Succeeded" + // ConfigurationServiceProvisioningStateUpdating ... + ConfigurationServiceProvisioningStateUpdating ConfigurationServiceProvisioningState = "Updating" +) + +// PossibleConfigurationServiceProvisioningStateValues returns an array of possible values for the ConfigurationServiceProvisioningState const type. +func PossibleConfigurationServiceProvisioningStateValues() []ConfigurationServiceProvisioningState { + return []ConfigurationServiceProvisioningState{ConfigurationServiceProvisioningStateCreating, ConfigurationServiceProvisioningStateDeleting, ConfigurationServiceProvisioningStateFailed, ConfigurationServiceProvisioningStateSucceeded, ConfigurationServiceProvisioningStateUpdating} +} + +// CreatedByType enumerates the values for created by type. +type CreatedByType string + +const ( + // CreatedByTypeApplication ... + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey ... + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity ... + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser ... + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns an array of possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{CreatedByTypeApplication, CreatedByTypeKey, CreatedByTypeManagedIdentity, CreatedByTypeUser} +} + +// CustomDomainResourceProvisioningState enumerates the values for custom domain resource provisioning state. +type CustomDomainResourceProvisioningState string + +const ( + // CustomDomainResourceProvisioningStateCreating ... + CustomDomainResourceProvisioningStateCreating CustomDomainResourceProvisioningState = "Creating" + // CustomDomainResourceProvisioningStateDeleting ... + CustomDomainResourceProvisioningStateDeleting CustomDomainResourceProvisioningState = "Deleting" + // CustomDomainResourceProvisioningStateFailed ... + CustomDomainResourceProvisioningStateFailed CustomDomainResourceProvisioningState = "Failed" + // CustomDomainResourceProvisioningStateSucceeded ... + CustomDomainResourceProvisioningStateSucceeded CustomDomainResourceProvisioningState = "Succeeded" + // CustomDomainResourceProvisioningStateUpdating ... + CustomDomainResourceProvisioningStateUpdating CustomDomainResourceProvisioningState = "Updating" +) + +// PossibleCustomDomainResourceProvisioningStateValues returns an array of possible values for the CustomDomainResourceProvisioningState const type. +func PossibleCustomDomainResourceProvisioningStateValues() []CustomDomainResourceProvisioningState { + return []CustomDomainResourceProvisioningState{CustomDomainResourceProvisioningStateCreating, CustomDomainResourceProvisioningStateDeleting, CustomDomainResourceProvisioningStateFailed, CustomDomainResourceProvisioningStateSucceeded, CustomDomainResourceProvisioningStateUpdating} +} + +// DeploymentResourceProvisioningState enumerates the values for deployment resource provisioning state. +type DeploymentResourceProvisioningState string + +const ( + // DeploymentResourceProvisioningStateCreating ... + DeploymentResourceProvisioningStateCreating DeploymentResourceProvisioningState = "Creating" + // DeploymentResourceProvisioningStateFailed ... + DeploymentResourceProvisioningStateFailed DeploymentResourceProvisioningState = "Failed" + // DeploymentResourceProvisioningStateSucceeded ... + DeploymentResourceProvisioningStateSucceeded DeploymentResourceProvisioningState = "Succeeded" + // DeploymentResourceProvisioningStateUpdating ... + DeploymentResourceProvisioningStateUpdating DeploymentResourceProvisioningState = "Updating" +) + +// PossibleDeploymentResourceProvisioningStateValues returns an array of possible values for the DeploymentResourceProvisioningState const type. +func PossibleDeploymentResourceProvisioningStateValues() []DeploymentResourceProvisioningState { + return []DeploymentResourceProvisioningState{DeploymentResourceProvisioningStateCreating, DeploymentResourceProvisioningStateFailed, DeploymentResourceProvisioningStateSucceeded, DeploymentResourceProvisioningStateUpdating} +} + +// DeploymentResourceStatus enumerates the values for deployment resource status. +type DeploymentResourceStatus string + +const ( + // DeploymentResourceStatusRunning ... + DeploymentResourceStatusRunning DeploymentResourceStatus = "Running" + // DeploymentResourceStatusStopped ... + DeploymentResourceStatusStopped DeploymentResourceStatus = "Stopped" +) + +// PossibleDeploymentResourceStatusValues returns an array of possible values for the DeploymentResourceStatus const type. +func PossibleDeploymentResourceStatusValues() []DeploymentResourceStatus { + return []DeploymentResourceStatus{DeploymentResourceStatusRunning, DeploymentResourceStatusStopped} +} + +// GatewayProvisioningState enumerates the values for gateway provisioning state. +type GatewayProvisioningState string + +const ( + // GatewayProvisioningStateCreating ... + GatewayProvisioningStateCreating GatewayProvisioningState = "Creating" + // GatewayProvisioningStateDeleting ... + GatewayProvisioningStateDeleting GatewayProvisioningState = "Deleting" + // GatewayProvisioningStateFailed ... + GatewayProvisioningStateFailed GatewayProvisioningState = "Failed" + // GatewayProvisioningStateSucceeded ... + GatewayProvisioningStateSucceeded GatewayProvisioningState = "Succeeded" + // GatewayProvisioningStateUpdating ... + GatewayProvisioningStateUpdating GatewayProvisioningState = "Updating" +) + +// PossibleGatewayProvisioningStateValues returns an array of possible values for the GatewayProvisioningState const type. +func PossibleGatewayProvisioningStateValues() []GatewayProvisioningState { + return []GatewayProvisioningState{GatewayProvisioningStateCreating, GatewayProvisioningStateDeleting, GatewayProvisioningStateFailed, GatewayProvisioningStateSucceeded, GatewayProvisioningStateUpdating} +} + +// HTTPSchemeType enumerates the values for http scheme type. +type HTTPSchemeType string + +const ( + // HTTPSchemeTypeHTTP ... + HTTPSchemeTypeHTTP HTTPSchemeType = "HTTP" + // HTTPSchemeTypeHTTPS ... + HTTPSchemeTypeHTTPS HTTPSchemeType = "HTTPS" +) + +// PossibleHTTPSchemeTypeValues returns an array of possible values for the HTTPSchemeType const type. +func PossibleHTTPSchemeTypeValues() []HTTPSchemeType { + return []HTTPSchemeType{HTTPSchemeTypeHTTP, HTTPSchemeTypeHTTPS} +} + +// KPackBuildStageProvisioningState enumerates the values for k pack build stage provisioning state. +type KPackBuildStageProvisioningState string + +const ( + // KPackBuildStageProvisioningStateFailed ... + KPackBuildStageProvisioningStateFailed KPackBuildStageProvisioningState = "Failed" + // KPackBuildStageProvisioningStateNotStarted ... + KPackBuildStageProvisioningStateNotStarted KPackBuildStageProvisioningState = "NotStarted" + // KPackBuildStageProvisioningStateRunning ... + KPackBuildStageProvisioningStateRunning KPackBuildStageProvisioningState = "Running" + // KPackBuildStageProvisioningStateSucceeded ... + KPackBuildStageProvisioningStateSucceeded KPackBuildStageProvisioningState = "Succeeded" +) + +// PossibleKPackBuildStageProvisioningStateValues returns an array of possible values for the KPackBuildStageProvisioningState const type. +func PossibleKPackBuildStageProvisioningStateValues() []KPackBuildStageProvisioningState { + return []KPackBuildStageProvisioningState{KPackBuildStageProvisioningStateFailed, KPackBuildStageProvisioningStateNotStarted, KPackBuildStageProvisioningStateRunning, KPackBuildStageProvisioningStateSucceeded} +} + +// LastModifiedByType enumerates the values for last modified by type. +type LastModifiedByType string + +const ( + // LastModifiedByTypeApplication ... + LastModifiedByTypeApplication LastModifiedByType = "Application" + // LastModifiedByTypeKey ... + LastModifiedByTypeKey LastModifiedByType = "Key" + // LastModifiedByTypeManagedIdentity ... + LastModifiedByTypeManagedIdentity LastModifiedByType = "ManagedIdentity" + // LastModifiedByTypeUser ... + LastModifiedByTypeUser LastModifiedByType = "User" +) + +// PossibleLastModifiedByTypeValues returns an array of possible values for the LastModifiedByType const type. +func PossibleLastModifiedByTypeValues() []LastModifiedByType { + return []LastModifiedByType{LastModifiedByTypeApplication, LastModifiedByTypeKey, LastModifiedByTypeManagedIdentity, LastModifiedByTypeUser} +} + +// ManagedIdentityType enumerates the values for managed identity type. +type ManagedIdentityType string + +const ( + // ManagedIdentityTypeNone ... + ManagedIdentityTypeNone ManagedIdentityType = "None" + // ManagedIdentityTypeSystemAssigned ... + ManagedIdentityTypeSystemAssigned ManagedIdentityType = "SystemAssigned" + // ManagedIdentityTypeSystemAssignedUserAssigned ... + ManagedIdentityTypeSystemAssignedUserAssigned ManagedIdentityType = "SystemAssigned,UserAssigned" + // ManagedIdentityTypeUserAssigned ... + ManagedIdentityTypeUserAssigned ManagedIdentityType = "UserAssigned" +) + +// PossibleManagedIdentityTypeValues returns an array of possible values for the ManagedIdentityType const type. +func PossibleManagedIdentityTypeValues() []ManagedIdentityType { + return []ManagedIdentityType{ManagedIdentityTypeNone, ManagedIdentityTypeSystemAssigned, ManagedIdentityTypeSystemAssignedUserAssigned, ManagedIdentityTypeUserAssigned} +} + +// MonitoringSettingState enumerates the values for monitoring setting state. +type MonitoringSettingState string + +const ( + // MonitoringSettingStateFailed ... + MonitoringSettingStateFailed MonitoringSettingState = "Failed" + // MonitoringSettingStateNotAvailable ... + MonitoringSettingStateNotAvailable MonitoringSettingState = "NotAvailable" + // MonitoringSettingStateSucceeded ... + MonitoringSettingStateSucceeded MonitoringSettingState = "Succeeded" + // MonitoringSettingStateUpdating ... + MonitoringSettingStateUpdating MonitoringSettingState = "Updating" +) + +// PossibleMonitoringSettingStateValues returns an array of possible values for the MonitoringSettingState const type. +func PossibleMonitoringSettingStateValues() []MonitoringSettingState { + return []MonitoringSettingState{MonitoringSettingStateFailed, MonitoringSettingStateNotAvailable, MonitoringSettingStateSucceeded, MonitoringSettingStateUpdating} +} + +// PowerState enumerates the values for power state. +type PowerState string + +const ( + // PowerStateRunning ... + PowerStateRunning PowerState = "Running" + // PowerStateStopped ... + PowerStateStopped PowerState = "Stopped" +) + +// PossiblePowerStateValues returns an array of possible values for the PowerState const type. +func PossiblePowerStateValues() []PowerState { + return []PowerState{PowerStateRunning, PowerStateStopped} +} + +// ProvisioningState enumerates the values for provisioning state. +type ProvisioningState string + +const ( + // ProvisioningStateCreating ... + ProvisioningStateCreating ProvisioningState = "Creating" + // ProvisioningStateDeleted ... + ProvisioningStateDeleted ProvisioningState = "Deleted" + // ProvisioningStateDeleting ... + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed ... + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateMoved ... + ProvisioningStateMoved ProvisioningState = "Moved" + // ProvisioningStateMoveFailed ... + ProvisioningStateMoveFailed ProvisioningState = "MoveFailed" + // ProvisioningStateMoving ... + ProvisioningStateMoving ProvisioningState = "Moving" + // ProvisioningStateStarting ... + ProvisioningStateStarting ProvisioningState = "Starting" + // ProvisioningStateStopping ... + ProvisioningStateStopping ProvisioningState = "Stopping" + // ProvisioningStateSucceeded ... + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating ... + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ProvisioningStateCreating, ProvisioningStateDeleted, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateMoved, ProvisioningStateMoveFailed, ProvisioningStateMoving, ProvisioningStateStarting, ProvisioningStateStopping, ProvisioningStateSucceeded, ProvisioningStateUpdating} +} + +// ResourceSkuRestrictionsReasonCode enumerates the values for resource sku restrictions reason code. +type ResourceSkuRestrictionsReasonCode string + +const ( + // ResourceSkuRestrictionsReasonCodeNotAvailableForSubscription ... + ResourceSkuRestrictionsReasonCodeNotAvailableForSubscription ResourceSkuRestrictionsReasonCode = "NotAvailableForSubscription" + // ResourceSkuRestrictionsReasonCodeQuotaID ... + ResourceSkuRestrictionsReasonCodeQuotaID ResourceSkuRestrictionsReasonCode = "QuotaId" +) + +// PossibleResourceSkuRestrictionsReasonCodeValues returns an array of possible values for the ResourceSkuRestrictionsReasonCode const type. +func PossibleResourceSkuRestrictionsReasonCodeValues() []ResourceSkuRestrictionsReasonCode { + return []ResourceSkuRestrictionsReasonCode{ResourceSkuRestrictionsReasonCodeNotAvailableForSubscription, ResourceSkuRestrictionsReasonCodeQuotaID} +} + +// ResourceSkuRestrictionsType enumerates the values for resource sku restrictions type. +type ResourceSkuRestrictionsType string + +const ( + // ResourceSkuRestrictionsTypeLocation ... + ResourceSkuRestrictionsTypeLocation ResourceSkuRestrictionsType = "Location" + // ResourceSkuRestrictionsTypeZone ... + ResourceSkuRestrictionsTypeZone ResourceSkuRestrictionsType = "Zone" +) + +// PossibleResourceSkuRestrictionsTypeValues returns an array of possible values for the ResourceSkuRestrictionsType const type. +func PossibleResourceSkuRestrictionsTypeValues() []ResourceSkuRestrictionsType { + return []ResourceSkuRestrictionsType{ResourceSkuRestrictionsTypeLocation, ResourceSkuRestrictionsTypeZone} +} + +// ServiceRegistryProvisioningState enumerates the values for service registry provisioning state. +type ServiceRegistryProvisioningState string + +const ( + // ServiceRegistryProvisioningStateCreating ... + ServiceRegistryProvisioningStateCreating ServiceRegistryProvisioningState = "Creating" + // ServiceRegistryProvisioningStateDeleting ... + ServiceRegistryProvisioningStateDeleting ServiceRegistryProvisioningState = "Deleting" + // ServiceRegistryProvisioningStateFailed ... + ServiceRegistryProvisioningStateFailed ServiceRegistryProvisioningState = "Failed" + // ServiceRegistryProvisioningStateSucceeded ... + ServiceRegistryProvisioningStateSucceeded ServiceRegistryProvisioningState = "Succeeded" + // ServiceRegistryProvisioningStateUpdating ... + ServiceRegistryProvisioningStateUpdating ServiceRegistryProvisioningState = "Updating" +) + +// PossibleServiceRegistryProvisioningStateValues returns an array of possible values for the ServiceRegistryProvisioningState const type. +func PossibleServiceRegistryProvisioningStateValues() []ServiceRegistryProvisioningState { + return []ServiceRegistryProvisioningState{ServiceRegistryProvisioningStateCreating, ServiceRegistryProvisioningStateDeleting, ServiceRegistryProvisioningStateFailed, ServiceRegistryProvisioningStateSucceeded, ServiceRegistryProvisioningStateUpdating} +} + +// SkuScaleType enumerates the values for sku scale type. +type SkuScaleType string + +const ( + // SkuScaleTypeAutomatic ... + SkuScaleTypeAutomatic SkuScaleType = "Automatic" + // SkuScaleTypeManual ... + SkuScaleTypeManual SkuScaleType = "Manual" + // SkuScaleTypeNone ... + SkuScaleTypeNone SkuScaleType = "None" +) + +// PossibleSkuScaleTypeValues returns an array of possible values for the SkuScaleType const type. +func PossibleSkuScaleTypeValues() []SkuScaleType { + return []SkuScaleType{SkuScaleTypeAutomatic, SkuScaleTypeManual, SkuScaleTypeNone} +} + +// StorageType enumerates the values for storage type. +type StorageType string + +const ( + // StorageTypeStorageAccount ... + StorageTypeStorageAccount StorageType = "StorageAccount" + // StorageTypeStorageProperties ... + StorageTypeStorageProperties StorageType = "StorageProperties" +) + +// PossibleStorageTypeValues returns an array of possible values for the StorageType const type. +func PossibleStorageTypeValues() []StorageType { + return []StorageType{StorageTypeStorageAccount, StorageTypeStorageProperties} +} + +// SupportedRuntimePlatform enumerates the values for supported runtime platform. +type SupportedRuntimePlatform string + +const ( + // SupportedRuntimePlatformJava ... + SupportedRuntimePlatformJava SupportedRuntimePlatform = "Java" + // SupportedRuntimePlatformNETCore ... + SupportedRuntimePlatformNETCore SupportedRuntimePlatform = ".NET Core" +) + +// PossibleSupportedRuntimePlatformValues returns an array of possible values for the SupportedRuntimePlatform const type. +func PossibleSupportedRuntimePlatformValues() []SupportedRuntimePlatform { + return []SupportedRuntimePlatform{SupportedRuntimePlatformJava, SupportedRuntimePlatformNETCore} +} + +// SupportedRuntimeValue enumerates the values for supported runtime value. +type SupportedRuntimeValue string + +const ( + // SupportedRuntimeValueJava11 ... + SupportedRuntimeValueJava11 SupportedRuntimeValue = "Java_11" + // SupportedRuntimeValueJava17 ... + SupportedRuntimeValueJava17 SupportedRuntimeValue = "Java_17" + // SupportedRuntimeValueJava8 ... + SupportedRuntimeValueJava8 SupportedRuntimeValue = "Java_8" + // SupportedRuntimeValueNetCore31 ... + SupportedRuntimeValueNetCore31 SupportedRuntimeValue = "NetCore_31" +) + +// PossibleSupportedRuntimeValueValues returns an array of possible values for the SupportedRuntimeValue const type. +func PossibleSupportedRuntimeValueValues() []SupportedRuntimeValue { + return []SupportedRuntimeValue{SupportedRuntimeValueJava11, SupportedRuntimeValueJava17, SupportedRuntimeValueJava8, SupportedRuntimeValueNetCore31} +} + +// TestKeyType enumerates the values for test key type. +type TestKeyType string + +const ( + // TestKeyTypePrimary ... + TestKeyTypePrimary TestKeyType = "Primary" + // TestKeyTypeSecondary ... + TestKeyTypeSecondary TestKeyType = "Secondary" +) + +// PossibleTestKeyTypeValues returns an array of possible values for the TestKeyType const type. +func PossibleTestKeyTypeValues() []TestKeyType { + return []TestKeyType{TestKeyTypePrimary, TestKeyTypeSecondary} +} + +// TrafficDirection enumerates the values for traffic direction. +type TrafficDirection string + +const ( + // TrafficDirectionInbound ... + TrafficDirectionInbound TrafficDirection = "Inbound" + // TrafficDirectionOutbound ... + TrafficDirectionOutbound TrafficDirection = "Outbound" +) + +// PossibleTrafficDirectionValues returns an array of possible values for the TrafficDirection const type. +func PossibleTrafficDirectionValues() []TrafficDirection { + return []TrafficDirection{TrafficDirectionInbound, TrafficDirectionOutbound} +} + +// Type enumerates the values for type. +type Type string + +const ( + // TypeAzureFileVolume ... + TypeAzureFileVolume Type = "AzureFileVolume" + // TypeCustomPersistentDiskProperties ... + TypeCustomPersistentDiskProperties Type = "CustomPersistentDiskProperties" +) + +// PossibleTypeValues returns an array of possible values for the Type const type. +func PossibleTypeValues() []Type { + return []Type{TypeAzureFileVolume, TypeCustomPersistentDiskProperties} +} + +// TypeBasicCertificateProperties enumerates the values for type basic certificate properties. +type TypeBasicCertificateProperties string + +const ( + // TypeBasicCertificatePropertiesTypeCertificateProperties ... + TypeBasicCertificatePropertiesTypeCertificateProperties TypeBasicCertificateProperties = "CertificateProperties" + // TypeBasicCertificatePropertiesTypeContentCertificate ... + TypeBasicCertificatePropertiesTypeContentCertificate TypeBasicCertificateProperties = "ContentCertificate" + // TypeBasicCertificatePropertiesTypeKeyVaultCertificate ... + TypeBasicCertificatePropertiesTypeKeyVaultCertificate TypeBasicCertificateProperties = "KeyVaultCertificate" +) + +// PossibleTypeBasicCertificatePropertiesValues returns an array of possible values for the TypeBasicCertificateProperties const type. +func PossibleTypeBasicCertificatePropertiesValues() []TypeBasicCertificateProperties { + return []TypeBasicCertificateProperties{TypeBasicCertificatePropertiesTypeCertificateProperties, TypeBasicCertificatePropertiesTypeContentCertificate, TypeBasicCertificatePropertiesTypeKeyVaultCertificate} +} + +// TypeBasicProbeAction enumerates the values for type basic probe action. +type TypeBasicProbeAction string + +const ( + // TypeBasicProbeActionTypeExecAction ... + TypeBasicProbeActionTypeExecAction TypeBasicProbeAction = "ExecAction" + // TypeBasicProbeActionTypeHTTPGetAction ... + TypeBasicProbeActionTypeHTTPGetAction TypeBasicProbeAction = "HTTPGetAction" + // TypeBasicProbeActionTypeProbeAction ... + TypeBasicProbeActionTypeProbeAction TypeBasicProbeAction = "ProbeAction" + // TypeBasicProbeActionTypeTCPSocketAction ... + TypeBasicProbeActionTypeTCPSocketAction TypeBasicProbeAction = "TCPSocketAction" +) + +// PossibleTypeBasicProbeActionValues returns an array of possible values for the TypeBasicProbeAction const type. +func PossibleTypeBasicProbeActionValues() []TypeBasicProbeAction { + return []TypeBasicProbeAction{TypeBasicProbeActionTypeExecAction, TypeBasicProbeActionTypeHTTPGetAction, TypeBasicProbeActionTypeProbeAction, TypeBasicProbeActionTypeTCPSocketAction} +} + +// TypeBasicUserSourceInfo enumerates the values for type basic user source info. +type TypeBasicUserSourceInfo string + +const ( + // TypeBasicUserSourceInfoTypeBuildResult ... + TypeBasicUserSourceInfoTypeBuildResult TypeBasicUserSourceInfo = "BuildResult" + // TypeBasicUserSourceInfoTypeContainer ... + TypeBasicUserSourceInfoTypeContainer TypeBasicUserSourceInfo = "Container" + // TypeBasicUserSourceInfoTypeJar ... + TypeBasicUserSourceInfoTypeJar TypeBasicUserSourceInfo = "Jar" + // TypeBasicUserSourceInfoTypeNetCoreZip ... + TypeBasicUserSourceInfoTypeNetCoreZip TypeBasicUserSourceInfo = "NetCoreZip" + // TypeBasicUserSourceInfoTypeSource ... + TypeBasicUserSourceInfoTypeSource TypeBasicUserSourceInfo = "Source" + // TypeBasicUserSourceInfoTypeUploadedUserSourceInfo ... + TypeBasicUserSourceInfoTypeUploadedUserSourceInfo TypeBasicUserSourceInfo = "UploadedUserSourceInfo" + // TypeBasicUserSourceInfoTypeUserSourceInfo ... + TypeBasicUserSourceInfoTypeUserSourceInfo TypeBasicUserSourceInfo = "UserSourceInfo" +) + +// PossibleTypeBasicUserSourceInfoValues returns an array of possible values for the TypeBasicUserSourceInfo const type. +func PossibleTypeBasicUserSourceInfoValues() []TypeBasicUserSourceInfo { + return []TypeBasicUserSourceInfo{TypeBasicUserSourceInfoTypeBuildResult, TypeBasicUserSourceInfoTypeContainer, TypeBasicUserSourceInfoTypeJar, TypeBasicUserSourceInfoTypeNetCoreZip, TypeBasicUserSourceInfoTypeSource, TypeBasicUserSourceInfoTypeUploadedUserSourceInfo, TypeBasicUserSourceInfoTypeUserSourceInfo} +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gatewaycustomdomains.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gatewaycustomdomains.go new file mode 100644 index 000000000000..2ba9a4e5b900 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gatewaycustomdomains.go @@ -0,0 +1,404 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// GatewayCustomDomainsClient is the REST API for Azure Spring Apps +type GatewayCustomDomainsClient struct { + BaseClient +} + +// NewGatewayCustomDomainsClient creates an instance of the GatewayCustomDomainsClient client. +func NewGatewayCustomDomainsClient(subscriptionID string) GatewayCustomDomainsClient { + return NewGatewayCustomDomainsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewGatewayCustomDomainsClientWithBaseURI creates an instance of the GatewayCustomDomainsClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewGatewayCustomDomainsClientWithBaseURI(baseURI string, subscriptionID string) GatewayCustomDomainsClient { + return GatewayCustomDomainsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or update the Spring Cloud Gateway custom domain. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +// domainName - the name of the Spring Cloud Gateway custom domain. +// gatewayCustomDomainResource - the gateway custom domain resource for the create or update operation +func (client GatewayCustomDomainsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string, gatewayCustomDomainResource GatewayCustomDomainResource) (result GatewayCustomDomainsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, gatewayName, domainName, gatewayCustomDomainResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client GatewayCustomDomainsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string, gatewayCustomDomainResource GatewayCustomDomainResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "domainName": autorest.Encode("path", domainName), + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/domains/{domainName}", pathParameters), + autorest.WithJSON(gatewayCustomDomainResource), + 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 GatewayCustomDomainsClient) CreateOrUpdateSender(req *http.Request) (future GatewayCustomDomainsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client GatewayCustomDomainsClient) CreateOrUpdateResponder(resp *http.Response) (result GatewayCustomDomainResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete the Spring Cloud Gateway custom domain. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +// domainName - the name of the Spring Cloud Gateway custom domain. +func (client GatewayCustomDomainsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string) (result GatewayCustomDomainsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, gatewayName, domainName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client GatewayCustomDomainsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "domainName": autorest.Encode("path", domainName), + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/domains/{domainName}", 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 GatewayCustomDomainsClient) DeleteSender(req *http.Request) (future GatewayCustomDomainsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client GatewayCustomDomainsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the Spring Cloud Gateway custom domain. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +// domainName - the name of the Spring Cloud Gateway custom domain. +func (client GatewayCustomDomainsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string) (result GatewayCustomDomainResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, gatewayName, domainName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client GatewayCustomDomainsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "domainName": autorest.Encode("path", domainName), + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/domains/{domainName}", 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 GatewayCustomDomainsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client GatewayCustomDomainsClient) GetResponder(resp *http.Response) (result GatewayCustomDomainResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handle requests to list all Spring Cloud Gateway custom domains. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +func (client GatewayCustomDomainsClient) List(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayCustomDomainResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.List") + defer func() { + sc := -1 + if result.gcdrc.Response.Response != nil { + sc = result.gcdrc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, gatewayName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.gcdrc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "List", resp, "Failure sending request") + return + } + + result.gcdrc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "List", resp, "Failure responding to request") + return + } + if result.gcdrc.hasNextLink() && result.gcdrc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client GatewayCustomDomainsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/domains", 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 GatewayCustomDomainsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client GatewayCustomDomainsClient) ListResponder(resp *http.Response) (result GatewayCustomDomainResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 GatewayCustomDomainsClient) listNextResults(ctx context.Context, lastResults GatewayCustomDomainResourceCollection) (result GatewayCustomDomainResourceCollection, err error) { + req, err := lastResults.gatewayCustomDomainResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "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, "appplatform.GatewayCustomDomainsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client GatewayCustomDomainsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayCustomDomainResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName, gatewayName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gatewayrouteconfigs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gatewayrouteconfigs.go new file mode 100644 index 000000000000..1f80054fa1a1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gatewayrouteconfigs.go @@ -0,0 +1,405 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// GatewayRouteConfigsClient is the REST API for Azure Spring Apps +type GatewayRouteConfigsClient struct { + BaseClient +} + +// NewGatewayRouteConfigsClient creates an instance of the GatewayRouteConfigsClient client. +func NewGatewayRouteConfigsClient(subscriptionID string) GatewayRouteConfigsClient { + return NewGatewayRouteConfigsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewGatewayRouteConfigsClientWithBaseURI creates an instance of the GatewayRouteConfigsClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewGatewayRouteConfigsClientWithBaseURI(baseURI string, subscriptionID string) GatewayRouteConfigsClient { + return GatewayRouteConfigsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create the default Spring Cloud Gateway route configs or update the existing Spring Cloud Gateway +// route configs. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +// routeConfigName - the name of the Spring Cloud Gateway route config. +// gatewayRouteConfigResource - the Spring Cloud Gateway route config for the create or update operation +func (client GatewayRouteConfigsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string, gatewayRouteConfigResource GatewayRouteConfigResource) (result GatewayRouteConfigsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, gatewayName, routeConfigName, gatewayRouteConfigResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client GatewayRouteConfigsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string, gatewayRouteConfigResource GatewayRouteConfigResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeConfigName": autorest.Encode("path", routeConfigName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/routeConfigs/{routeConfigName}", pathParameters), + autorest.WithJSON(gatewayRouteConfigResource), + 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 GatewayRouteConfigsClient) CreateOrUpdateSender(req *http.Request) (future GatewayRouteConfigsCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client GatewayRouteConfigsClient) CreateOrUpdateResponder(resp *http.Response) (result GatewayRouteConfigResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete the Spring Cloud Gateway route config. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +// routeConfigName - the name of the Spring Cloud Gateway route config. +func (client GatewayRouteConfigsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string) (result GatewayRouteConfigsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, gatewayName, routeConfigName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client GatewayRouteConfigsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeConfigName": autorest.Encode("path", routeConfigName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/routeConfigs/{routeConfigName}", 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 GatewayRouteConfigsClient) DeleteSender(req *http.Request) (future GatewayRouteConfigsDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client GatewayRouteConfigsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the Spring Cloud Gateway route configs. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +// routeConfigName - the name of the Spring Cloud Gateway route config. +func (client GatewayRouteConfigsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string) (result GatewayRouteConfigResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, gatewayName, routeConfigName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client GatewayRouteConfigsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeConfigName": autorest.Encode("path", routeConfigName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/routeConfigs/{routeConfigName}", 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 GatewayRouteConfigsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client GatewayRouteConfigsClient) GetResponder(resp *http.Response) (result GatewayRouteConfigResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handle requests to list all Spring Cloud Gateway route configs. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +func (client GatewayRouteConfigsClient) List(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayRouteConfigResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.List") + defer func() { + sc := -1 + if result.grcrc.Response.Response != nil { + sc = result.grcrc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, gatewayName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.grcrc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "List", resp, "Failure sending request") + return + } + + result.grcrc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "List", resp, "Failure responding to request") + return + } + if result.grcrc.hasNextLink() && result.grcrc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client GatewayRouteConfigsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/routeConfigs", 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 GatewayRouteConfigsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client GatewayRouteConfigsClient) ListResponder(resp *http.Response) (result GatewayRouteConfigResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 GatewayRouteConfigsClient) listNextResults(ctx context.Context, lastResults GatewayRouteConfigResourceCollection) (result GatewayRouteConfigResourceCollection, err error) { + req, err := lastResults.gatewayRouteConfigResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "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, "appplatform.GatewayRouteConfigsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client GatewayRouteConfigsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayRouteConfigResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName, gatewayName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gateways.go new file mode 100644 index 000000000000..31fb4c9e4aae --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/gateways.go @@ -0,0 +1,484 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// GatewaysClient is the REST API for Azure Spring Apps +type GatewaysClient struct { + BaseClient +} + +// NewGatewaysClient creates an instance of the GatewaysClient client. +func NewGatewaysClient(subscriptionID string) GatewaysClient { + return NewGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewGatewaysClientWithBaseURI creates an instance of the GatewaysClient client using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewGatewaysClientWithBaseURI(baseURI string, subscriptionID string) GatewaysClient { + return GatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create the default Spring Cloud Gateway or update the existing Spring Cloud Gateway. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +// gatewayResource - the gateway for the create or update operation +func (client GatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, gatewayResource GatewayResource) (result GatewaysCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, gatewayName, gatewayResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client GatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, gatewayResource GatewayResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}", pathParameters), + autorest.WithJSON(gatewayResource), + 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 GatewaysClient) CreateOrUpdateSender(req *http.Request) (future GatewaysCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client GatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result GatewayResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete disable the default Spring Cloud Gateway. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +func (client GatewaysClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewaysDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, gatewayName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client GatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}", 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 GatewaysClient) DeleteSender(req *http.Request) (future GatewaysDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client GatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the Spring Cloud Gateway and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +func (client GatewaysClient) Get(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, gatewayName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client GatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}", 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 GatewaysClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client GatewaysClient) GetResponder(resp *http.Response) (result GatewayResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handles requests to list all resources in a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client GatewaysClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result GatewayResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.List") + defer func() { + sc := -1 + if result.grc.Response.Response != nil { + sc = result.grc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.grc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "List", resp, "Failure sending request") + return + } + + result.grc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "List", resp, "Failure responding to request") + return + } + if result.grc.hasNextLink() && result.grc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client GatewaysClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways", 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 GatewaysClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client GatewaysClient) ListResponder(resp *http.Response) (result GatewayResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 GatewaysClient) listNextResults(ctx context.Context, lastResults GatewayResourceCollection) (result GatewayResourceCollection, err error) { + req, err := lastResults.gatewayResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "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, "appplatform.GatewaysClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client GatewaysClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result GatewayResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName) + return +} + +// ValidateDomain check the domains are valid as well as not in use. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// gatewayName - the name of Spring Cloud Gateway. +// validatePayload - custom domain payload to be validated +func (client GatewaysClient) ValidateDomain(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, validatePayload CustomDomainValidatePayload) (result CustomDomainValidateResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.ValidateDomain") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: validatePayload, + Constraints: []validation.Constraint{{Target: "validatePayload.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("appplatform.GatewaysClient", "ValidateDomain", err.Error()) + } + + req, err := client.ValidateDomainPreparer(ctx, resourceGroupName, serviceName, gatewayName, validatePayload) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "ValidateDomain", nil, "Failure preparing request") + return + } + + resp, err := client.ValidateDomainSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "ValidateDomain", resp, "Failure sending request") + return + } + + result, err = client.ValidateDomainResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "ValidateDomain", resp, "Failure responding to request") + return + } + + return +} + +// ValidateDomainPreparer prepares the ValidateDomain request. +func (client GatewaysClient) ValidateDomainPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, validatePayload CustomDomainValidatePayload) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "gatewayName": autorest.Encode("path", gatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/validateDomain", pathParameters), + autorest.WithJSON(validatePayload), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ValidateDomainSender sends the ValidateDomain request. The method will close the +// http.Response Body if it receives an error. +func (client GatewaysClient) ValidateDomainSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ValidateDomainResponder handles the response to the ValidateDomain request. The method always +// closes the http.Response Body. +func (client GatewaysClient) ValidateDomainResponder(resp *http.Response) (result CustomDomainValidateResult, err error) { + err = autorest.Respond( + resp, + 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/models.go new file mode 100644 index 000000000000..1a8d33624b94 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/models.go @@ -0,0 +1,9834 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// The package's fully qualified name. +const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform" + +// ActiveDeploymentCollection object that includes an array of Deployment resource name and set them as +// active. +type ActiveDeploymentCollection struct { + // ActiveDeploymentNames - Collection of Deployment name. + ActiveDeploymentNames *[]string `json:"activeDeploymentNames,omitempty"` +} + +// APIPortalCustomDomainProperties the properties of custom domain for API portal +type APIPortalCustomDomainProperties struct { + // Thumbprint - The thumbprint of bound certificate. + Thumbprint *string `json:"thumbprint,omitempty"` +} + +// APIPortalCustomDomainResource custom domain of the API portal +type APIPortalCustomDomainResource struct { + autorest.Response `json:"-"` + Properties *APIPortalCustomDomainProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for APIPortalCustomDomainResource. +func (apcdr APIPortalCustomDomainResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if apcdr.Properties != nil { + objectMap["properties"] = apcdr.Properties + } + if apcdr.SystemData != nil { + objectMap["systemData"] = apcdr.SystemData + } + return json.Marshal(objectMap) +} + +// APIPortalCustomDomainResourceCollection object that includes an array of API portal custom domain +// resources and a possible link for next set +type APIPortalCustomDomainResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of API portal custom domain resources + Value *[]APIPortalCustomDomainResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// APIPortalCustomDomainResourceCollectionIterator provides access to a complete listing of +// APIPortalCustomDomainResource values. +type APIPortalCustomDomainResourceCollectionIterator struct { + i int + page APIPortalCustomDomainResourceCollectionPage +} + +// NextWithContext 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 *APIPortalCustomDomainResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *APIPortalCustomDomainResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter APIPortalCustomDomainResourceCollectionIterator) 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 APIPortalCustomDomainResourceCollectionIterator) Response() APIPortalCustomDomainResourceCollection { + 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 APIPortalCustomDomainResourceCollectionIterator) Value() APIPortalCustomDomainResource { + if !iter.page.NotDone() { + return APIPortalCustomDomainResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the APIPortalCustomDomainResourceCollectionIterator type. +func NewAPIPortalCustomDomainResourceCollectionIterator(page APIPortalCustomDomainResourceCollectionPage) APIPortalCustomDomainResourceCollectionIterator { + return APIPortalCustomDomainResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (apcdrc APIPortalCustomDomainResourceCollection) IsEmpty() bool { + return apcdrc.Value == nil || len(*apcdrc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (apcdrc APIPortalCustomDomainResourceCollection) hasNextLink() bool { + return apcdrc.NextLink != nil && len(*apcdrc.NextLink) != 0 +} + +// aPIPortalCustomDomainResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (apcdrc APIPortalCustomDomainResourceCollection) aPIPortalCustomDomainResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !apcdrc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(apcdrc.NextLink))) +} + +// APIPortalCustomDomainResourceCollectionPage contains a page of APIPortalCustomDomainResource values. +type APIPortalCustomDomainResourceCollectionPage struct { + fn func(context.Context, APIPortalCustomDomainResourceCollection) (APIPortalCustomDomainResourceCollection, error) + apcdrc APIPortalCustomDomainResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *APIPortalCustomDomainResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.apcdrc) + if err != nil { + return err + } + page.apcdrc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *APIPortalCustomDomainResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page APIPortalCustomDomainResourceCollectionPage) NotDone() bool { + return !page.apcdrc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page APIPortalCustomDomainResourceCollectionPage) Response() APIPortalCustomDomainResourceCollection { + return page.apcdrc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page APIPortalCustomDomainResourceCollectionPage) Values() []APIPortalCustomDomainResource { + if page.apcdrc.IsEmpty() { + return nil + } + return *page.apcdrc.Value +} + +// Creates a new instance of the APIPortalCustomDomainResourceCollectionPage type. +func NewAPIPortalCustomDomainResourceCollectionPage(cur APIPortalCustomDomainResourceCollection, getNextPage func(context.Context, APIPortalCustomDomainResourceCollection) (APIPortalCustomDomainResourceCollection, error)) APIPortalCustomDomainResourceCollectionPage { + return APIPortalCustomDomainResourceCollectionPage{ + fn: getNextPage, + apcdrc: cur, + } +} + +// APIPortalCustomDomainsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type APIPortalCustomDomainsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(APIPortalCustomDomainsClient) (APIPortalCustomDomainResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *APIPortalCustomDomainsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for APIPortalCustomDomainsCreateOrUpdateFuture.Result. +func (future *APIPortalCustomDomainsCreateOrUpdateFuture) result(client APIPortalCustomDomainsClient) (apcdr APIPortalCustomDomainResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + apcdr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.APIPortalCustomDomainsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if apcdr.Response.Response, err = future.GetResult(sender); err == nil && apcdr.Response.Response.StatusCode != http.StatusNoContent { + apcdr, err = client.CreateOrUpdateResponder(apcdr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsCreateOrUpdateFuture", "Result", apcdr.Response.Response, "Failure responding to request") + } + } + return +} + +// APIPortalCustomDomainsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type APIPortalCustomDomainsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(APIPortalCustomDomainsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *APIPortalCustomDomainsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for APIPortalCustomDomainsDeleteFuture.Result. +func (future *APIPortalCustomDomainsDeleteFuture) result(client APIPortalCustomDomainsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.APIPortalCustomDomainsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// APIPortalInstance collection of instances belong to the API portal +type APIPortalInstance struct { + // Name - READ-ONLY; Name of the API portal instance + Name *string `json:"name,omitempty"` + // Status - READ-ONLY; Status of the API portal instance + Status *string `json:"status,omitempty"` +} + +// MarshalJSON is the custom marshaler for APIPortalInstance. +func (API APIPortalInstance) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// APIPortalProperties API portal properties payload +type APIPortalProperties struct { + // ProvisioningState - READ-ONLY; State of the API portal. Possible values include: 'APIPortalProvisioningStateCreating', 'APIPortalProvisioningStateUpdating', 'APIPortalProvisioningStateSucceeded', 'APIPortalProvisioningStateFailed', 'APIPortalProvisioningStateDeleting' + ProvisioningState APIPortalProvisioningState `json:"provisioningState,omitempty"` + // Public - Indicates whether the API portal exposes endpoint. + Public *bool `json:"public,omitempty"` + // URL - READ-ONLY; URL of the API portal, exposed when 'public' is true. + URL *string `json:"url,omitempty"` + // HTTPSOnly - Indicate if only https is allowed. + HTTPSOnly *bool `json:"httpsOnly,omitempty"` + // GatewayIds - The array of resource Ids of gateway to integrate with API portal. + GatewayIds *[]string `json:"gatewayIds,omitempty"` + // SourceUrls - Collection of OpenAPI source URL locations. + SourceUrls *[]string `json:"sourceUrls,omitempty"` + SsoProperties *SsoProperties `json:"ssoProperties,omitempty"` + // ResourceRequests - READ-ONLY; The requested resource quantity for required CPU and Memory. + ResourceRequests *APIPortalResourceRequests `json:"resourceRequests,omitempty"` + // Instances - READ-ONLY; Collection of instances belong to API portal. + Instances *[]APIPortalInstance `json:"instances,omitempty"` +} + +// MarshalJSON is the custom marshaler for APIPortalProperties. +func (app APIPortalProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if app.Public != nil { + objectMap["public"] = app.Public + } + if app.HTTPSOnly != nil { + objectMap["httpsOnly"] = app.HTTPSOnly + } + if app.GatewayIds != nil { + objectMap["gatewayIds"] = app.GatewayIds + } + if app.SourceUrls != nil { + objectMap["sourceUrls"] = app.SourceUrls + } + if app.SsoProperties != nil { + objectMap["ssoProperties"] = app.SsoProperties + } + return json.Marshal(objectMap) +} + +// APIPortalResource API portal resource +type APIPortalResource struct { + autorest.Response `json:"-"` + Properties *APIPortalProperties `json:"properties,omitempty"` + // Sku - Sku of the API portal resource + Sku *Sku `json:"sku,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for APIPortalResource. +func (apr APIPortalResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if apr.Properties != nil { + objectMap["properties"] = apr.Properties + } + if apr.Sku != nil { + objectMap["sku"] = apr.Sku + } + if apr.SystemData != nil { + objectMap["systemData"] = apr.SystemData + } + return json.Marshal(objectMap) +} + +// APIPortalResourceCollection object that includes an array of API portal resources and a possible link +// for next set +type APIPortalResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of API portal resources + Value *[]APIPortalResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// APIPortalResourceCollectionIterator provides access to a complete listing of APIPortalResource values. +type APIPortalResourceCollectionIterator struct { + i int + page APIPortalResourceCollectionPage +} + +// NextWithContext 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 *APIPortalResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *APIPortalResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter APIPortalResourceCollectionIterator) 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 APIPortalResourceCollectionIterator) Response() APIPortalResourceCollection { + 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 APIPortalResourceCollectionIterator) Value() APIPortalResource { + if !iter.page.NotDone() { + return APIPortalResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the APIPortalResourceCollectionIterator type. +func NewAPIPortalResourceCollectionIterator(page APIPortalResourceCollectionPage) APIPortalResourceCollectionIterator { + return APIPortalResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (aprc APIPortalResourceCollection) IsEmpty() bool { + return aprc.Value == nil || len(*aprc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (aprc APIPortalResourceCollection) hasNextLink() bool { + return aprc.NextLink != nil && len(*aprc.NextLink) != 0 +} + +// aPIPortalResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (aprc APIPortalResourceCollection) aPIPortalResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !aprc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(aprc.NextLink))) +} + +// APIPortalResourceCollectionPage contains a page of APIPortalResource values. +type APIPortalResourceCollectionPage struct { + fn func(context.Context, APIPortalResourceCollection) (APIPortalResourceCollection, error) + aprc APIPortalResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *APIPortalResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.aprc) + if err != nil { + return err + } + page.aprc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *APIPortalResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page APIPortalResourceCollectionPage) NotDone() bool { + return !page.aprc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page APIPortalResourceCollectionPage) Response() APIPortalResourceCollection { + return page.aprc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page APIPortalResourceCollectionPage) Values() []APIPortalResource { + if page.aprc.IsEmpty() { + return nil + } + return *page.aprc.Value +} + +// Creates a new instance of the APIPortalResourceCollectionPage type. +func NewAPIPortalResourceCollectionPage(cur APIPortalResourceCollection, getNextPage func(context.Context, APIPortalResourceCollection) (APIPortalResourceCollection, error)) APIPortalResourceCollectionPage { + return APIPortalResourceCollectionPage{ + fn: getNextPage, + aprc: cur, + } +} + +// APIPortalResourceRequests resource requests of the API portal +type APIPortalResourceRequests struct { + // CPU - READ-ONLY; Cpu allocated to each API portal instance + CPU *string `json:"cpu,omitempty"` + // Memory - READ-ONLY; Memory allocated to each API portal instance + Memory *string `json:"memory,omitempty"` +} + +// MarshalJSON is the custom marshaler for APIPortalResourceRequests. +func (aprr APIPortalResourceRequests) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// APIPortalsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type APIPortalsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(APIPortalsClient) (APIPortalResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *APIPortalsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for APIPortalsCreateOrUpdateFuture.Result. +func (future *APIPortalsCreateOrUpdateFuture) result(client APIPortalsClient) (apr APIPortalResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + apr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.APIPortalsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if apr.Response.Response, err = future.GetResult(sender); err == nil && apr.Response.Response.StatusCode != http.StatusNoContent { + apr, err = client.CreateOrUpdateResponder(apr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsCreateOrUpdateFuture", "Result", apr.Response.Response, "Failure responding to request") + } + } + return +} + +// APIPortalsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type APIPortalsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(APIPortalsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *APIPortalsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for APIPortalsDeleteFuture.Result. +func (future *APIPortalsDeleteFuture) result(client APIPortalsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.APIPortalsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.APIPortalsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ApplicationInsightsAgentVersions application Insights agent versions properties payload +type ApplicationInsightsAgentVersions struct { + // Java - READ-ONLY; Indicates the version of application insight java agent + Java *string `json:"java,omitempty"` +} + +// MarshalJSON is the custom marshaler for ApplicationInsightsAgentVersions. +func (aiav ApplicationInsightsAgentVersions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// AppResource app resource payload +type AppResource struct { + autorest.Response `json:"-"` + // Properties - Properties of the App resource + Properties *AppResourceProperties `json:"properties,omitempty"` + // Identity - The Managed Identity type of the app resource + Identity *ManagedIdentityProperties `json:"identity,omitempty"` + // Location - The GEO location of the application, always the same with its parent resource + Location *string `json:"location,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for AppResource. +func (ar AppResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ar.Properties != nil { + objectMap["properties"] = ar.Properties + } + if ar.Identity != nil { + objectMap["identity"] = ar.Identity + } + if ar.Location != nil { + objectMap["location"] = ar.Location + } + if ar.SystemData != nil { + objectMap["systemData"] = ar.SystemData + } + return json.Marshal(objectMap) +} + +// AppResourceCollection object that includes an array of App resources and a possible link for next set +type AppResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of App resources + Value *[]AppResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// AppResourceCollectionIterator provides access to a complete listing of AppResource values. +type AppResourceCollectionIterator struct { + i int + page AppResourceCollectionPage +} + +// NextWithContext 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 *AppResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *AppResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter AppResourceCollectionIterator) 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 AppResourceCollectionIterator) Response() AppResourceCollection { + 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 AppResourceCollectionIterator) Value() AppResource { + if !iter.page.NotDone() { + return AppResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the AppResourceCollectionIterator type. +func NewAppResourceCollectionIterator(page AppResourceCollectionPage) AppResourceCollectionIterator { + return AppResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (arc AppResourceCollection) IsEmpty() bool { + return arc.Value == nil || len(*arc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (arc AppResourceCollection) hasNextLink() bool { + return arc.NextLink != nil && len(*arc.NextLink) != 0 +} + +// appResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (arc AppResourceCollection) appResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !arc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(arc.NextLink))) +} + +// AppResourceCollectionPage contains a page of AppResource values. +type AppResourceCollectionPage struct { + fn func(context.Context, AppResourceCollection) (AppResourceCollection, error) + arc AppResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *AppResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AppResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.arc) + if err != nil { + return err + } + page.arc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *AppResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page AppResourceCollectionPage) NotDone() bool { + return !page.arc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page AppResourceCollectionPage) Response() AppResourceCollection { + return page.arc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page AppResourceCollectionPage) Values() []AppResource { + if page.arc.IsEmpty() { + return nil + } + return *page.arc.Value +} + +// Creates a new instance of the AppResourceCollectionPage type. +func NewAppResourceCollectionPage(cur AppResourceCollection, getNextPage func(context.Context, AppResourceCollection) (AppResourceCollection, error)) AppResourceCollectionPage { + return AppResourceCollectionPage{ + fn: getNextPage, + arc: cur, + } +} + +// AppResourceProperties app resource properties payload +type AppResourceProperties struct { + // Public - Indicates whether the App exposes public endpoint + Public *bool `json:"public,omitempty"` + // URL - READ-ONLY; URL of the App + URL *string `json:"url,omitempty"` + // AddonConfigs - Collection of addons + AddonConfigs map[string]map[string]interface{} `json:"addonConfigs"` + // ProvisioningState - READ-ONLY; Provisioning state of the App. Possible values include: 'AppResourceProvisioningStateSucceeded', 'AppResourceProvisioningStateFailed', 'AppResourceProvisioningStateCreating', 'AppResourceProvisioningStateUpdating', 'AppResourceProvisioningStateDeleting' + ProvisioningState AppResourceProvisioningState `json:"provisioningState,omitempty"` + // Fqdn - Fully qualified dns Name. + Fqdn *string `json:"fqdn,omitempty"` + // HTTPSOnly - Indicate if only https is allowed. + HTTPSOnly *bool `json:"httpsOnly,omitempty"` + // TemporaryDisk - Temporary disk settings + TemporaryDisk *TemporaryDisk `json:"temporaryDisk,omitempty"` + // PersistentDisk - Persistent disk settings + PersistentDisk *PersistentDisk `json:"persistentDisk,omitempty"` + // CustomPersistentDisks - List of custom persistent disks + CustomPersistentDisks *[]CustomPersistentDiskResource `json:"customPersistentDisks,omitempty"` + // EnableEndToEndTLS - Indicate if end to end TLS is enabled. + EnableEndToEndTLS *bool `json:"enableEndToEndTLS,omitempty"` + // LoadedCertificates - Collection of loaded certificates + LoadedCertificates *[]LoadedCertificate `json:"loadedCertificates,omitempty"` + // VnetAddons - Additional App settings in vnet injection instance + VnetAddons *AppVNetAddons `json:"vnetAddons,omitempty"` +} + +// MarshalJSON is the custom marshaler for AppResourceProperties. +func (arp AppResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if arp.Public != nil { + objectMap["public"] = arp.Public + } + if arp.AddonConfigs != nil { + objectMap["addonConfigs"] = arp.AddonConfigs + } + if arp.Fqdn != nil { + objectMap["fqdn"] = arp.Fqdn + } + if arp.HTTPSOnly != nil { + objectMap["httpsOnly"] = arp.HTTPSOnly + } + if arp.TemporaryDisk != nil { + objectMap["temporaryDisk"] = arp.TemporaryDisk + } + if arp.PersistentDisk != nil { + objectMap["persistentDisk"] = arp.PersistentDisk + } + if arp.CustomPersistentDisks != nil { + objectMap["customPersistentDisks"] = arp.CustomPersistentDisks + } + if arp.EnableEndToEndTLS != nil { + objectMap["enableEndToEndTLS"] = arp.EnableEndToEndTLS + } + if arp.LoadedCertificates != nil { + objectMap["loadedCertificates"] = arp.LoadedCertificates + } + if arp.VnetAddons != nil { + objectMap["vnetAddons"] = arp.VnetAddons + } + return json.Marshal(objectMap) +} + +// AppsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type AppsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(AppsClient) (AppResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *AppsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for AppsCreateOrUpdateFuture.Result. +func (future *AppsCreateOrUpdateFuture) result(client AppsClient) (ar AppResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.AppsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ar.Response.Response, err = future.GetResult(sender); err == nil && ar.Response.Response.StatusCode != http.StatusNoContent { + ar, err = client.CreateOrUpdateResponder(ar.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsCreateOrUpdateFuture", "Result", ar.Response.Response, "Failure responding to request") + } + } + return +} + +// AppsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type AppsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(AppsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *AppsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for AppsDeleteFuture.Result. +func (future *AppsDeleteFuture) result(client AppsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.AppsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// AppsSetActiveDeploymentsFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type AppsSetActiveDeploymentsFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(AppsClient) (AppResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *AppsSetActiveDeploymentsFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for AppsSetActiveDeploymentsFuture.Result. +func (future *AppsSetActiveDeploymentsFuture) result(client AppsClient) (ar AppResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsSetActiveDeploymentsFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.AppsSetActiveDeploymentsFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ar.Response.Response, err = future.GetResult(sender); err == nil && ar.Response.Response.StatusCode != http.StatusNoContent { + ar, err = client.SetActiveDeploymentsResponder(ar.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsSetActiveDeploymentsFuture", "Result", ar.Response.Response, "Failure responding to request") + } + } + return +} + +// AppsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type AppsUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(AppsClient) (AppResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *AppsUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for AppsUpdateFuture.Result. +func (future *AppsUpdateFuture) result(client AppsClient) (ar AppResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.AppsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ar.Response.Response, err = future.GetResult(sender); err == nil && ar.Response.Response.StatusCode != http.StatusNoContent { + ar, err = client.UpdateResponder(ar.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.AppsUpdateFuture", "Result", ar.Response.Response, "Failure responding to request") + } + } + return +} + +// AppVNetAddons additional App settings in vnet injection instance +type AppVNetAddons struct { + // PublicEndpoint - Indicates whether the App in vnet injection instance exposes endpoint which could be accessed from internet. + PublicEndpoint *bool `json:"publicEndpoint,omitempty"` + // PublicEndpointURL - READ-ONLY; URL of the App in vnet injection instance which could be accessed from internet + PublicEndpointURL *string `json:"publicEndpointUrl,omitempty"` +} + +// MarshalJSON is the custom marshaler for AppVNetAddons. +func (avna AppVNetAddons) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if avna.PublicEndpoint != nil { + objectMap["publicEndpoint"] = avna.PublicEndpoint + } + return json.Marshal(objectMap) +} + +// AvailableOperations available operations of the service +type AvailableOperations struct { + autorest.Response `json:"-"` + // Value - Collection of available operation details + Value *[]OperationDetail `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// AvailableOperationsIterator provides access to a complete listing of OperationDetail values. +type AvailableOperationsIterator struct { + i int + page AvailableOperationsPage +} + +// NextWithContext 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 *AvailableOperationsIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AvailableOperationsIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *AvailableOperationsIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter AvailableOperationsIterator) 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 AvailableOperationsIterator) Response() AvailableOperations { + 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 AvailableOperationsIterator) Value() OperationDetail { + if !iter.page.NotDone() { + return OperationDetail{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the AvailableOperationsIterator type. +func NewAvailableOperationsIterator(page AvailableOperationsPage) AvailableOperationsIterator { + return AvailableOperationsIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (ao AvailableOperations) IsEmpty() bool { + return ao.Value == nil || len(*ao.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (ao AvailableOperations) hasNextLink() bool { + return ao.NextLink != nil && len(*ao.NextLink) != 0 +} + +// availableOperationsPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ao AvailableOperations) availableOperationsPreparer(ctx context.Context) (*http.Request, error) { + if !ao.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ao.NextLink))) +} + +// AvailableOperationsPage contains a page of OperationDetail values. +type AvailableOperationsPage struct { + fn func(context.Context, AvailableOperations) (AvailableOperations, error) + ao AvailableOperations +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *AvailableOperationsPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AvailableOperationsPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.ao) + if err != nil { + return err + } + page.ao = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *AvailableOperationsPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page AvailableOperationsPage) NotDone() bool { + return !page.ao.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page AvailableOperationsPage) Response() AvailableOperations { + return page.ao +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page AvailableOperationsPage) Values() []OperationDetail { + if page.ao.IsEmpty() { + return nil + } + return *page.ao.Value +} + +// Creates a new instance of the AvailableOperationsPage type. +func NewAvailableOperationsPage(cur AvailableOperations, getNextPage func(context.Context, AvailableOperations) (AvailableOperations, error)) AvailableOperationsPage { + return AvailableOperationsPage{ + fn: getNextPage, + ao: cur, + } +} + +// AvailableRuntimeVersions ... +type AvailableRuntimeVersions struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; A list of all supported runtime versions. + Value *[]SupportedRuntimeVersion `json:"value,omitempty"` +} + +// MarshalJSON is the custom marshaler for AvailableRuntimeVersions. +func (arv AvailableRuntimeVersions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// AzureFileVolume the properties of the Azure File volume. Azure File shares are mounted as volumes. +type AzureFileVolume struct { + // ShareName - The share name of the Azure File share. + ShareName *string `json:"shareName,omitempty"` + // MountPath - The mount path of the persistent disk. + MountPath *string `json:"mountPath,omitempty"` + // ReadOnly - Indicates whether the persistent disk is a readOnly one. + ReadOnly *bool `json:"readOnly,omitempty"` + // MountOptions - These are the mount options for a persistent disk. + MountOptions *[]string `json:"mountOptions,omitempty"` + // Type - Possible values include: 'TypeCustomPersistentDiskProperties', 'TypeAzureFileVolume' + Type Type `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for AzureFileVolume. +func (afv AzureFileVolume) MarshalJSON() ([]byte, error) { + afv.Type = TypeAzureFileVolume + objectMap := make(map[string]interface{}) + if afv.ShareName != nil { + objectMap["shareName"] = afv.ShareName + } + if afv.MountPath != nil { + objectMap["mountPath"] = afv.MountPath + } + if afv.ReadOnly != nil { + objectMap["readOnly"] = afv.ReadOnly + } + if afv.MountOptions != nil { + objectMap["mountOptions"] = afv.MountOptions + } + if afv.Type != "" { + objectMap["type"] = afv.Type + } + return json.Marshal(objectMap) +} + +// AsAzureFileVolume is the BasicCustomPersistentDiskProperties implementation for AzureFileVolume. +func (afv AzureFileVolume) AsAzureFileVolume() (*AzureFileVolume, bool) { + return &afv, true +} + +// AsCustomPersistentDiskProperties is the BasicCustomPersistentDiskProperties implementation for AzureFileVolume. +func (afv AzureFileVolume) AsCustomPersistentDiskProperties() (*CustomPersistentDiskProperties, bool) { + return nil, false +} + +// AsBasicCustomPersistentDiskProperties is the BasicCustomPersistentDiskProperties implementation for AzureFileVolume. +func (afv AzureFileVolume) AsBasicCustomPersistentDiskProperties() (BasicCustomPersistentDiskProperties, bool) { + return &afv, true +} + +// BindingResource binding resource payload +type BindingResource struct { + autorest.Response `json:"-"` + // Properties - Properties of the Binding resource + Properties *BindingResourceProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for BindingResource. +func (br BindingResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if br.Properties != nil { + objectMap["properties"] = br.Properties + } + if br.SystemData != nil { + objectMap["systemData"] = br.SystemData + } + return json.Marshal(objectMap) +} + +// BindingResourceCollection object that includes an array of Binding resources and a possible link for +// next set +type BindingResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of Binding resources + Value *[]BindingResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// BindingResourceCollectionIterator provides access to a complete listing of BindingResource values. +type BindingResourceCollectionIterator struct { + i int + page BindingResourceCollectionPage +} + +// NextWithContext 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 *BindingResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BindingResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *BindingResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter BindingResourceCollectionIterator) 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 BindingResourceCollectionIterator) Response() BindingResourceCollection { + 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 BindingResourceCollectionIterator) Value() BindingResource { + if !iter.page.NotDone() { + return BindingResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the BindingResourceCollectionIterator type. +func NewBindingResourceCollectionIterator(page BindingResourceCollectionPage) BindingResourceCollectionIterator { + return BindingResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (brc BindingResourceCollection) IsEmpty() bool { + return brc.Value == nil || len(*brc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (brc BindingResourceCollection) hasNextLink() bool { + return brc.NextLink != nil && len(*brc.NextLink) != 0 +} + +// bindingResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (brc BindingResourceCollection) bindingResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !brc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(brc.NextLink))) +} + +// BindingResourceCollectionPage contains a page of BindingResource values. +type BindingResourceCollectionPage struct { + fn func(context.Context, BindingResourceCollection) (BindingResourceCollection, error) + brc BindingResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *BindingResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BindingResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.brc) + if err != nil { + return err + } + page.brc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *BindingResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page BindingResourceCollectionPage) NotDone() bool { + return !page.brc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page BindingResourceCollectionPage) Response() BindingResourceCollection { + return page.brc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page BindingResourceCollectionPage) Values() []BindingResource { + if page.brc.IsEmpty() { + return nil + } + return *page.brc.Value +} + +// Creates a new instance of the BindingResourceCollectionPage type. +func NewBindingResourceCollectionPage(cur BindingResourceCollection, getNextPage func(context.Context, BindingResourceCollection) (BindingResourceCollection, error)) BindingResourceCollectionPage { + return BindingResourceCollectionPage{ + fn: getNextPage, + brc: cur, + } +} + +// BindingResourceProperties binding resource properties payload +type BindingResourceProperties struct { + // ResourceName - READ-ONLY; The name of the bound resource + ResourceName *string `json:"resourceName,omitempty"` + // ResourceType - READ-ONLY; The standard Azure resource type of the bound resource + ResourceType *string `json:"resourceType,omitempty"` + // ResourceID - The Azure resource id of the bound resource + ResourceID *string `json:"resourceId,omitempty"` + // Key - The key of the bound resource + Key *string `json:"key,omitempty"` + // BindingParameters - Binding parameters of the Binding resource + BindingParameters map[string]interface{} `json:"bindingParameters"` + // GeneratedProperties - READ-ONLY; The generated Spring Boot property file for this binding. The secret will be deducted. + GeneratedProperties *string `json:"generatedProperties,omitempty"` + // CreatedAt - READ-ONLY; Creation time of the Binding resource + CreatedAt *string `json:"createdAt,omitempty"` + // UpdatedAt - READ-ONLY; Update time of the Binding resource + UpdatedAt *string `json:"updatedAt,omitempty"` +} + +// MarshalJSON is the custom marshaler for BindingResourceProperties. +func (brp BindingResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if brp.ResourceID != nil { + objectMap["resourceId"] = brp.ResourceID + } + if brp.Key != nil { + objectMap["key"] = brp.Key + } + if brp.BindingParameters != nil { + objectMap["bindingParameters"] = brp.BindingParameters + } + return json.Marshal(objectMap) +} + +// BindingsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type BindingsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(BindingsClient) (BindingResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *BindingsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for BindingsCreateOrUpdateFuture.Result. +func (future *BindingsCreateOrUpdateFuture) result(client BindingsClient) (br BindingResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + br.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.BindingsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if br.Response.Response, err = future.GetResult(sender); err == nil && br.Response.Response.StatusCode != http.StatusNoContent { + br, err = client.CreateOrUpdateResponder(br.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsCreateOrUpdateFuture", "Result", br.Response.Response, "Failure responding to request") + } + } + return +} + +// BindingsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type BindingsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(BindingsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *BindingsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for BindingsDeleteFuture.Result. +func (future *BindingsDeleteFuture) result(client BindingsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.BindingsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// BindingsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type BindingsUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(BindingsClient) (BindingResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *BindingsUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for BindingsUpdateFuture.Result. +func (future *BindingsUpdateFuture) result(client BindingsClient) (br BindingResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + br.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.BindingsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if br.Response.Response, err = future.GetResult(sender); err == nil && br.Response.Response.StatusCode != http.StatusNoContent { + br, err = client.UpdateResponder(br.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BindingsUpdateFuture", "Result", br.Response.Response, "Failure responding to request") + } + } + return +} + +// Build build resource payload +type Build struct { + autorest.Response `json:"-"` + // Properties - Properties of the build resource + Properties *BuildProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for Build. +func (b Build) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if b.Properties != nil { + objectMap["properties"] = b.Properties + } + if b.SystemData != nil { + objectMap["systemData"] = b.SystemData + } + return json.Marshal(objectMap) +} + +// BuildCollection object that includes an array of Build resources and a possible link for next set +type BuildCollection struct { + autorest.Response `json:"-"` + // Value - Collection of Build resources + Value *[]Build `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// BuildCollectionIterator provides access to a complete listing of Build values. +type BuildCollectionIterator struct { + i int + page BuildCollectionPage +} + +// NextWithContext 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 *BuildCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *BuildCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter BuildCollectionIterator) 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 BuildCollectionIterator) Response() BuildCollection { + 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 BuildCollectionIterator) Value() Build { + if !iter.page.NotDone() { + return Build{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the BuildCollectionIterator type. +func NewBuildCollectionIterator(page BuildCollectionPage) BuildCollectionIterator { + return BuildCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (bc BuildCollection) IsEmpty() bool { + return bc.Value == nil || len(*bc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (bc BuildCollection) hasNextLink() bool { + return bc.NextLink != nil && len(*bc.NextLink) != 0 +} + +// buildCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (bc BuildCollection) buildCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !bc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(bc.NextLink))) +} + +// BuildCollectionPage contains a page of Build values. +type BuildCollectionPage struct { + fn func(context.Context, BuildCollection) (BuildCollection, error) + bc BuildCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *BuildCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.bc) + if err != nil { + return err + } + page.bc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *BuildCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page BuildCollectionPage) NotDone() bool { + return !page.bc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page BuildCollectionPage) Response() BuildCollection { + return page.bc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page BuildCollectionPage) Values() []Build { + if page.bc.IsEmpty() { + return nil + } + return *page.bc.Value +} + +// Creates a new instance of the BuildCollectionPage type. +func NewBuildCollectionPage(cur BuildCollection, getNextPage func(context.Context, BuildCollection) (BuildCollection, error)) BuildCollectionPage { + return BuildCollectionPage{ + fn: getNextPage, + bc: cur, + } +} + +// BuilderProperties kPack Builder properties payload +type BuilderProperties struct { + // ProvisioningState - READ-ONLY; Builder provision status. Possible values include: 'BuilderProvisioningStateCreating', 'BuilderProvisioningStateUpdating', 'BuilderProvisioningStateSucceeded', 'BuilderProvisioningStateFailed', 'BuilderProvisioningStateDeleting' + ProvisioningState BuilderProvisioningState `json:"provisioningState,omitempty"` + // Stack - Builder cluster stack property. + Stack *StackProperties `json:"stack,omitempty"` + // BuildpackGroups - Builder buildpack groups. + BuildpackGroups *[]BuildpacksGroupProperties `json:"buildpackGroups,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuilderProperties. +func (bp BuilderProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bp.Stack != nil { + objectMap["stack"] = bp.Stack + } + if bp.BuildpackGroups != nil { + objectMap["buildpackGroups"] = bp.BuildpackGroups + } + return json.Marshal(objectMap) +} + +// BuilderResource kPack Builder resource +type BuilderResource struct { + autorest.Response `json:"-"` + // Properties - Property of the Builder resource. + Properties *BuilderProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuilderResource. +func (br BuilderResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if br.Properties != nil { + objectMap["properties"] = br.Properties + } + if br.SystemData != nil { + objectMap["systemData"] = br.SystemData + } + return json.Marshal(objectMap) +} + +// BuilderResourceCollection object that includes an array of Builder resources and a possible link for +// next set +type BuilderResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of Builder resources + Value *[]BuilderResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// BuilderResourceCollectionIterator provides access to a complete listing of BuilderResource values. +type BuilderResourceCollectionIterator struct { + i int + page BuilderResourceCollectionPage +} + +// NextWithContext 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 *BuilderResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuilderResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *BuilderResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter BuilderResourceCollectionIterator) 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 BuilderResourceCollectionIterator) Response() BuilderResourceCollection { + 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 BuilderResourceCollectionIterator) Value() BuilderResource { + if !iter.page.NotDone() { + return BuilderResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the BuilderResourceCollectionIterator type. +func NewBuilderResourceCollectionIterator(page BuilderResourceCollectionPage) BuilderResourceCollectionIterator { + return BuilderResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (brc BuilderResourceCollection) IsEmpty() bool { + return brc.Value == nil || len(*brc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (brc BuilderResourceCollection) hasNextLink() bool { + return brc.NextLink != nil && len(*brc.NextLink) != 0 +} + +// builderResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (brc BuilderResourceCollection) builderResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !brc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(brc.NextLink))) +} + +// BuilderResourceCollectionPage contains a page of BuilderResource values. +type BuilderResourceCollectionPage struct { + fn func(context.Context, BuilderResourceCollection) (BuilderResourceCollection, error) + brc BuilderResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *BuilderResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuilderResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.brc) + if err != nil { + return err + } + page.brc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *BuilderResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page BuilderResourceCollectionPage) NotDone() bool { + return !page.brc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page BuilderResourceCollectionPage) Response() BuilderResourceCollection { + return page.brc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page BuilderResourceCollectionPage) Values() []BuilderResource { + if page.brc.IsEmpty() { + return nil + } + return *page.brc.Value +} + +// Creates a new instance of the BuilderResourceCollectionPage type. +func NewBuilderResourceCollectionPage(cur BuilderResourceCollection, getNextPage func(context.Context, BuilderResourceCollection) (BuilderResourceCollection, error)) BuilderResourceCollectionPage { + return BuilderResourceCollectionPage{ + fn: getNextPage, + brc: cur, + } +} + +// BuildpackBindingCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type BuildpackBindingCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(BuildpackBindingClient) (BuildpackBindingResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *BuildpackBindingCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for BuildpackBindingCreateOrUpdateFuture.Result. +func (future *BuildpackBindingCreateOrUpdateFuture) result(client BuildpackBindingClient) (bbr BuildpackBindingResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + bbr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.BuildpackBindingCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if bbr.Response.Response, err = future.GetResult(sender); err == nil && bbr.Response.Response.StatusCode != http.StatusNoContent { + bbr, err = client.CreateOrUpdateResponder(bbr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingCreateOrUpdateFuture", "Result", bbr.Response.Response, "Failure responding to request") + } + } + return +} + +// BuildpackBindingDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type BuildpackBindingDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(BuildpackBindingClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *BuildpackBindingDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for BuildpackBindingDeleteFuture.Result. +func (future *BuildpackBindingDeleteFuture) result(client BuildpackBindingClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.BuildpackBindingDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// BuildpackBindingLaunchProperties buildpack Binding Launch Properties +type BuildpackBindingLaunchProperties struct { + // Properties - Non-sensitive properties for launchProperties + Properties map[string]*string `json:"properties"` + // Secrets - Sensitive properties for launchProperties + Secrets map[string]*string `json:"secrets"` +} + +// MarshalJSON is the custom marshaler for BuildpackBindingLaunchProperties. +func (bblp BuildpackBindingLaunchProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bblp.Properties != nil { + objectMap["properties"] = bblp.Properties + } + if bblp.Secrets != nil { + objectMap["secrets"] = bblp.Secrets + } + return json.Marshal(objectMap) +} + +// BuildpackBindingProperties properties of a buildpack binding +type BuildpackBindingProperties struct { + // BindingType - Buildpack Binding Type. Possible values include: 'BindingTypeApplicationInsights', 'BindingTypeApacheSkyWalking', 'BindingTypeAppDynamics', 'BindingTypeDynatrace', 'BindingTypeNewRelic', 'BindingTypeElasticAPM' + BindingType BindingType `json:"bindingType,omitempty"` + // ProvisioningState - READ-ONLY; State of the Buildpack Binding. Possible values include: 'BuildpackBindingProvisioningStateCreating', 'BuildpackBindingProvisioningStateUpdating', 'BuildpackBindingProvisioningStateSucceeded', 'BuildpackBindingProvisioningStateFailed', 'BuildpackBindingProvisioningStateDeleting' + ProvisioningState BuildpackBindingProvisioningState `json:"provisioningState,omitempty"` + // LaunchProperties - The object describes the buildpack binding launch properties + LaunchProperties *BuildpackBindingLaunchProperties `json:"launchProperties,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildpackBindingProperties. +func (bbp BuildpackBindingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bbp.BindingType != "" { + objectMap["bindingType"] = bbp.BindingType + } + if bbp.LaunchProperties != nil { + objectMap["launchProperties"] = bbp.LaunchProperties + } + return json.Marshal(objectMap) +} + +// BuildpackBindingResource buildpack Binding Resource object +type BuildpackBindingResource struct { + autorest.Response `json:"-"` + // Properties - Properties of a buildpack binding + Properties *BuildpackBindingProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildpackBindingResource. +func (bbr BuildpackBindingResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bbr.Properties != nil { + objectMap["properties"] = bbr.Properties + } + if bbr.SystemData != nil { + objectMap["systemData"] = bbr.SystemData + } + return json.Marshal(objectMap) +} + +// BuildpackBindingResourceCollection object that includes an array of BuildpackBinding resources and a +// possible link for next set +type BuildpackBindingResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of BuildpackBinding resources + Value *[]BuildpackBindingResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// BuildpackBindingResourceCollectionIterator provides access to a complete listing of +// BuildpackBindingResource values. +type BuildpackBindingResourceCollectionIterator struct { + i int + page BuildpackBindingResourceCollectionPage +} + +// NextWithContext 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 *BuildpackBindingResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *BuildpackBindingResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter BuildpackBindingResourceCollectionIterator) 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 BuildpackBindingResourceCollectionIterator) Response() BuildpackBindingResourceCollection { + 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 BuildpackBindingResourceCollectionIterator) Value() BuildpackBindingResource { + if !iter.page.NotDone() { + return BuildpackBindingResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the BuildpackBindingResourceCollectionIterator type. +func NewBuildpackBindingResourceCollectionIterator(page BuildpackBindingResourceCollectionPage) BuildpackBindingResourceCollectionIterator { + return BuildpackBindingResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (bbrc BuildpackBindingResourceCollection) IsEmpty() bool { + return bbrc.Value == nil || len(*bbrc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (bbrc BuildpackBindingResourceCollection) hasNextLink() bool { + return bbrc.NextLink != nil && len(*bbrc.NextLink) != 0 +} + +// buildpackBindingResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (bbrc BuildpackBindingResourceCollection) buildpackBindingResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !bbrc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(bbrc.NextLink))) +} + +// BuildpackBindingResourceCollectionPage contains a page of BuildpackBindingResource values. +type BuildpackBindingResourceCollectionPage struct { + fn func(context.Context, BuildpackBindingResourceCollection) (BuildpackBindingResourceCollection, error) + bbrc BuildpackBindingResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *BuildpackBindingResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.bbrc) + if err != nil { + return err + } + page.bbrc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *BuildpackBindingResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page BuildpackBindingResourceCollectionPage) NotDone() bool { + return !page.bbrc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page BuildpackBindingResourceCollectionPage) Response() BuildpackBindingResourceCollection { + return page.bbrc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page BuildpackBindingResourceCollectionPage) Values() []BuildpackBindingResource { + if page.bbrc.IsEmpty() { + return nil + } + return *page.bbrc.Value +} + +// Creates a new instance of the BuildpackBindingResourceCollectionPage type. +func NewBuildpackBindingResourceCollectionPage(cur BuildpackBindingResourceCollection, getNextPage func(context.Context, BuildpackBindingResourceCollection) (BuildpackBindingResourceCollection, error)) BuildpackBindingResourceCollectionPage { + return BuildpackBindingResourceCollectionPage{ + fn: getNextPage, + bbrc: cur, + } +} + +// BuildpackProperties buildpack properties payload +type BuildpackProperties struct { + // ID - Id of the buildpack + ID *string `json:"id,omitempty"` +} + +// BuildpacksGroupProperties buildpack group properties of the Builder +type BuildpacksGroupProperties struct { + // Name - Buildpack group name + Name *string `json:"name,omitempty"` + // Buildpacks - Buildpacks in the buildpack group + Buildpacks *[]BuildpackProperties `json:"buildpacks,omitempty"` +} + +// BuildProperties build resource properties payload +type BuildProperties struct { + // RelativePath - The relative path of source code + RelativePath *string `json:"relativePath,omitempty"` + // Builder - The resource id of builder to build the source code + Builder *string `json:"builder,omitempty"` + // AgentPool - The resource id of agent pool + AgentPool *string `json:"agentPool,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the KPack build result. Possible values include: 'BuildProvisioningStateCreating', 'BuildProvisioningStateUpdating', 'BuildProvisioningStateSucceeded', 'BuildProvisioningStateFailed', 'BuildProvisioningStateDeleting' + ProvisioningState BuildProvisioningState `json:"provisioningState,omitempty"` + // Env - The environment variables for this build + Env map[string]*string `json:"env"` + // TriggeredBuildResult - The build result triggered by this build + TriggeredBuildResult *TriggeredBuildResult `json:"triggeredBuildResult,omitempty"` + // ResourceRequests - The customized build resource for this build + ResourceRequests *BuildResourceRequests `json:"resourceRequests,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildProperties. +func (bp BuildProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bp.RelativePath != nil { + objectMap["relativePath"] = bp.RelativePath + } + if bp.Builder != nil { + objectMap["builder"] = bp.Builder + } + if bp.AgentPool != nil { + objectMap["agentPool"] = bp.AgentPool + } + if bp.Env != nil { + objectMap["env"] = bp.Env + } + if bp.TriggeredBuildResult != nil { + objectMap["triggeredBuildResult"] = bp.TriggeredBuildResult + } + if bp.ResourceRequests != nil { + objectMap["resourceRequests"] = bp.ResourceRequests + } + return json.Marshal(objectMap) +} + +// BuildResourceRequests resource request payload of Build Resource. +type BuildResourceRequests struct { + // CPU - Optional Cpu allocated to the build resource. 1 core can be represented by 1 or 1000m. + // The default value is 1, this should not exceed build service agent pool cpu size. + CPU *string `json:"cpu,omitempty"` + // Memory - Optional Memory allocated to the build resource. 1 GB can be represented by 1Gi or 1024Mi. + // The default value is 2Gi, this should not exceed build service agent pool memory size. + Memory *string `json:"memory,omitempty"` +} + +// BuildResult build result resource payload +type BuildResult struct { + autorest.Response `json:"-"` + // Properties - Properties of the build result resource + Properties *BuildResultProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildResult. +func (br BuildResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if br.Properties != nil { + objectMap["properties"] = br.Properties + } + if br.SystemData != nil { + objectMap["systemData"] = br.SystemData + } + return json.Marshal(objectMap) +} + +// BuildResultCollection object that includes an array of Build result resources and a possible link for +// next set +type BuildResultCollection struct { + autorest.Response `json:"-"` + // Value - Collection of Build result resources + Value *[]BuildResult `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// BuildResultCollectionIterator provides access to a complete listing of BuildResult values. +type BuildResultCollectionIterator struct { + i int + page BuildResultCollectionPage +} + +// NextWithContext 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 *BuildResultCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildResultCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *BuildResultCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter BuildResultCollectionIterator) 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 BuildResultCollectionIterator) Response() BuildResultCollection { + 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 BuildResultCollectionIterator) Value() BuildResult { + if !iter.page.NotDone() { + return BuildResult{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the BuildResultCollectionIterator type. +func NewBuildResultCollectionIterator(page BuildResultCollectionPage) BuildResultCollectionIterator { + return BuildResultCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (brc BuildResultCollection) IsEmpty() bool { + return brc.Value == nil || len(*brc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (brc BuildResultCollection) hasNextLink() bool { + return brc.NextLink != nil && len(*brc.NextLink) != 0 +} + +// buildResultCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (brc BuildResultCollection) buildResultCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !brc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(brc.NextLink))) +} + +// BuildResultCollectionPage contains a page of BuildResult values. +type BuildResultCollectionPage struct { + fn func(context.Context, BuildResultCollection) (BuildResultCollection, error) + brc BuildResultCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *BuildResultCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildResultCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.brc) + if err != nil { + return err + } + page.brc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *BuildResultCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page BuildResultCollectionPage) NotDone() bool { + return !page.brc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page BuildResultCollectionPage) Response() BuildResultCollection { + return page.brc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page BuildResultCollectionPage) Values() []BuildResult { + if page.brc.IsEmpty() { + return nil + } + return *page.brc.Value +} + +// Creates a new instance of the BuildResultCollectionPage type. +func NewBuildResultCollectionPage(cur BuildResultCollection, getNextPage func(context.Context, BuildResultCollection) (BuildResultCollection, error)) BuildResultCollectionPage { + return BuildResultCollectionPage{ + fn: getNextPage, + brc: cur, + } +} + +// BuildResultLog build result log resource properties payload +type BuildResultLog struct { + autorest.Response `json:"-"` + // BlobURL - The public download URL of this build result log + BlobURL *string `json:"blobUrl,omitempty"` +} + +// BuildResultProperties build result resource properties payload +type BuildResultProperties struct { + // Name - The name of this build result + Name *string `json:"name,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the KPack build result. Possible values include: 'BuildResultProvisioningStateQueuing', 'BuildResultProvisioningStateBuilding', 'BuildResultProvisioningStateSucceeded', 'BuildResultProvisioningStateFailed', 'BuildResultProvisioningStateDeleting' + ProvisioningState BuildResultProvisioningState `json:"provisioningState,omitempty"` + // BuildPodName - The build pod name which can be used to get the build log streaming. + BuildPodName *string `json:"buildPodName,omitempty"` + // BuildStages - READ-ONLY; All of the build stage (init-container and container) resources in build pod. + BuildStages *[]BuildStageProperties `json:"buildStages,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildResultProperties. +func (brp BuildResultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if brp.Name != nil { + objectMap["name"] = brp.Name + } + if brp.BuildPodName != nil { + objectMap["buildPodName"] = brp.BuildPodName + } + return json.Marshal(objectMap) +} + +// BuildResultUserSourceInfo reference to a build result +type BuildResultUserSourceInfo struct { + // BuildResultID - Resource id of an existing succeeded build result under the same Spring instance. + BuildResultID *string `json:"buildResultId,omitempty"` + // Version - Version of the source + Version *string `json:"version,omitempty"` + // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' + Type TypeBasicUserSourceInfo `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) MarshalJSON() ([]byte, error) { + brusi.Type = TypeBasicUserSourceInfoTypeBuildResult + objectMap := make(map[string]interface{}) + if brusi.BuildResultID != nil { + objectMap["buildResultId"] = brusi.BuildResultID + } + if brusi.Version != nil { + objectMap["version"] = brusi.Version + } + if brusi.Type != "" { + objectMap["type"] = brusi.Type + } + return json.Marshal(objectMap) +} + +// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { + return &brusi, true +} + +// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { + return nil, false +} + +// AsUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { + return nil, false +} + +// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. +func (brusi BuildResultUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { + return &brusi, true +} + +// BuildService build service resource payload +type BuildService struct { + autorest.Response `json:"-"` + // Properties - Properties of the build resource + Properties *BuildServiceProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildService. +func (bs BuildService) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bs.Properties != nil { + objectMap["properties"] = bs.Properties + } + if bs.SystemData != nil { + objectMap["systemData"] = bs.SystemData + } + return json.Marshal(objectMap) +} + +// BuildServiceAgentPoolProperties build service agent pool properties +type BuildServiceAgentPoolProperties struct { + // ProvisioningState - READ-ONLY; Provisioning state of the build service agent pool + ProvisioningState *string `json:"provisioningState,omitempty"` + // PoolSize - build service agent pool size properties + PoolSize *BuildServiceAgentPoolSizeProperties `json:"poolSize,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildServiceAgentPoolProperties. +func (bsapp BuildServiceAgentPoolProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bsapp.PoolSize != nil { + objectMap["poolSize"] = bsapp.PoolSize + } + return json.Marshal(objectMap) +} + +// BuildServiceAgentPoolResource the build service agent pool resource +type BuildServiceAgentPoolResource struct { + autorest.Response `json:"-"` + // Properties - build service agent pool properties + Properties *BuildServiceAgentPoolProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildServiceAgentPoolResource. +func (bsapr BuildServiceAgentPoolResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bsapr.Properties != nil { + objectMap["properties"] = bsapr.Properties + } + if bsapr.SystemData != nil { + objectMap["systemData"] = bsapr.SystemData + } + return json.Marshal(objectMap) +} + +// BuildServiceAgentPoolResourceCollection object that includes an array of build service agent pool +// resources and a possible link for next set +type BuildServiceAgentPoolResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of build service agent pool resource + Value *[]BuildServiceAgentPoolResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// BuildServiceAgentPoolResourceCollectionIterator provides access to a complete listing of +// BuildServiceAgentPoolResource values. +type BuildServiceAgentPoolResourceCollectionIterator struct { + i int + page BuildServiceAgentPoolResourceCollectionPage +} + +// NextWithContext 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 *BuildServiceAgentPoolResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *BuildServiceAgentPoolResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter BuildServiceAgentPoolResourceCollectionIterator) 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 BuildServiceAgentPoolResourceCollectionIterator) Response() BuildServiceAgentPoolResourceCollection { + 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 BuildServiceAgentPoolResourceCollectionIterator) Value() BuildServiceAgentPoolResource { + if !iter.page.NotDone() { + return BuildServiceAgentPoolResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the BuildServiceAgentPoolResourceCollectionIterator type. +func NewBuildServiceAgentPoolResourceCollectionIterator(page BuildServiceAgentPoolResourceCollectionPage) BuildServiceAgentPoolResourceCollectionIterator { + return BuildServiceAgentPoolResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (bsaprc BuildServiceAgentPoolResourceCollection) IsEmpty() bool { + return bsaprc.Value == nil || len(*bsaprc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (bsaprc BuildServiceAgentPoolResourceCollection) hasNextLink() bool { + return bsaprc.NextLink != nil && len(*bsaprc.NextLink) != 0 +} + +// buildServiceAgentPoolResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (bsaprc BuildServiceAgentPoolResourceCollection) buildServiceAgentPoolResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !bsaprc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(bsaprc.NextLink))) +} + +// BuildServiceAgentPoolResourceCollectionPage contains a page of BuildServiceAgentPoolResource values. +type BuildServiceAgentPoolResourceCollectionPage struct { + fn func(context.Context, BuildServiceAgentPoolResourceCollection) (BuildServiceAgentPoolResourceCollection, error) + bsaprc BuildServiceAgentPoolResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *BuildServiceAgentPoolResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.bsaprc) + if err != nil { + return err + } + page.bsaprc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *BuildServiceAgentPoolResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page BuildServiceAgentPoolResourceCollectionPage) NotDone() bool { + return !page.bsaprc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page BuildServiceAgentPoolResourceCollectionPage) Response() BuildServiceAgentPoolResourceCollection { + return page.bsaprc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page BuildServiceAgentPoolResourceCollectionPage) Values() []BuildServiceAgentPoolResource { + if page.bsaprc.IsEmpty() { + return nil + } + return *page.bsaprc.Value +} + +// Creates a new instance of the BuildServiceAgentPoolResourceCollectionPage type. +func NewBuildServiceAgentPoolResourceCollectionPage(cur BuildServiceAgentPoolResourceCollection, getNextPage func(context.Context, BuildServiceAgentPoolResourceCollection) (BuildServiceAgentPoolResourceCollection, error)) BuildServiceAgentPoolResourceCollectionPage { + return BuildServiceAgentPoolResourceCollectionPage{ + fn: getNextPage, + bsaprc: cur, + } +} + +// BuildServiceAgentPoolSizeProperties build service agent pool size properties +type BuildServiceAgentPoolSizeProperties struct { + // Name - The name of build service agent pool size + Name *string `json:"name,omitempty"` + // CPU - READ-ONLY; The cpu property of build service agent pool size + CPU *string `json:"cpu,omitempty"` + // Memory - READ-ONLY; The memory property of build service agent pool size + Memory *string `json:"memory,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildServiceAgentPoolSizeProperties. +func (bsapsp BuildServiceAgentPoolSizeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bsapsp.Name != nil { + objectMap["name"] = bsapsp.Name + } + return json.Marshal(objectMap) +} + +// BuildServiceAgentPoolUpdatePutFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type BuildServiceAgentPoolUpdatePutFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(BuildServiceAgentPoolClient) (BuildServiceAgentPoolResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *BuildServiceAgentPoolUpdatePutFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for BuildServiceAgentPoolUpdatePutFuture.Result. +func (future *BuildServiceAgentPoolUpdatePutFuture) result(client BuildServiceAgentPoolClient) (bsapr BuildServiceAgentPoolResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolUpdatePutFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + bsapr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.BuildServiceAgentPoolUpdatePutFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if bsapr.Response.Response, err = future.GetResult(sender); err == nil && bsapr.Response.Response.StatusCode != http.StatusNoContent { + bsapr, err = client.UpdatePutResponder(bsapr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolUpdatePutFuture", "Result", bsapr.Response.Response, "Failure responding to request") + } + } + return +} + +// BuildServiceBuilderCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type BuildServiceBuilderCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(BuildServiceBuilderClient) (BuilderResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *BuildServiceBuilderCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for BuildServiceBuilderCreateOrUpdateFuture.Result. +func (future *BuildServiceBuilderCreateOrUpdateFuture) result(client BuildServiceBuilderClient) (br BuilderResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + br.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.BuildServiceBuilderCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if br.Response.Response, err = future.GetResult(sender); err == nil && br.Response.Response.StatusCode != http.StatusNoContent { + br, err = client.CreateOrUpdateResponder(br.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderCreateOrUpdateFuture", "Result", br.Response.Response, "Failure responding to request") + } + } + return +} + +// BuildServiceBuilderDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type BuildServiceBuilderDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(BuildServiceBuilderClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *BuildServiceBuilderDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for BuildServiceBuilderDeleteFuture.Result. +func (future *BuildServiceBuilderDeleteFuture) result(client BuildServiceBuilderClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.BuildServiceBuilderDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// BuildServiceCollection object that includes an array of Build service resources and a possible link for +// next set +type BuildServiceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of Build service resources + Value *[]BuildService `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// BuildServiceCollectionIterator provides access to a complete listing of BuildService values. +type BuildServiceCollectionIterator struct { + i int + page BuildServiceCollectionPage +} + +// NextWithContext 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 *BuildServiceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *BuildServiceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter BuildServiceCollectionIterator) 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 BuildServiceCollectionIterator) Response() BuildServiceCollection { + 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 BuildServiceCollectionIterator) Value() BuildService { + if !iter.page.NotDone() { + return BuildService{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the BuildServiceCollectionIterator type. +func NewBuildServiceCollectionIterator(page BuildServiceCollectionPage) BuildServiceCollectionIterator { + return BuildServiceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (bsc BuildServiceCollection) IsEmpty() bool { + return bsc.Value == nil || len(*bsc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (bsc BuildServiceCollection) hasNextLink() bool { + return bsc.NextLink != nil && len(*bsc.NextLink) != 0 +} + +// buildServiceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (bsc BuildServiceCollection) buildServiceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !bsc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(bsc.NextLink))) +} + +// BuildServiceCollectionPage contains a page of BuildService values. +type BuildServiceCollectionPage struct { + fn func(context.Context, BuildServiceCollection) (BuildServiceCollection, error) + bsc BuildServiceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *BuildServiceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.bsc) + if err != nil { + return err + } + page.bsc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *BuildServiceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page BuildServiceCollectionPage) NotDone() bool { + return !page.bsc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page BuildServiceCollectionPage) Response() BuildServiceCollection { + return page.bsc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page BuildServiceCollectionPage) Values() []BuildService { + if page.bsc.IsEmpty() { + return nil + } + return *page.bsc.Value +} + +// Creates a new instance of the BuildServiceCollectionPage type. +func NewBuildServiceCollectionPage(cur BuildServiceCollection, getNextPage func(context.Context, BuildServiceCollection) (BuildServiceCollection, error)) BuildServiceCollectionPage { + return BuildServiceCollectionPage{ + fn: getNextPage, + bsc: cur, + } +} + +// BuildServiceProperties build service resource properties payload +type BuildServiceProperties struct { + // KPackVersion - The installed KPack version in this build service. + KPackVersion *string `json:"kPackVersion,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the KPack build result. Possible values include: 'BuildServiceProvisioningStateCreating', 'BuildServiceProvisioningStateUpdating', 'BuildServiceProvisioningStateSucceeded', 'BuildServiceProvisioningStateFailed', 'BuildServiceProvisioningStateDeleting' + ProvisioningState BuildServiceProvisioningState `json:"provisioningState,omitempty"` + // ResourceRequests - The runtime resource configuration of this build service. + ResourceRequests *BuildServicePropertiesResourceRequests `json:"resourceRequests,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildServiceProperties. +func (bsp BuildServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bsp.KPackVersion != nil { + objectMap["kPackVersion"] = bsp.KPackVersion + } + if bsp.ResourceRequests != nil { + objectMap["resourceRequests"] = bsp.ResourceRequests + } + return json.Marshal(objectMap) +} + +// BuildServicePropertiesResourceRequests the runtime resource configuration of this build service. +type BuildServicePropertiesResourceRequests struct { + // CPU - READ-ONLY; vCPU allocated to the entire build service node pool. + CPU *string `json:"cpu,omitempty"` + // Memory - READ-ONLY; Memory allocated to the entire build service node pool. + Memory *string `json:"memory,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildServicePropertiesResourceRequests. +func (bspR BuildServicePropertiesResourceRequests) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// BuildStageProperties the build stage (init-container and container) resources in build pod. +type BuildStageProperties struct { + // Name - READ-ONLY; The name of this build stage resource. + Name *string `json:"name,omitempty"` + // Status - READ-ONLY; The provisioning state of this build stage resource. Possible values include: 'KPackBuildStageProvisioningStateNotStarted', 'KPackBuildStageProvisioningStateRunning', 'KPackBuildStageProvisioningStateSucceeded', 'KPackBuildStageProvisioningStateFailed' + Status KPackBuildStageProvisioningState `json:"status,omitempty"` +} + +// MarshalJSON is the custom marshaler for BuildStageProperties. +func (bsp BuildStageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// BasicCertificateProperties certificate resource payload. +type BasicCertificateProperties interface { + AsKeyVaultCertificateProperties() (*KeyVaultCertificateProperties, bool) + AsContentCertificateProperties() (*ContentCertificateProperties, bool) + AsCertificateProperties() (*CertificateProperties, bool) +} + +// CertificateProperties certificate resource payload. +type CertificateProperties struct { + // Thumbprint - READ-ONLY; The thumbprint of certificate. + Thumbprint *string `json:"thumbprint,omitempty"` + // Issuer - READ-ONLY; The issuer of certificate. + Issuer *string `json:"issuer,omitempty"` + // IssuedDate - READ-ONLY; The issue date of certificate. + IssuedDate *string `json:"issuedDate,omitempty"` + // ExpirationDate - READ-ONLY; The expiration date of certificate. + ExpirationDate *string `json:"expirationDate,omitempty"` + // ActivateDate - READ-ONLY; The activate date of certificate. + ActivateDate *string `json:"activateDate,omitempty"` + // SubjectName - READ-ONLY; The subject name of certificate. + SubjectName *string `json:"subjectName,omitempty"` + // DNSNames - READ-ONLY; The domain list of certificate. + DNSNames *[]string `json:"dnsNames,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the Certificate. Possible values include: 'CertificateResourceProvisioningStateCreating', 'CertificateResourceProvisioningStateUpdating', 'CertificateResourceProvisioningStateSucceeded', 'CertificateResourceProvisioningStateFailed', 'CertificateResourceProvisioningStateDeleting' + ProvisioningState CertificateResourceProvisioningState `json:"provisioningState,omitempty"` + // Type - Possible values include: 'TypeBasicCertificatePropertiesTypeCertificateProperties', 'TypeBasicCertificatePropertiesTypeKeyVaultCertificate', 'TypeBasicCertificatePropertiesTypeContentCertificate' + Type TypeBasicCertificateProperties `json:"type,omitempty"` +} + +func unmarshalBasicCertificateProperties(body []byte) (BasicCertificateProperties, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["type"] { + case string(TypeBasicCertificatePropertiesTypeKeyVaultCertificate): + var kvcp KeyVaultCertificateProperties + err := json.Unmarshal(body, &kvcp) + return kvcp, err + case string(TypeBasicCertificatePropertiesTypeContentCertificate): + var ccp ContentCertificateProperties + err := json.Unmarshal(body, &ccp) + return ccp, err + default: + var cp CertificateProperties + err := json.Unmarshal(body, &cp) + return cp, err + } +} +func unmarshalBasicCertificatePropertiesArray(body []byte) ([]BasicCertificateProperties, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + cpArray := make([]BasicCertificateProperties, len(rawMessages)) + + for index, rawMessage := range rawMessages { + cp, err := unmarshalBasicCertificateProperties(*rawMessage) + if err != nil { + return nil, err + } + cpArray[index] = cp + } + return cpArray, nil +} + +// MarshalJSON is the custom marshaler for CertificateProperties. +func (cp CertificateProperties) MarshalJSON() ([]byte, error) { + cp.Type = TypeBasicCertificatePropertiesTypeCertificateProperties + objectMap := make(map[string]interface{}) + if cp.Type != "" { + objectMap["type"] = cp.Type + } + return json.Marshal(objectMap) +} + +// AsKeyVaultCertificateProperties is the BasicCertificateProperties implementation for CertificateProperties. +func (cp CertificateProperties) AsKeyVaultCertificateProperties() (*KeyVaultCertificateProperties, bool) { + return nil, false +} + +// AsContentCertificateProperties is the BasicCertificateProperties implementation for CertificateProperties. +func (cp CertificateProperties) AsContentCertificateProperties() (*ContentCertificateProperties, bool) { + return nil, false +} + +// AsCertificateProperties is the BasicCertificateProperties implementation for CertificateProperties. +func (cp CertificateProperties) AsCertificateProperties() (*CertificateProperties, bool) { + return &cp, true +} + +// AsBasicCertificateProperties is the BasicCertificateProperties implementation for CertificateProperties. +func (cp CertificateProperties) AsBasicCertificateProperties() (BasicCertificateProperties, bool) { + return &cp, true +} + +// CertificateResource certificate resource payload. +type CertificateResource struct { + autorest.Response `json:"-"` + // Properties - Properties of the certificate resource payload. + Properties BasicCertificateProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for CertificateResource. +func (cr CertificateResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + objectMap["properties"] = cr.Properties + if cr.SystemData != nil { + objectMap["systemData"] = cr.SystemData + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for CertificateResource struct. +func (cr *CertificateResource) 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 { + properties, err := unmarshalBasicCertificateProperties(*v) + if err != nil { + return err + } + cr.Properties = properties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + cr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + cr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + cr.Type = &typeVar + } + case "systemData": + if v != nil { + var systemData SystemData + err = json.Unmarshal(*v, &systemData) + if err != nil { + return err + } + cr.SystemData = &systemData + } + } + } + + return nil +} + +// CertificateResourceCollection collection compose of certificate resources list and a possible link for +// next page. +type CertificateResourceCollection struct { + autorest.Response `json:"-"` + // Value - The certificate resources list. + Value *[]CertificateResource `json:"value,omitempty"` + // NextLink - The link to next page of certificate list. + NextLink *string `json:"nextLink,omitempty"` +} + +// CertificateResourceCollectionIterator provides access to a complete listing of CertificateResource +// values. +type CertificateResourceCollectionIterator struct { + i int + page CertificateResourceCollectionPage +} + +// NextWithContext 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 *CertificateResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CertificateResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *CertificateResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter CertificateResourceCollectionIterator) 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 CertificateResourceCollectionIterator) Response() CertificateResourceCollection { + 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 CertificateResourceCollectionIterator) Value() CertificateResource { + if !iter.page.NotDone() { + return CertificateResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the CertificateResourceCollectionIterator type. +func NewCertificateResourceCollectionIterator(page CertificateResourceCollectionPage) CertificateResourceCollectionIterator { + return CertificateResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (crc CertificateResourceCollection) IsEmpty() bool { + return crc.Value == nil || len(*crc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (crc CertificateResourceCollection) hasNextLink() bool { + return crc.NextLink != nil && len(*crc.NextLink) != 0 +} + +// certificateResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (crc CertificateResourceCollection) certificateResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !crc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(crc.NextLink))) +} + +// CertificateResourceCollectionPage contains a page of CertificateResource values. +type CertificateResourceCollectionPage struct { + fn func(context.Context, CertificateResourceCollection) (CertificateResourceCollection, error) + crc CertificateResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *CertificateResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CertificateResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.crc) + if err != nil { + return err + } + page.crc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *CertificateResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page CertificateResourceCollectionPage) NotDone() bool { + return !page.crc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page CertificateResourceCollectionPage) Response() CertificateResourceCollection { + return page.crc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page CertificateResourceCollectionPage) Values() []CertificateResource { + if page.crc.IsEmpty() { + return nil + } + return *page.crc.Value +} + +// Creates a new instance of the CertificateResourceCollectionPage type. +func NewCertificateResourceCollectionPage(cur CertificateResourceCollection, getNextPage func(context.Context, CertificateResourceCollection) (CertificateResourceCollection, error)) CertificateResourceCollectionPage { + return CertificateResourceCollectionPage{ + fn: getNextPage, + crc: cur, + } +} + +// CertificatesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type CertificatesCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(CertificatesClient) (CertificateResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *CertificatesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for CertificatesCreateOrUpdateFuture.Result. +func (future *CertificatesCreateOrUpdateFuture) result(client CertificatesClient) (cr CertificateResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + cr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.CertificatesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if cr.Response.Response, err = future.GetResult(sender); err == nil && cr.Response.Response.StatusCode != http.StatusNoContent { + cr, err = client.CreateOrUpdateResponder(cr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesCreateOrUpdateFuture", "Result", cr.Response.Response, "Failure responding to request") + } + } + return +} + +// CertificatesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type CertificatesDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(CertificatesClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *CertificatesDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for CertificatesDeleteFuture.Result. +func (future *CertificatesDeleteFuture) result(client CertificatesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CertificatesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.CertificatesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// CloudError an error response from the service. +type CloudError struct { + // Error - An error response from the service. + Error *CloudErrorBody `json:"error,omitempty"` +} + +// CloudErrorBody an error response from the service. +type CloudErrorBody struct { + // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + // Message - A message describing the error, intended to be suitable for display in a user interface. + Message *string `json:"message,omitempty"` + // Target - The target of the particular error. For example, the name of the property in error. + Target *string `json:"target,omitempty"` + // Details - A list of additional details about the error. + Details *[]CloudErrorBody `json:"details,omitempty"` +} + +// ClusterResourceProperties service properties payload +type ClusterResourceProperties struct { + // ProvisioningState - READ-ONLY; Provisioning state of the Service. Possible values include: 'ProvisioningStateCreating', 'ProvisioningStateUpdating', 'ProvisioningStateStarting', 'ProvisioningStateStopping', 'ProvisioningStateDeleting', 'ProvisioningStateDeleted', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving', 'ProvisioningStateMoved', 'ProvisioningStateMoveFailed' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // NetworkProfile - Network profile of the Service + NetworkProfile *NetworkProfile `json:"networkProfile,omitempty"` + // VnetAddons - Additional Service settings in vnet injection instance + VnetAddons *ServiceVNetAddons `json:"vnetAddons,omitempty"` + // Version - READ-ONLY; Version of the Service + Version *int32 `json:"version,omitempty"` + // ServiceID - READ-ONLY; ServiceInstanceEntity GUID which uniquely identifies a created resource + ServiceID *string `json:"serviceId,omitempty"` + // PowerState - READ-ONLY; Power state of the Service. Possible values include: 'PowerStateRunning', 'PowerStateStopped' + PowerState PowerState `json:"powerState,omitempty"` + ZoneRedundant *bool `json:"zoneRedundant,omitempty"` + // Fqdn - READ-ONLY; Fully qualified dns name of the service instance + Fqdn *string `json:"fqdn,omitempty"` + // MarketplaceResource - Purchasing 3rd party product of the Service resource. + MarketplaceResource *MarketplaceResource `json:"marketplaceResource,omitempty"` +} + +// MarshalJSON is the custom marshaler for ClusterResourceProperties. +func (crp ClusterResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if crp.NetworkProfile != nil { + objectMap["networkProfile"] = crp.NetworkProfile + } + if crp.VnetAddons != nil { + objectMap["vnetAddons"] = crp.VnetAddons + } + if crp.ZoneRedundant != nil { + objectMap["zoneRedundant"] = crp.ZoneRedundant + } + if crp.MarketplaceResource != nil { + objectMap["marketplaceResource"] = crp.MarketplaceResource + } + return json.Marshal(objectMap) +} + +// ConfigServerGitProperty property of git. +type ConfigServerGitProperty struct { + // Repositories - Repositories of git. + Repositories *[]GitPatternRepository `json:"repositories,omitempty"` + // URI - URI of the repository + URI *string `json:"uri,omitempty"` + // Label - Label of the repository + Label *string `json:"label,omitempty"` + // SearchPaths - Searching path of the repository + SearchPaths *[]string `json:"searchPaths,omitempty"` + // Username - Username of git repository basic auth. + Username *string `json:"username,omitempty"` + // Password - Password of git repository basic auth. + Password *string `json:"password,omitempty"` + // HostKey - Public sshKey of git repository. + HostKey *string `json:"hostKey,omitempty"` + // HostKeyAlgorithm - SshKey algorithm of git repository. + HostKeyAlgorithm *string `json:"hostKeyAlgorithm,omitempty"` + // PrivateKey - Private sshKey algorithm of git repository. + PrivateKey *string `json:"privateKey,omitempty"` + // StrictHostKeyChecking - Strict host key checking or not. + StrictHostKeyChecking *bool `json:"strictHostKeyChecking,omitempty"` +} + +// ConfigServerProperties config server git properties payload +type ConfigServerProperties struct { + // ProvisioningState - READ-ONLY; State of the config server. Possible values include: 'ConfigServerStateNotAvailable', 'ConfigServerStateDeleted', 'ConfigServerStateFailed', 'ConfigServerStateSucceeded', 'ConfigServerStateUpdating' + ProvisioningState ConfigServerState `json:"provisioningState,omitempty"` + // Error - Error when apply config server settings. + Error *Error `json:"error,omitempty"` + // ConfigServer - Settings of config server. + ConfigServer *ConfigServerSettings `json:"configServer,omitempty"` +} + +// MarshalJSON is the custom marshaler for ConfigServerProperties. +func (csp ConfigServerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if csp.Error != nil { + objectMap["error"] = csp.Error + } + if csp.ConfigServer != nil { + objectMap["configServer"] = csp.ConfigServer + } + return json.Marshal(objectMap) +} + +// ConfigServerResource config Server resource +type ConfigServerResource struct { + autorest.Response `json:"-"` + // Properties - Properties of the Config Server resource + Properties *ConfigServerProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for ConfigServerResource. +func (csr ConfigServerResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if csr.Properties != nil { + objectMap["properties"] = csr.Properties + } + if csr.SystemData != nil { + objectMap["systemData"] = csr.SystemData + } + return json.Marshal(objectMap) +} + +// ConfigServerSettings the settings of config server. +type ConfigServerSettings struct { + // GitProperty - Property of git environment. + GitProperty *ConfigServerGitProperty `json:"gitProperty,omitempty"` +} + +// ConfigServerSettingsErrorRecord error record of the config server settings +type ConfigServerSettingsErrorRecord struct { + // Name - The name of the config server settings error record + Name *string `json:"name,omitempty"` + // URI - The uri of the config server settings error record + URI *string `json:"uri,omitempty"` + // Messages - The detail error messages of the record + Messages *[]string `json:"messages,omitempty"` +} + +// ConfigServerSettingsValidateResult validation result for config server settings +type ConfigServerSettingsValidateResult struct { + autorest.Response `json:"-"` + // IsValid - Indicate if the config server settings are valid + IsValid *bool `json:"isValid,omitempty"` + // Details - The detail validation results + Details *[]ConfigServerSettingsErrorRecord `json:"details,omitempty"` +} + +// ConfigServersUpdatePatchFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ConfigServersUpdatePatchFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ConfigServersClient) (ConfigServerResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ConfigServersUpdatePatchFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ConfigServersUpdatePatchFuture.Result. +func (future *ConfigServersUpdatePatchFuture) result(client ConfigServersClient) (csr ConfigServerResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersUpdatePatchFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + csr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ConfigServersUpdatePatchFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if csr.Response.Response, err = future.GetResult(sender); err == nil && csr.Response.Response.StatusCode != http.StatusNoContent { + csr, err = client.UpdatePatchResponder(csr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersUpdatePatchFuture", "Result", csr.Response.Response, "Failure responding to request") + } + } + return +} + +// ConfigServersUpdatePutFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ConfigServersUpdatePutFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ConfigServersClient) (ConfigServerResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ConfigServersUpdatePutFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ConfigServersUpdatePutFuture.Result. +func (future *ConfigServersUpdatePutFuture) result(client ConfigServersClient) (csr ConfigServerResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersUpdatePutFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + csr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ConfigServersUpdatePutFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if csr.Response.Response, err = future.GetResult(sender); err == nil && csr.Response.Response.StatusCode != http.StatusNoContent { + csr, err = client.UpdatePutResponder(csr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersUpdatePutFuture", "Result", csr.Response.Response, "Failure responding to request") + } + } + return +} + +// ConfigServersValidateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ConfigServersValidateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ConfigServersClient) (ConfigServerSettingsValidateResult, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ConfigServersValidateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ConfigServersValidateFuture.Result. +func (future *ConfigServersValidateFuture) result(client ConfigServersClient) (cssvr ConfigServerSettingsValidateResult, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersValidateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + cssvr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ConfigServersValidateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if cssvr.Response.Response, err = future.GetResult(sender); err == nil && cssvr.Response.Response.StatusCode != http.StatusNoContent { + cssvr, err = client.ValidateResponder(cssvr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigServersValidateFuture", "Result", cssvr.Response.Response, "Failure responding to request") + } + } + return +} + +// ConfigurationServiceGitProperty property of git environment. +type ConfigurationServiceGitProperty struct { + Repositories *[]ConfigurationServiceGitRepository `json:"repositories,omitempty"` +} + +// ConfigurationServiceGitPropertyValidateResult validation result for configuration service settings +type ConfigurationServiceGitPropertyValidateResult struct { + // IsValid - Indicate if the configuration service settings are valid + IsValid *bool `json:"isValid,omitempty"` + // GitReposValidationResult - The detail validation results + GitReposValidationResult *[]ValidationMessages `json:"gitReposValidationResult,omitempty"` +} + +// ConfigurationServiceGitRepository git repository property payload for Application Configuration Service +type ConfigurationServiceGitRepository struct { + // Name - Name of the repository + Name *string `json:"name,omitempty"` + // Patterns - Collection of patterns of the repository + Patterns *[]string `json:"patterns,omitempty"` + // URI - URI of the repository + URI *string `json:"uri,omitempty"` + // Label - Label of the repository + Label *string `json:"label,omitempty"` + // SearchPaths - Searching path of the repository + SearchPaths *[]string `json:"searchPaths,omitempty"` + // Username - Username of git repository basic auth. + Username *string `json:"username,omitempty"` + // Password - Password of git repository basic auth. + Password *string `json:"password,omitempty"` + // HostKey - Public sshKey of git repository. + HostKey *string `json:"hostKey,omitempty"` + // HostKeyAlgorithm - SshKey algorithm of git repository. + HostKeyAlgorithm *string `json:"hostKeyAlgorithm,omitempty"` + // PrivateKey - Private sshKey algorithm of git repository. + PrivateKey *string `json:"privateKey,omitempty"` + // StrictHostKeyChecking - Strict host key checking or not. + StrictHostKeyChecking *bool `json:"strictHostKeyChecking,omitempty"` +} + +// ConfigurationServiceInstance collection of instances belong to the Application Configuration Service +type ConfigurationServiceInstance struct { + // Name - READ-ONLY; Name of the Application Configuration Service instance + Name *string `json:"name,omitempty"` + // Status - READ-ONLY; Status of the Application Configuration Service instance + Status *string `json:"status,omitempty"` +} + +// MarshalJSON is the custom marshaler for ConfigurationServiceInstance. +func (csi ConfigurationServiceInstance) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// ConfigurationServiceProperties application Configuration Service properties payload +type ConfigurationServiceProperties struct { + // ProvisioningState - READ-ONLY; State of the Application Configuration Service. Possible values include: 'ConfigurationServiceProvisioningStateCreating', 'ConfigurationServiceProvisioningStateUpdating', 'ConfigurationServiceProvisioningStateSucceeded', 'ConfigurationServiceProvisioningStateFailed', 'ConfigurationServiceProvisioningStateDeleting' + ProvisioningState ConfigurationServiceProvisioningState `json:"provisioningState,omitempty"` + // ResourceRequests - The requested resource quantity for required CPU and Memory. + ResourceRequests *ConfigurationServiceResourceRequests `json:"resourceRequests,omitempty"` + // Instances - READ-ONLY; Collection of instances belong to Application Configuration Service. + Instances *[]ConfigurationServiceInstance `json:"instances,omitempty"` + Settings *ConfigurationServiceSettings `json:"settings,omitempty"` +} + +// MarshalJSON is the custom marshaler for ConfigurationServiceProperties. +func (csp ConfigurationServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if csp.ResourceRequests != nil { + objectMap["resourceRequests"] = csp.ResourceRequests + } + if csp.Settings != nil { + objectMap["settings"] = csp.Settings + } + return json.Marshal(objectMap) +} + +// ConfigurationServiceResource application Configuration Service resource +type ConfigurationServiceResource struct { + autorest.Response `json:"-"` + Properties *ConfigurationServiceProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for ConfigurationServiceResource. +func (csr ConfigurationServiceResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if csr.Properties != nil { + objectMap["properties"] = csr.Properties + } + if csr.SystemData != nil { + objectMap["systemData"] = csr.SystemData + } + return json.Marshal(objectMap) +} + +// ConfigurationServiceResourceCollection object that includes an array of configuration service resources +// and a possible link for next set +type ConfigurationServiceResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of configuration service resources + Value *[]ConfigurationServiceResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// ConfigurationServiceResourceCollectionIterator provides access to a complete listing of +// ConfigurationServiceResource values. +type ConfigurationServiceResourceCollectionIterator struct { + i int + page ConfigurationServiceResourceCollectionPage +} + +// NextWithContext 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 *ConfigurationServiceResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServiceResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ConfigurationServiceResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ConfigurationServiceResourceCollectionIterator) 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 ConfigurationServiceResourceCollectionIterator) Response() ConfigurationServiceResourceCollection { + 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 ConfigurationServiceResourceCollectionIterator) Value() ConfigurationServiceResource { + if !iter.page.NotDone() { + return ConfigurationServiceResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ConfigurationServiceResourceCollectionIterator type. +func NewConfigurationServiceResourceCollectionIterator(page ConfigurationServiceResourceCollectionPage) ConfigurationServiceResourceCollectionIterator { + return ConfigurationServiceResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (csrc ConfigurationServiceResourceCollection) IsEmpty() bool { + return csrc.Value == nil || len(*csrc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (csrc ConfigurationServiceResourceCollection) hasNextLink() bool { + return csrc.NextLink != nil && len(*csrc.NextLink) != 0 +} + +// configurationServiceResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (csrc ConfigurationServiceResourceCollection) configurationServiceResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !csrc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(csrc.NextLink))) +} + +// ConfigurationServiceResourceCollectionPage contains a page of ConfigurationServiceResource values. +type ConfigurationServiceResourceCollectionPage struct { + fn func(context.Context, ConfigurationServiceResourceCollection) (ConfigurationServiceResourceCollection, error) + csrc ConfigurationServiceResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ConfigurationServiceResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServiceResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.csrc) + if err != nil { + return err + } + page.csrc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ConfigurationServiceResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ConfigurationServiceResourceCollectionPage) NotDone() bool { + return !page.csrc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ConfigurationServiceResourceCollectionPage) Response() ConfigurationServiceResourceCollection { + return page.csrc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ConfigurationServiceResourceCollectionPage) Values() []ConfigurationServiceResource { + if page.csrc.IsEmpty() { + return nil + } + return *page.csrc.Value +} + +// Creates a new instance of the ConfigurationServiceResourceCollectionPage type. +func NewConfigurationServiceResourceCollectionPage(cur ConfigurationServiceResourceCollection, getNextPage func(context.Context, ConfigurationServiceResourceCollection) (ConfigurationServiceResourceCollection, error)) ConfigurationServiceResourceCollectionPage { + return ConfigurationServiceResourceCollectionPage{ + fn: getNextPage, + csrc: cur, + } +} + +// ConfigurationServiceResourceRequests resource request payload of Application Configuration Service +type ConfigurationServiceResourceRequests struct { + // CPU - READ-ONLY; Cpu allocated to each Application Configuration Service instance + CPU *string `json:"cpu,omitempty"` + // Memory - READ-ONLY; Memory allocated to each Application Configuration Service instance + Memory *string `json:"memory,omitempty"` + // InstanceCount - READ-ONLY; Instance count of the Application Configuration Service + InstanceCount *int32 `json:"instanceCount,omitempty"` +} + +// MarshalJSON is the custom marshaler for ConfigurationServiceResourceRequests. +func (csrr ConfigurationServiceResourceRequests) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// ConfigurationServicesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ConfigurationServicesCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ConfigurationServicesClient) (ConfigurationServiceResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ConfigurationServicesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ConfigurationServicesCreateOrUpdateFuture.Result. +func (future *ConfigurationServicesCreateOrUpdateFuture) result(client ConfigurationServicesClient) (csr ConfigurationServiceResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + csr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ConfigurationServicesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if csr.Response.Response, err = future.GetResult(sender); err == nil && csr.Response.Response.StatusCode != http.StatusNoContent { + csr, err = client.CreateOrUpdateResponder(csr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesCreateOrUpdateFuture", "Result", csr.Response.Response, "Failure responding to request") + } + } + return +} + +// ConfigurationServicesDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ConfigurationServicesDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ConfigurationServicesClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ConfigurationServicesDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ConfigurationServicesDeleteFuture.Result. +func (future *ConfigurationServicesDeleteFuture) result(client ConfigurationServicesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ConfigurationServicesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ConfigurationServiceSettings the settings of Application Configuration Service. +type ConfigurationServiceSettings struct { + GitProperty *ConfigurationServiceGitProperty `json:"gitProperty,omitempty"` +} + +// ConfigurationServiceSettingsValidateResult validation result for configuration service settings +type ConfigurationServiceSettingsValidateResult struct { + autorest.Response `json:"-"` + GitPropertyValidationResult *ConfigurationServiceGitPropertyValidateResult `json:"gitPropertyValidationResult,omitempty"` +} + +// ConfigurationServicesValidateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ConfigurationServicesValidateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ConfigurationServicesClient) (ConfigurationServiceSettingsValidateResult, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ConfigurationServicesValidateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ConfigurationServicesValidateFuture.Result. +func (future *ConfigurationServicesValidateFuture) result(client ConfigurationServicesClient) (cssvr ConfigurationServiceSettingsValidateResult, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesValidateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + cssvr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ConfigurationServicesValidateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if cssvr.Response.Response, err = future.GetResult(sender); err == nil && cssvr.Response.Response.StatusCode != http.StatusNoContent { + cssvr, err = client.ValidateResponder(cssvr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesValidateFuture", "Result", cssvr.Response.Response, "Failure responding to request") + } + } + return +} + +// ContainerProbeSettings container liveness and readiness probe settings +type ContainerProbeSettings struct { + // DisableProbe - Indicates whether disable the liveness and readiness probe + DisableProbe *bool `json:"disableProbe,omitempty"` +} + +// ContentCertificateProperties properties of certificate imported from key vault. +type ContentCertificateProperties struct { + // Content - The content of uploaded certificate. + Content *string `json:"content,omitempty"` + // Thumbprint - READ-ONLY; The thumbprint of certificate. + Thumbprint *string `json:"thumbprint,omitempty"` + // Issuer - READ-ONLY; The issuer of certificate. + Issuer *string `json:"issuer,omitempty"` + // IssuedDate - READ-ONLY; The issue date of certificate. + IssuedDate *string `json:"issuedDate,omitempty"` + // ExpirationDate - READ-ONLY; The expiration date of certificate. + ExpirationDate *string `json:"expirationDate,omitempty"` + // ActivateDate - READ-ONLY; The activate date of certificate. + ActivateDate *string `json:"activateDate,omitempty"` + // SubjectName - READ-ONLY; The subject name of certificate. + SubjectName *string `json:"subjectName,omitempty"` + // DNSNames - READ-ONLY; The domain list of certificate. + DNSNames *[]string `json:"dnsNames,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the Certificate. Possible values include: 'CertificateResourceProvisioningStateCreating', 'CertificateResourceProvisioningStateUpdating', 'CertificateResourceProvisioningStateSucceeded', 'CertificateResourceProvisioningStateFailed', 'CertificateResourceProvisioningStateDeleting' + ProvisioningState CertificateResourceProvisioningState `json:"provisioningState,omitempty"` + // Type - Possible values include: 'TypeBasicCertificatePropertiesTypeCertificateProperties', 'TypeBasicCertificatePropertiesTypeKeyVaultCertificate', 'TypeBasicCertificatePropertiesTypeContentCertificate' + Type TypeBasicCertificateProperties `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ContentCertificateProperties. +func (ccp ContentCertificateProperties) MarshalJSON() ([]byte, error) { + ccp.Type = TypeBasicCertificatePropertiesTypeContentCertificate + objectMap := make(map[string]interface{}) + if ccp.Content != nil { + objectMap["content"] = ccp.Content + } + if ccp.Type != "" { + objectMap["type"] = ccp.Type + } + return json.Marshal(objectMap) +} + +// AsKeyVaultCertificateProperties is the BasicCertificateProperties implementation for ContentCertificateProperties. +func (ccp ContentCertificateProperties) AsKeyVaultCertificateProperties() (*KeyVaultCertificateProperties, bool) { + return nil, false +} + +// AsContentCertificateProperties is the BasicCertificateProperties implementation for ContentCertificateProperties. +func (ccp ContentCertificateProperties) AsContentCertificateProperties() (*ContentCertificateProperties, bool) { + return &ccp, true +} + +// AsCertificateProperties is the BasicCertificateProperties implementation for ContentCertificateProperties. +func (ccp ContentCertificateProperties) AsCertificateProperties() (*CertificateProperties, bool) { + return nil, false +} + +// AsBasicCertificateProperties is the BasicCertificateProperties implementation for ContentCertificateProperties. +func (ccp ContentCertificateProperties) AsBasicCertificateProperties() (BasicCertificateProperties, bool) { + return &ccp, true +} + +// CustomContainer custom container payload +type CustomContainer struct { + // Server - The name of the registry that contains the container image + Server *string `json:"server,omitempty"` + // ContainerImage - Container image of the custom container. This should be in the form of : without the server name of the registry + ContainerImage *string `json:"containerImage,omitempty"` + // Command - Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. + Command *[]string `json:"command,omitempty"` + // Args - Arguments to the entrypoint. The docker image's CMD is used if this is not provided. + Args *[]string `json:"args,omitempty"` + // ImageRegistryCredential - Credential of the image registry + ImageRegistryCredential *ImageRegistryCredential `json:"imageRegistryCredential,omitempty"` + // LanguageFramework - Language framework of the container image uploaded + LanguageFramework *string `json:"languageFramework,omitempty"` +} + +// CustomContainerUserSourceInfo custom container user source info +type CustomContainerUserSourceInfo struct { + CustomContainer *CustomContainer `json:"customContainer,omitempty"` + // Version - Version of the source + Version *string `json:"version,omitempty"` + // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' + Type TypeBasicUserSourceInfo `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) MarshalJSON() ([]byte, error) { + ccusi.Type = TypeBasicUserSourceInfoTypeContainer + objectMap := make(map[string]interface{}) + if ccusi.CustomContainer != nil { + objectMap["customContainer"] = ccusi.CustomContainer + } + if ccusi.Version != nil { + objectMap["version"] = ccusi.Version + } + if ccusi.Type != "" { + objectMap["type"] = ccusi.Type + } + return json.Marshal(objectMap) +} + +// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { + return nil, false +} + +// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { + return &ccusi, true +} + +// AsUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { + return nil, false +} + +// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. +func (ccusi CustomContainerUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { + return &ccusi, true +} + +// CustomDomainProperties custom domain of app resource payload. +type CustomDomainProperties struct { + // Thumbprint - The thumbprint of bound certificate. + Thumbprint *string `json:"thumbprint,omitempty"` + // AppName - READ-ONLY; The app name of domain. + AppName *string `json:"appName,omitempty"` + // CertName - The bound certificate name of domain. + CertName *string `json:"certName,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the Domain. Possible values include: 'CustomDomainResourceProvisioningStateCreating', 'CustomDomainResourceProvisioningStateUpdating', 'CustomDomainResourceProvisioningStateSucceeded', 'CustomDomainResourceProvisioningStateFailed', 'CustomDomainResourceProvisioningStateDeleting' + ProvisioningState CustomDomainResourceProvisioningState `json:"provisioningState,omitempty"` +} + +// MarshalJSON is the custom marshaler for CustomDomainProperties. +func (cdp CustomDomainProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cdp.Thumbprint != nil { + objectMap["thumbprint"] = cdp.Thumbprint + } + if cdp.CertName != nil { + objectMap["certName"] = cdp.CertName + } + return json.Marshal(objectMap) +} + +// CustomDomainResource custom domain resource payload. +type CustomDomainResource struct { + autorest.Response `json:"-"` + // Properties - Properties of the custom domain resource. + Properties *CustomDomainProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for CustomDomainResource. +func (cdr CustomDomainResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cdr.Properties != nil { + objectMap["properties"] = cdr.Properties + } + if cdr.SystemData != nil { + objectMap["systemData"] = cdr.SystemData + } + return json.Marshal(objectMap) +} + +// CustomDomainResourceCollection collection compose of a custom domain resources list and a possible link +// for next page. +type CustomDomainResourceCollection struct { + autorest.Response `json:"-"` + // Value - The custom domain resources list. + Value *[]CustomDomainResource `json:"value,omitempty"` + // NextLink - The link to next page of custom domain list. + NextLink *string `json:"nextLink,omitempty"` +} + +// CustomDomainResourceCollectionIterator provides access to a complete listing of CustomDomainResource +// values. +type CustomDomainResourceCollectionIterator struct { + i int + page CustomDomainResourceCollectionPage +} + +// NextWithContext 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 *CustomDomainResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *CustomDomainResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter CustomDomainResourceCollectionIterator) 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 CustomDomainResourceCollectionIterator) Response() CustomDomainResourceCollection { + 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 CustomDomainResourceCollectionIterator) Value() CustomDomainResource { + if !iter.page.NotDone() { + return CustomDomainResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the CustomDomainResourceCollectionIterator type. +func NewCustomDomainResourceCollectionIterator(page CustomDomainResourceCollectionPage) CustomDomainResourceCollectionIterator { + return CustomDomainResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (cdrc CustomDomainResourceCollection) IsEmpty() bool { + return cdrc.Value == nil || len(*cdrc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (cdrc CustomDomainResourceCollection) hasNextLink() bool { + return cdrc.NextLink != nil && len(*cdrc.NextLink) != 0 +} + +// customDomainResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (cdrc CustomDomainResourceCollection) customDomainResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !cdrc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(cdrc.NextLink))) +} + +// CustomDomainResourceCollectionPage contains a page of CustomDomainResource values. +type CustomDomainResourceCollectionPage struct { + fn func(context.Context, CustomDomainResourceCollection) (CustomDomainResourceCollection, error) + cdrc CustomDomainResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *CustomDomainResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.cdrc) + if err != nil { + return err + } + page.cdrc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *CustomDomainResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page CustomDomainResourceCollectionPage) NotDone() bool { + return !page.cdrc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page CustomDomainResourceCollectionPage) Response() CustomDomainResourceCollection { + return page.cdrc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page CustomDomainResourceCollectionPage) Values() []CustomDomainResource { + if page.cdrc.IsEmpty() { + return nil + } + return *page.cdrc.Value +} + +// Creates a new instance of the CustomDomainResourceCollectionPage type. +func NewCustomDomainResourceCollectionPage(cur CustomDomainResourceCollection, getNextPage func(context.Context, CustomDomainResourceCollection) (CustomDomainResourceCollection, error)) CustomDomainResourceCollectionPage { + return CustomDomainResourceCollectionPage{ + fn: getNextPage, + cdrc: cur, + } +} + +// CustomDomainsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type CustomDomainsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(CustomDomainsClient) (CustomDomainResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *CustomDomainsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for CustomDomainsCreateOrUpdateFuture.Result. +func (future *CustomDomainsCreateOrUpdateFuture) result(client CustomDomainsClient) (cdr CustomDomainResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + cdr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.CustomDomainsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if cdr.Response.Response, err = future.GetResult(sender); err == nil && cdr.Response.Response.StatusCode != http.StatusNoContent { + cdr, err = client.CreateOrUpdateResponder(cdr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsCreateOrUpdateFuture", "Result", cdr.Response.Response, "Failure responding to request") + } + } + return +} + +// CustomDomainsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type CustomDomainsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(CustomDomainsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *CustomDomainsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for CustomDomainsDeleteFuture.Result. +func (future *CustomDomainsDeleteFuture) result(client CustomDomainsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.CustomDomainsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// CustomDomainsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type CustomDomainsUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(CustomDomainsClient) (CustomDomainResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *CustomDomainsUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for CustomDomainsUpdateFuture.Result. +func (future *CustomDomainsUpdateFuture) result(client CustomDomainsClient) (cdr CustomDomainResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + cdr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.CustomDomainsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if cdr.Response.Response, err = future.GetResult(sender); err == nil && cdr.Response.Response.StatusCode != http.StatusNoContent { + cdr, err = client.UpdateResponder(cdr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsUpdateFuture", "Result", cdr.Response.Response, "Failure responding to request") + } + } + return +} + +// CustomDomainValidatePayload custom domain validate payload. +type CustomDomainValidatePayload struct { + // Name - Name to be validated + Name *string `json:"name,omitempty"` +} + +// CustomDomainValidateResult validation result for custom domain. +type CustomDomainValidateResult struct { + autorest.Response `json:"-"` + // IsValid - Indicates if domain name is valid. + IsValid *bool `json:"isValid,omitempty"` + // Message - Message of why domain name is invalid. + Message *string `json:"message,omitempty"` +} + +// BasicCustomPersistentDiskProperties custom persistent disk resource payload. +type BasicCustomPersistentDiskProperties interface { + AsAzureFileVolume() (*AzureFileVolume, bool) + AsCustomPersistentDiskProperties() (*CustomPersistentDiskProperties, bool) +} + +// CustomPersistentDiskProperties custom persistent disk resource payload. +type CustomPersistentDiskProperties struct { + // MountPath - The mount path of the persistent disk. + MountPath *string `json:"mountPath,omitempty"` + // ReadOnly - Indicates whether the persistent disk is a readOnly one. + ReadOnly *bool `json:"readOnly,omitempty"` + // MountOptions - These are the mount options for a persistent disk. + MountOptions *[]string `json:"mountOptions,omitempty"` + // Type - Possible values include: 'TypeCustomPersistentDiskProperties', 'TypeAzureFileVolume' + Type Type `json:"type,omitempty"` +} + +func unmarshalBasicCustomPersistentDiskProperties(body []byte) (BasicCustomPersistentDiskProperties, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["type"] { + case string(TypeAzureFileVolume): + var afv AzureFileVolume + err := json.Unmarshal(body, &afv) + return afv, err + default: + var cpdp CustomPersistentDiskProperties + err := json.Unmarshal(body, &cpdp) + return cpdp, err + } +} +func unmarshalBasicCustomPersistentDiskPropertiesArray(body []byte) ([]BasicCustomPersistentDiskProperties, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + cpdpArray := make([]BasicCustomPersistentDiskProperties, len(rawMessages)) + + for index, rawMessage := range rawMessages { + cpdp, err := unmarshalBasicCustomPersistentDiskProperties(*rawMessage) + if err != nil { + return nil, err + } + cpdpArray[index] = cpdp + } + return cpdpArray, nil +} + +// MarshalJSON is the custom marshaler for CustomPersistentDiskProperties. +func (cpdp CustomPersistentDiskProperties) MarshalJSON() ([]byte, error) { + cpdp.Type = TypeCustomPersistentDiskProperties + objectMap := make(map[string]interface{}) + if cpdp.MountPath != nil { + objectMap["mountPath"] = cpdp.MountPath + } + if cpdp.ReadOnly != nil { + objectMap["readOnly"] = cpdp.ReadOnly + } + if cpdp.MountOptions != nil { + objectMap["mountOptions"] = cpdp.MountOptions + } + if cpdp.Type != "" { + objectMap["type"] = cpdp.Type + } + return json.Marshal(objectMap) +} + +// AsAzureFileVolume is the BasicCustomPersistentDiskProperties implementation for CustomPersistentDiskProperties. +func (cpdp CustomPersistentDiskProperties) AsAzureFileVolume() (*AzureFileVolume, bool) { + return nil, false +} + +// AsCustomPersistentDiskProperties is the BasicCustomPersistentDiskProperties implementation for CustomPersistentDiskProperties. +func (cpdp CustomPersistentDiskProperties) AsCustomPersistentDiskProperties() (*CustomPersistentDiskProperties, bool) { + return &cpdp, true +} + +// AsBasicCustomPersistentDiskProperties is the BasicCustomPersistentDiskProperties implementation for CustomPersistentDiskProperties. +func (cpdp CustomPersistentDiskProperties) AsBasicCustomPersistentDiskProperties() (BasicCustomPersistentDiskProperties, bool) { + return &cpdp, true +} + +// CustomPersistentDiskResource custom persistent disk resource payload. +type CustomPersistentDiskResource struct { + // CustomPersistentDiskProperties - Properties of the custom persistent disk resource payload. + CustomPersistentDiskProperties BasicCustomPersistentDiskProperties `json:"customPersistentDiskProperties,omitempty"` + // StorageID - The resource id of Azure Spring Apps Storage resource. + StorageID *string `json:"storageId,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for CustomPersistentDiskResource struct. +func (cpdr *CustomPersistentDiskResource) 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 "customPersistentDiskProperties": + if v != nil { + customPersistentDiskProperties, err := unmarshalBasicCustomPersistentDiskProperties(*v) + if err != nil { + return err + } + cpdr.CustomPersistentDiskProperties = customPersistentDiskProperties + } + case "storageId": + if v != nil { + var storageID string + err = json.Unmarshal(*v, &storageID) + if err != nil { + return err + } + cpdr.StorageID = &storageID + } + } + } + + return nil +} + +// DeploymentInstance deployment instance payload +type DeploymentInstance struct { + // Name - READ-ONLY; Name of the deployment instance + Name *string `json:"name,omitempty"` + // Status - READ-ONLY; Status of the deployment instance + Status *string `json:"status,omitempty"` + // Reason - READ-ONLY; Failed reason of the deployment instance + Reason *string `json:"reason,omitempty"` + // DiscoveryStatus - READ-ONLY; Discovery status of the deployment instance + DiscoveryStatus *string `json:"discoveryStatus,omitempty"` + // StartTime - READ-ONLY; Start time of the deployment instance + StartTime *string `json:"startTime,omitempty"` + // Zone - READ-ONLY; Availability zone information of the deployment instance + Zone *string `json:"zone,omitempty"` +} + +// MarshalJSON is the custom marshaler for DeploymentInstance. +func (di DeploymentInstance) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// DeploymentResource deployment resource payload +type DeploymentResource struct { + autorest.Response `json:"-"` + // Properties - Properties of the Deployment resource + Properties *DeploymentResourceProperties `json:"properties,omitempty"` + // Sku - Sku of the Deployment resource + Sku *Sku `json:"sku,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for DeploymentResource. +func (dr DeploymentResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if dr.Properties != nil { + objectMap["properties"] = dr.Properties + } + if dr.Sku != nil { + objectMap["sku"] = dr.Sku + } + if dr.SystemData != nil { + objectMap["systemData"] = dr.SystemData + } + return json.Marshal(objectMap) +} + +// DeploymentResourceCollection object that includes an array of App resources and a possible link for next +// set +type DeploymentResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of Deployment resources + Value *[]DeploymentResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// DeploymentResourceCollectionIterator provides access to a complete listing of DeploymentResource values. +type DeploymentResourceCollectionIterator struct { + i int + page DeploymentResourceCollectionPage +} + +// NextWithContext 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 *DeploymentResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *DeploymentResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter DeploymentResourceCollectionIterator) 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 DeploymentResourceCollectionIterator) Response() DeploymentResourceCollection { + 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 DeploymentResourceCollectionIterator) Value() DeploymentResource { + if !iter.page.NotDone() { + return DeploymentResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the DeploymentResourceCollectionIterator type. +func NewDeploymentResourceCollectionIterator(page DeploymentResourceCollectionPage) DeploymentResourceCollectionIterator { + return DeploymentResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (drc DeploymentResourceCollection) IsEmpty() bool { + return drc.Value == nil || len(*drc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (drc DeploymentResourceCollection) hasNextLink() bool { + return drc.NextLink != nil && len(*drc.NextLink) != 0 +} + +// deploymentResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (drc DeploymentResourceCollection) deploymentResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !drc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(drc.NextLink))) +} + +// DeploymentResourceCollectionPage contains a page of DeploymentResource values. +type DeploymentResourceCollectionPage struct { + fn func(context.Context, DeploymentResourceCollection) (DeploymentResourceCollection, error) + drc DeploymentResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *DeploymentResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.drc) + if err != nil { + return err + } + page.drc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *DeploymentResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page DeploymentResourceCollectionPage) NotDone() bool { + return !page.drc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page DeploymentResourceCollectionPage) Response() DeploymentResourceCollection { + return page.drc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page DeploymentResourceCollectionPage) Values() []DeploymentResource { + if page.drc.IsEmpty() { + return nil + } + return *page.drc.Value +} + +// Creates a new instance of the DeploymentResourceCollectionPage type. +func NewDeploymentResourceCollectionPage(cur DeploymentResourceCollection, getNextPage func(context.Context, DeploymentResourceCollection) (DeploymentResourceCollection, error)) DeploymentResourceCollectionPage { + return DeploymentResourceCollectionPage{ + fn: getNextPage, + drc: cur, + } +} + +// DeploymentResourceProperties deployment resource properties payload +type DeploymentResourceProperties struct { + // Source - Uploaded source information of the deployment. + Source BasicUserSourceInfo `json:"source,omitempty"` + // DeploymentSettings - Deployment settings of the Deployment + DeploymentSettings *DeploymentSettings `json:"deploymentSettings,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the Deployment. Possible values include: 'DeploymentResourceProvisioningStateCreating', 'DeploymentResourceProvisioningStateUpdating', 'DeploymentResourceProvisioningStateSucceeded', 'DeploymentResourceProvisioningStateFailed' + ProvisioningState DeploymentResourceProvisioningState `json:"provisioningState,omitempty"` + // Status - READ-ONLY; Status of the Deployment. Possible values include: 'DeploymentResourceStatusStopped', 'DeploymentResourceStatusRunning' + Status DeploymentResourceStatus `json:"status,omitempty"` + // Active - Indicates whether the Deployment is active + Active *bool `json:"active,omitempty"` + // Instances - READ-ONLY; Collection of instances belong to the Deployment + Instances *[]DeploymentInstance `json:"instances,omitempty"` +} + +// MarshalJSON is the custom marshaler for DeploymentResourceProperties. +func (drp DeploymentResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + objectMap["source"] = drp.Source + if drp.DeploymentSettings != nil { + objectMap["deploymentSettings"] = drp.DeploymentSettings + } + if drp.Active != nil { + objectMap["active"] = drp.Active + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DeploymentResourceProperties struct. +func (drp *DeploymentResourceProperties) 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 "source": + if v != nil { + source, err := unmarshalBasicUserSourceInfo(*v) + if err != nil { + return err + } + drp.Source = source + } + case "deploymentSettings": + if v != nil { + var deploymentSettings DeploymentSettings + err = json.Unmarshal(*v, &deploymentSettings) + if err != nil { + return err + } + drp.DeploymentSettings = &deploymentSettings + } + case "provisioningState": + if v != nil { + var provisioningState DeploymentResourceProvisioningState + err = json.Unmarshal(*v, &provisioningState) + if err != nil { + return err + } + drp.ProvisioningState = provisioningState + } + case "status": + if v != nil { + var status DeploymentResourceStatus + err = json.Unmarshal(*v, &status) + if err != nil { + return err + } + drp.Status = status + } + case "active": + if v != nil { + var active bool + err = json.Unmarshal(*v, &active) + if err != nil { + return err + } + drp.Active = &active + } + case "instances": + if v != nil { + var instances []DeploymentInstance + err = json.Unmarshal(*v, &instances) + if err != nil { + return err + } + drp.Instances = &instances + } + } + } + + return nil +} + +// DeploymentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type DeploymentsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DeploymentsClient) (DeploymentResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DeploymentsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DeploymentsCreateOrUpdateFuture.Result. +func (future *DeploymentsCreateOrUpdateFuture) result(client DeploymentsClient) (dr DeploymentResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + dr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dr.Response.Response, err = future.GetResult(sender); err == nil && dr.Response.Response.StatusCode != http.StatusNoContent { + dr, err = client.CreateOrUpdateResponder(dr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsCreateOrUpdateFuture", "Result", dr.Response.Response, "Failure responding to request") + } + } + return +} + +// DeploymentsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DeploymentsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DeploymentsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DeploymentsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DeploymentsDeleteFuture.Result. +func (future *DeploymentsDeleteFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// DeploymentSettings deployment settings payload +type DeploymentSettings struct { + // ResourceRequests - The requested resource quantity for required CPU and Memory. It is recommended that using this field to represent the required CPU and Memory, the old field cpu and memoryInGB will be deprecated later. + ResourceRequests *ResourceRequests `json:"resourceRequests,omitempty"` + // EnvironmentVariables - Collection of environment variables + EnvironmentVariables map[string]*string `json:"environmentVariables"` + // AddonConfigs - Collection of addons + AddonConfigs map[string]map[string]interface{} `json:"addonConfigs"` + // LivenessProbe - Periodic probe of App Instance liveness. App Instance will be restarted if the probe fails. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes + LivenessProbe *Probe `json:"livenessProbe,omitempty"` + // ReadinessProbe - Periodic probe of App Instance service readiness. App Instance will be removed from service endpoints if the probe fails. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes + ReadinessProbe *Probe `json:"readinessProbe,omitempty"` + // StartupProbe - StartupProbe indicates that the App Instance has successfully initialized. If specified, no other probes are executed until this completes successfully. If this probe fails, the Pod will be restarted, just as if the livenessProbe failed. This can be used to provide different probe parameters at the beginning of a App Instance's lifecycle, when it might take a long time to load data or warm a cache, than during steady-state operation. This cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes + StartupProbe *Probe `json:"startupProbe,omitempty"` + // TerminationGracePeriodSeconds - Optional duration in seconds the App Instance needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the App Instance are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 90 seconds. + TerminationGracePeriodSeconds *int32 `json:"terminationGracePeriodSeconds,omitempty"` + ContainerProbeSettings *ContainerProbeSettings `json:"containerProbeSettings,omitempty"` +} + +// MarshalJSON is the custom marshaler for DeploymentSettings. +func (ds DeploymentSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ds.ResourceRequests != nil { + objectMap["resourceRequests"] = ds.ResourceRequests + } + if ds.EnvironmentVariables != nil { + objectMap["environmentVariables"] = ds.EnvironmentVariables + } + if ds.AddonConfigs != nil { + objectMap["addonConfigs"] = ds.AddonConfigs + } + if ds.LivenessProbe != nil { + objectMap["livenessProbe"] = ds.LivenessProbe + } + if ds.ReadinessProbe != nil { + objectMap["readinessProbe"] = ds.ReadinessProbe + } + if ds.StartupProbe != nil { + objectMap["startupProbe"] = ds.StartupProbe + } + if ds.TerminationGracePeriodSeconds != nil { + objectMap["terminationGracePeriodSeconds"] = ds.TerminationGracePeriodSeconds + } + if ds.ContainerProbeSettings != nil { + objectMap["containerProbeSettings"] = ds.ContainerProbeSettings + } + return json.Marshal(objectMap) +} + +// DeploymentsGenerateHeapDumpFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type DeploymentsGenerateHeapDumpFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DeploymentsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DeploymentsGenerateHeapDumpFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DeploymentsGenerateHeapDumpFuture.Result. +func (future *DeploymentsGenerateHeapDumpFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsGenerateHeapDumpFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsGenerateHeapDumpFuture") + return + } + ar.Response = future.Response() + return +} + +// DeploymentsGenerateThreadDumpFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type DeploymentsGenerateThreadDumpFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DeploymentsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DeploymentsGenerateThreadDumpFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DeploymentsGenerateThreadDumpFuture.Result. +func (future *DeploymentsGenerateThreadDumpFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsGenerateThreadDumpFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsGenerateThreadDumpFuture") + return + } + ar.Response = future.Response() + return +} + +// DeploymentsRestartFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DeploymentsRestartFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DeploymentsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DeploymentsRestartFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DeploymentsRestartFuture.Result. +func (future *DeploymentsRestartFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsRestartFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsRestartFuture") + return + } + ar.Response = future.Response() + return +} + +// DeploymentsStartFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DeploymentsStartFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DeploymentsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DeploymentsStartFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DeploymentsStartFuture.Result. +func (future *DeploymentsStartFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsStartFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsStartFuture") + return + } + ar.Response = future.Response() + return +} + +// DeploymentsStartJFRFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DeploymentsStartJFRFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DeploymentsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DeploymentsStartJFRFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DeploymentsStartJFRFuture.Result. +func (future *DeploymentsStartJFRFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsStartJFRFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsStartJFRFuture") + return + } + ar.Response = future.Response() + return +} + +// DeploymentsStopFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DeploymentsStopFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DeploymentsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DeploymentsStopFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DeploymentsStopFuture.Result. +func (future *DeploymentsStopFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsStopFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsStopFuture") + return + } + ar.Response = future.Response() + return +} + +// DeploymentsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DeploymentsUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(DeploymentsClient) (DeploymentResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *DeploymentsUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for DeploymentsUpdateFuture.Result. +func (future *DeploymentsUpdateFuture) result(client DeploymentsClient) (dr DeploymentResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + dr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dr.Response.Response, err = future.GetResult(sender); err == nil && dr.Response.Response.StatusCode != http.StatusNoContent { + dr, err = client.UpdateResponder(dr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.DeploymentsUpdateFuture", "Result", dr.Response.Response, "Failure responding to request") + } + } + return +} + +// DiagnosticParameters diagnostic parameters of diagnostic operations +type DiagnosticParameters struct { + // AppInstance - App instance name + AppInstance *string `json:"appInstance,omitempty"` + // FilePath - Your target file path in your own BYOS + FilePath *string `json:"filePath,omitempty"` + // Duration - Duration of your JFR. 1 min can be represented by 1m or 60s. + Duration *string `json:"duration,omitempty"` +} + +// Error the error code compose of code and message. +type Error struct { + // Code - The code of error. + Code *string `json:"code,omitempty"` + // Message - The message of error. + Message *string `json:"message,omitempty"` +} + +// ExecAction execAction describes a "run in container" action. +type ExecAction struct { + // Command - Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy. + Command *[]string `json:"command,omitempty"` + // Type - Possible values include: 'TypeBasicProbeActionTypeProbeAction', 'TypeBasicProbeActionTypeHTTPGetAction', 'TypeBasicProbeActionTypeExecAction', 'TypeBasicProbeActionTypeTCPSocketAction' + Type TypeBasicProbeAction `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ExecAction. +func (ea ExecAction) MarshalJSON() ([]byte, error) { + ea.Type = TypeBasicProbeActionTypeExecAction + objectMap := make(map[string]interface{}) + if ea.Command != nil { + objectMap["command"] = ea.Command + } + if ea.Type != "" { + objectMap["type"] = ea.Type + } + return json.Marshal(objectMap) +} + +// AsHTTPGetAction is the BasicProbeAction implementation for ExecAction. +func (ea ExecAction) AsHTTPGetAction() (*HTTPGetAction, bool) { + return nil, false +} + +// AsExecAction is the BasicProbeAction implementation for ExecAction. +func (ea ExecAction) AsExecAction() (*ExecAction, bool) { + return &ea, true +} + +// AsTCPSocketAction is the BasicProbeAction implementation for ExecAction. +func (ea ExecAction) AsTCPSocketAction() (*TCPSocketAction, bool) { + return nil, false +} + +// AsProbeAction is the BasicProbeAction implementation for ExecAction. +func (ea ExecAction) AsProbeAction() (*ProbeAction, bool) { + return nil, false +} + +// AsBasicProbeAction is the BasicProbeAction implementation for ExecAction. +func (ea ExecAction) AsBasicProbeAction() (BasicProbeAction, bool) { + return &ea, true +} + +// GatewayAPIMetadataProperties API metadata property for Spring Cloud Gateway +type GatewayAPIMetadataProperties struct { + // Title - Title describing the context of the APIs available on the Gateway instance (default: `Spring Cloud Gateway for K8S`) + Title *string `json:"title,omitempty"` + // Description - Detailed description of the APIs available on the Gateway instance (default: `Generated OpenAPI 3 document that describes the API routes configured.`) + Description *string `json:"description,omitempty"` + // Documentation - Location of additional documentation for the APIs available on the Gateway instance + Documentation *string `json:"documentation,omitempty"` + // Version - Version of APIs available on this Gateway instance (default: `unspecified`). + Version *string `json:"version,omitempty"` + // ServerURL - Base URL that API consumers will use to access APIs on the Gateway instance. + ServerURL *string `json:"serverUrl,omitempty"` +} + +// GatewayAPIRoute API route config of the Spring Cloud Gateway +type GatewayAPIRoute struct { + // Title - A title, will be applied to methods in the generated OpenAPI documentation. + Title *string `json:"title,omitempty"` + // Description - A description, will be applied to methods in the generated OpenAPI documentation. + Description *string `json:"description,omitempty"` + // URI - Full uri, will override `appName`. + URI *string `json:"uri,omitempty"` + // SsoEnabled - Enable sso validation. + SsoEnabled *bool `json:"ssoEnabled,omitempty"` + // TokenRelay - Pass currently-authenticated user's identity token to application service, default is 'false' + TokenRelay *bool `json:"tokenRelay,omitempty"` + // Predicates - A number of conditions to evaluate a route for each request. Each predicate may be evaluated against request headers and parameter values. All of the predicates associated with a route must evaluate to true for the route to be matched to the request. + Predicates *[]string `json:"predicates,omitempty"` + // Filters - To modify the request before sending it to the target endpoint, or the received response. + Filters *[]string `json:"filters,omitempty"` + // Order - Route processing order. + Order *int32 `json:"order,omitempty"` + // Tags - Classification tags, will be applied to methods in the generated OpenAPI documentation. + Tags *[]string `json:"tags,omitempty"` +} + +// GatewayCorsProperties cross-Origin Resource Sharing property +type GatewayCorsProperties struct { + // AllowedOrigins - Allowed origins to make cross-site requests. The special value `*` allows all domains. + AllowedOrigins *[]string `json:"allowedOrigins,omitempty"` + // AllowedMethods - Allowed HTTP methods on cross-site requests. The special value `*` allows all methods. If not set, `GET` and `HEAD` are allowed by default. + AllowedMethods *[]string `json:"allowedMethods,omitempty"` + // AllowedHeaders - Allowed headers in cross-site requests. The special value `*` allows actual requests to send any header. + AllowedHeaders *[]string `json:"allowedHeaders,omitempty"` + // MaxAge - How long, in seconds, the response from a pre-flight request can be cached by clients. + MaxAge *int32 `json:"maxAge,omitempty"` + // AllowCredentials - Whether user credentials are supported on cross-site requests. Valid values: `true`, `false`. + AllowCredentials *bool `json:"allowCredentials,omitempty"` + // ExposedHeaders - HTTP response headers to expose for cross-site requests. + ExposedHeaders *[]string `json:"exposedHeaders,omitempty"` +} + +// GatewayCustomDomainProperties the properties of custom domain for Spring Cloud Gateway +type GatewayCustomDomainProperties struct { + // Thumbprint - The thumbprint of bound certificate. + Thumbprint *string `json:"thumbprint,omitempty"` +} + +// GatewayCustomDomainResource custom domain of the Spring Cloud Gateway +type GatewayCustomDomainResource struct { + autorest.Response `json:"-"` + Properties *GatewayCustomDomainProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for GatewayCustomDomainResource. +func (gcdr GatewayCustomDomainResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if gcdr.Properties != nil { + objectMap["properties"] = gcdr.Properties + } + if gcdr.SystemData != nil { + objectMap["systemData"] = gcdr.SystemData + } + return json.Marshal(objectMap) +} + +// GatewayCustomDomainResourceCollection object that includes an array of Spring Cloud Gateway custom +// domain resources and a possible link for next set +type GatewayCustomDomainResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of Spring Cloud Gateway custom domain resources + Value *[]GatewayCustomDomainResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// GatewayCustomDomainResourceCollectionIterator provides access to a complete listing of +// GatewayCustomDomainResource values. +type GatewayCustomDomainResourceCollectionIterator struct { + i int + page GatewayCustomDomainResourceCollectionPage +} + +// NextWithContext 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 *GatewayCustomDomainResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *GatewayCustomDomainResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter GatewayCustomDomainResourceCollectionIterator) 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 GatewayCustomDomainResourceCollectionIterator) Response() GatewayCustomDomainResourceCollection { + 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 GatewayCustomDomainResourceCollectionIterator) Value() GatewayCustomDomainResource { + if !iter.page.NotDone() { + return GatewayCustomDomainResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the GatewayCustomDomainResourceCollectionIterator type. +func NewGatewayCustomDomainResourceCollectionIterator(page GatewayCustomDomainResourceCollectionPage) GatewayCustomDomainResourceCollectionIterator { + return GatewayCustomDomainResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (gcdrc GatewayCustomDomainResourceCollection) IsEmpty() bool { + return gcdrc.Value == nil || len(*gcdrc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (gcdrc GatewayCustomDomainResourceCollection) hasNextLink() bool { + return gcdrc.NextLink != nil && len(*gcdrc.NextLink) != 0 +} + +// gatewayCustomDomainResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (gcdrc GatewayCustomDomainResourceCollection) gatewayCustomDomainResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !gcdrc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(gcdrc.NextLink))) +} + +// GatewayCustomDomainResourceCollectionPage contains a page of GatewayCustomDomainResource values. +type GatewayCustomDomainResourceCollectionPage struct { + fn func(context.Context, GatewayCustomDomainResourceCollection) (GatewayCustomDomainResourceCollection, error) + gcdrc GatewayCustomDomainResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *GatewayCustomDomainResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.gcdrc) + if err != nil { + return err + } + page.gcdrc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *GatewayCustomDomainResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page GatewayCustomDomainResourceCollectionPage) NotDone() bool { + return !page.gcdrc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page GatewayCustomDomainResourceCollectionPage) Response() GatewayCustomDomainResourceCollection { + return page.gcdrc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page GatewayCustomDomainResourceCollectionPage) Values() []GatewayCustomDomainResource { + if page.gcdrc.IsEmpty() { + return nil + } + return *page.gcdrc.Value +} + +// Creates a new instance of the GatewayCustomDomainResourceCollectionPage type. +func NewGatewayCustomDomainResourceCollectionPage(cur GatewayCustomDomainResourceCollection, getNextPage func(context.Context, GatewayCustomDomainResourceCollection) (GatewayCustomDomainResourceCollection, error)) GatewayCustomDomainResourceCollectionPage { + return GatewayCustomDomainResourceCollectionPage{ + fn: getNextPage, + gcdrc: cur, + } +} + +// GatewayCustomDomainsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type GatewayCustomDomainsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(GatewayCustomDomainsClient) (GatewayCustomDomainResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *GatewayCustomDomainsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for GatewayCustomDomainsCreateOrUpdateFuture.Result. +func (future *GatewayCustomDomainsCreateOrUpdateFuture) result(client GatewayCustomDomainsClient) (gcdr GatewayCustomDomainResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + gcdr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.GatewayCustomDomainsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if gcdr.Response.Response, err = future.GetResult(sender); err == nil && gcdr.Response.Response.StatusCode != http.StatusNoContent { + gcdr, err = client.CreateOrUpdateResponder(gcdr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsCreateOrUpdateFuture", "Result", gcdr.Response.Response, "Failure responding to request") + } + } + return +} + +// GatewayCustomDomainsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type GatewayCustomDomainsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(GatewayCustomDomainsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *GatewayCustomDomainsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for GatewayCustomDomainsDeleteFuture.Result. +func (future *GatewayCustomDomainsDeleteFuture) result(client GatewayCustomDomainsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.GatewayCustomDomainsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// GatewayInstance collection of instances belong to the Spring Cloud Gateway +type GatewayInstance struct { + // Name - READ-ONLY; Name of the Spring Cloud Gateway instance + Name *string `json:"name,omitempty"` + // Status - READ-ONLY; Status of the Spring Cloud Gateway instance + Status *string `json:"status,omitempty"` +} + +// MarshalJSON is the custom marshaler for GatewayInstance. +func (gi GatewayInstance) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// GatewayOperatorProperties properties of the Spring Cloud Gateway Operator. +type GatewayOperatorProperties struct { + // ResourceRequests - The requested resource quantity for required CPU and Memory. + ResourceRequests *GatewayOperatorResourceRequests `json:"resourceRequests,omitempty"` + // Instances - READ-ONLY; Collection of instances belong to Spring Cloud Gateway operator. + Instances *[]GatewayInstance `json:"instances,omitempty"` +} + +// MarshalJSON is the custom marshaler for GatewayOperatorProperties. +func (gop GatewayOperatorProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if gop.ResourceRequests != nil { + objectMap["resourceRequests"] = gop.ResourceRequests + } + return json.Marshal(objectMap) +} + +// GatewayOperatorResourceRequests properties of the Spring Cloud Gateway Operator. +type GatewayOperatorResourceRequests struct { + // CPU - READ-ONLY; Cpu allocated to each Spring Cloud Gateway Operator instance. + CPU *string `json:"cpu,omitempty"` + // Memory - READ-ONLY; Memory allocated to each Spring Cloud Gateway Operator instance. + Memory *string `json:"memory,omitempty"` + // InstanceCount - READ-ONLY; Instance count of the Spring Cloud Gateway Operator. + InstanceCount *int32 `json:"instanceCount,omitempty"` +} + +// MarshalJSON is the custom marshaler for GatewayOperatorResourceRequests. +func (gorr GatewayOperatorResourceRequests) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// GatewayProperties spring Cloud Gateway properties payload +type GatewayProperties struct { + // ProvisioningState - READ-ONLY; State of the Spring Cloud Gateway. Possible values include: 'GatewayProvisioningStateCreating', 'GatewayProvisioningStateUpdating', 'GatewayProvisioningStateSucceeded', 'GatewayProvisioningStateFailed', 'GatewayProvisioningStateDeleting' + ProvisioningState GatewayProvisioningState `json:"provisioningState,omitempty"` + // Public - Indicates whether the Spring Cloud Gateway exposes endpoint. + Public *bool `json:"public,omitempty"` + // URL - READ-ONLY; URL of the Spring Cloud Gateway, exposed when 'public' is true. + URL *string `json:"url,omitempty"` + // HTTPSOnly - Indicate if only https is allowed. + HTTPSOnly *bool `json:"httpsOnly,omitempty"` + SsoProperties *SsoProperties `json:"ssoProperties,omitempty"` + APIMetadataProperties *GatewayAPIMetadataProperties `json:"apiMetadataProperties,omitempty"` + CorsProperties *GatewayCorsProperties `json:"corsProperties,omitempty"` + // ResourceRequests - The requested resource quantity for required CPU and Memory. + ResourceRequests *GatewayResourceRequests `json:"resourceRequests,omitempty"` + // Instances - READ-ONLY; Collection of instances belong to Spring Cloud Gateway. + Instances *[]GatewayInstance `json:"instances,omitempty"` + // OperatorProperties - READ-ONLY + OperatorProperties *GatewayOperatorProperties `json:"operatorProperties,omitempty"` +} + +// MarshalJSON is the custom marshaler for GatewayProperties. +func (gp GatewayProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if gp.Public != nil { + objectMap["public"] = gp.Public + } + if gp.HTTPSOnly != nil { + objectMap["httpsOnly"] = gp.HTTPSOnly + } + if gp.SsoProperties != nil { + objectMap["ssoProperties"] = gp.SsoProperties + } + if gp.APIMetadataProperties != nil { + objectMap["apiMetadataProperties"] = gp.APIMetadataProperties + } + if gp.CorsProperties != nil { + objectMap["corsProperties"] = gp.CorsProperties + } + if gp.ResourceRequests != nil { + objectMap["resourceRequests"] = gp.ResourceRequests + } + return json.Marshal(objectMap) +} + +// GatewayResource spring Cloud Gateway resource +type GatewayResource struct { + autorest.Response `json:"-"` + Properties *GatewayProperties `json:"properties,omitempty"` + // Sku - Sku of the Spring Cloud Gateway resource + Sku *Sku `json:"sku,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for GatewayResource. +func (gr GatewayResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if gr.Properties != nil { + objectMap["properties"] = gr.Properties + } + if gr.Sku != nil { + objectMap["sku"] = gr.Sku + } + if gr.SystemData != nil { + objectMap["systemData"] = gr.SystemData + } + return json.Marshal(objectMap) +} + +// GatewayResourceCollection object that includes an array of gateway resources and a possible link for +// next set +type GatewayResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of gateway resources + Value *[]GatewayResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// GatewayResourceCollectionIterator provides access to a complete listing of GatewayResource values. +type GatewayResourceCollectionIterator struct { + i int + page GatewayResourceCollectionPage +} + +// NextWithContext 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 *GatewayResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *GatewayResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter GatewayResourceCollectionIterator) 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 GatewayResourceCollectionIterator) Response() GatewayResourceCollection { + 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 GatewayResourceCollectionIterator) Value() GatewayResource { + if !iter.page.NotDone() { + return GatewayResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the GatewayResourceCollectionIterator type. +func NewGatewayResourceCollectionIterator(page GatewayResourceCollectionPage) GatewayResourceCollectionIterator { + return GatewayResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (grc GatewayResourceCollection) IsEmpty() bool { + return grc.Value == nil || len(*grc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (grc GatewayResourceCollection) hasNextLink() bool { + return grc.NextLink != nil && len(*grc.NextLink) != 0 +} + +// gatewayResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (grc GatewayResourceCollection) gatewayResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !grc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(grc.NextLink))) +} + +// GatewayResourceCollectionPage contains a page of GatewayResource values. +type GatewayResourceCollectionPage struct { + fn func(context.Context, GatewayResourceCollection) (GatewayResourceCollection, error) + grc GatewayResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *GatewayResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.grc) + if err != nil { + return err + } + page.grc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *GatewayResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page GatewayResourceCollectionPage) NotDone() bool { + return !page.grc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page GatewayResourceCollectionPage) Response() GatewayResourceCollection { + return page.grc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page GatewayResourceCollectionPage) Values() []GatewayResource { + if page.grc.IsEmpty() { + return nil + } + return *page.grc.Value +} + +// Creates a new instance of the GatewayResourceCollectionPage type. +func NewGatewayResourceCollectionPage(cur GatewayResourceCollection, getNextPage func(context.Context, GatewayResourceCollection) (GatewayResourceCollection, error)) GatewayResourceCollectionPage { + return GatewayResourceCollectionPage{ + fn: getNextPage, + grc: cur, + } +} + +// GatewayResourceRequests resource request payload of Spring Cloud Gateway. +type GatewayResourceRequests struct { + // CPU - Cpu allocated to each Spring Cloud Gateway instance. + CPU *string `json:"cpu,omitempty"` + // Memory - Memory allocated to each Spring Cloud Gateway instance. + Memory *string `json:"memory,omitempty"` +} + +// GatewayRouteConfigOpenAPIProperties openAPI properties of Spring Cloud Gateway route config. +type GatewayRouteConfigOpenAPIProperties struct { + // URI - The URI of OpenAPI specification. + URI *string `json:"uri,omitempty"` +} + +// GatewayRouteConfigProperties API route config of the Spring Cloud Gateway +type GatewayRouteConfigProperties struct { + // ProvisioningState - READ-ONLY; State of the Spring Cloud Gateway route config. Possible values include: 'GatewayProvisioningStateCreating', 'GatewayProvisioningStateUpdating', 'GatewayProvisioningStateSucceeded', 'GatewayProvisioningStateFailed', 'GatewayProvisioningStateDeleting' + ProvisioningState GatewayProvisioningState `json:"provisioningState,omitempty"` + // AppResourceID - The resource Id of the Azure Spring Apps app, required unless route defines `uri`. + AppResourceID *string `json:"appResourceId,omitempty"` + OpenAPI *GatewayRouteConfigOpenAPIProperties `json:"openApi,omitempty"` + // Routes - Array of API routes, each route contains properties such as `title`, `uri`, `ssoEnabled`, `predicates`, `filters`. + Routes *[]GatewayAPIRoute `json:"routes,omitempty"` +} + +// MarshalJSON is the custom marshaler for GatewayRouteConfigProperties. +func (grcp GatewayRouteConfigProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if grcp.AppResourceID != nil { + objectMap["appResourceId"] = grcp.AppResourceID + } + if grcp.OpenAPI != nil { + objectMap["openApi"] = grcp.OpenAPI + } + if grcp.Routes != nil { + objectMap["routes"] = grcp.Routes + } + return json.Marshal(objectMap) +} + +// GatewayRouteConfigResource spring Cloud Gateway route config resource +type GatewayRouteConfigResource struct { + autorest.Response `json:"-"` + Properties *GatewayRouteConfigProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for GatewayRouteConfigResource. +func (grcr GatewayRouteConfigResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if grcr.Properties != nil { + objectMap["properties"] = grcr.Properties + } + if grcr.SystemData != nil { + objectMap["systemData"] = grcr.SystemData + } + return json.Marshal(objectMap) +} + +// GatewayRouteConfigResourceCollection object that includes an array of Spring Cloud Gateway route config +// resources and a possible link for next set +type GatewayRouteConfigResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of Spring Cloud Gateway route config resources + Value *[]GatewayRouteConfigResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// GatewayRouteConfigResourceCollectionIterator provides access to a complete listing of +// GatewayRouteConfigResource values. +type GatewayRouteConfigResourceCollectionIterator struct { + i int + page GatewayRouteConfigResourceCollectionPage +} + +// NextWithContext 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 *GatewayRouteConfigResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *GatewayRouteConfigResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter GatewayRouteConfigResourceCollectionIterator) 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 GatewayRouteConfigResourceCollectionIterator) Response() GatewayRouteConfigResourceCollection { + 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 GatewayRouteConfigResourceCollectionIterator) Value() GatewayRouteConfigResource { + if !iter.page.NotDone() { + return GatewayRouteConfigResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the GatewayRouteConfigResourceCollectionIterator type. +func NewGatewayRouteConfigResourceCollectionIterator(page GatewayRouteConfigResourceCollectionPage) GatewayRouteConfigResourceCollectionIterator { + return GatewayRouteConfigResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (grcrc GatewayRouteConfigResourceCollection) IsEmpty() bool { + return grcrc.Value == nil || len(*grcrc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (grcrc GatewayRouteConfigResourceCollection) hasNextLink() bool { + return grcrc.NextLink != nil && len(*grcrc.NextLink) != 0 +} + +// gatewayRouteConfigResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (grcrc GatewayRouteConfigResourceCollection) gatewayRouteConfigResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !grcrc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(grcrc.NextLink))) +} + +// GatewayRouteConfigResourceCollectionPage contains a page of GatewayRouteConfigResource values. +type GatewayRouteConfigResourceCollectionPage struct { + fn func(context.Context, GatewayRouteConfigResourceCollection) (GatewayRouteConfigResourceCollection, error) + grcrc GatewayRouteConfigResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *GatewayRouteConfigResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.grcrc) + if err != nil { + return err + } + page.grcrc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *GatewayRouteConfigResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page GatewayRouteConfigResourceCollectionPage) NotDone() bool { + return !page.grcrc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page GatewayRouteConfigResourceCollectionPage) Response() GatewayRouteConfigResourceCollection { + return page.grcrc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page GatewayRouteConfigResourceCollectionPage) Values() []GatewayRouteConfigResource { + if page.grcrc.IsEmpty() { + return nil + } + return *page.grcrc.Value +} + +// Creates a new instance of the GatewayRouteConfigResourceCollectionPage type. +func NewGatewayRouteConfigResourceCollectionPage(cur GatewayRouteConfigResourceCollection, getNextPage func(context.Context, GatewayRouteConfigResourceCollection) (GatewayRouteConfigResourceCollection, error)) GatewayRouteConfigResourceCollectionPage { + return GatewayRouteConfigResourceCollectionPage{ + fn: getNextPage, + grcrc: cur, + } +} + +// GatewayRouteConfigsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type GatewayRouteConfigsCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(GatewayRouteConfigsClient) (GatewayRouteConfigResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *GatewayRouteConfigsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for GatewayRouteConfigsCreateOrUpdateFuture.Result. +func (future *GatewayRouteConfigsCreateOrUpdateFuture) result(client GatewayRouteConfigsClient) (grcr GatewayRouteConfigResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + grcr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.GatewayRouteConfigsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if grcr.Response.Response, err = future.GetResult(sender); err == nil && grcr.Response.Response.StatusCode != http.StatusNoContent { + grcr, err = client.CreateOrUpdateResponder(grcr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsCreateOrUpdateFuture", "Result", grcr.Response.Response, "Failure responding to request") + } + } + return +} + +// GatewayRouteConfigsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type GatewayRouteConfigsDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(GatewayRouteConfigsClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *GatewayRouteConfigsDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for GatewayRouteConfigsDeleteFuture.Result. +func (future *GatewayRouteConfigsDeleteFuture) result(client GatewayRouteConfigsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.GatewayRouteConfigsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// GatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type GatewaysCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(GatewaysClient) (GatewayResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *GatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for GatewaysCreateOrUpdateFuture.Result. +func (future *GatewaysCreateOrUpdateFuture) result(client GatewaysClient) (gr GatewayResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + gr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.GatewaysCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if gr.Response.Response, err = future.GetResult(sender); err == nil && gr.Response.Response.StatusCode != http.StatusNoContent { + gr, err = client.CreateOrUpdateResponder(gr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysCreateOrUpdateFuture", "Result", gr.Response.Response, "Failure responding to request") + } + } + return +} + +// GatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type GatewaysDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(GatewaysClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *GatewaysDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for GatewaysDeleteFuture.Result. +func (future *GatewaysDeleteFuture) result(client GatewaysClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.GatewaysDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.GatewaysDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// GitPatternRepository git repository property payload for config server +type GitPatternRepository struct { + // Name - Name of the repository + Name *string `json:"name,omitempty"` + // Pattern - Collection of pattern of the repository + Pattern *[]string `json:"pattern,omitempty"` + // URI - URI of the repository + URI *string `json:"uri,omitempty"` + // Label - Label of the repository + Label *string `json:"label,omitempty"` + // SearchPaths - Searching path of the repository + SearchPaths *[]string `json:"searchPaths,omitempty"` + // Username - Username of git repository basic auth. + Username *string `json:"username,omitempty"` + // Password - Password of git repository basic auth. + Password *string `json:"password,omitempty"` + // HostKey - Public sshKey of git repository. + HostKey *string `json:"hostKey,omitempty"` + // HostKeyAlgorithm - SshKey algorithm of git repository. + HostKeyAlgorithm *string `json:"hostKeyAlgorithm,omitempty"` + // PrivateKey - Private sshKey algorithm of git repository. + PrivateKey *string `json:"privateKey,omitempty"` + // StrictHostKeyChecking - Strict host key checking or not. + StrictHostKeyChecking *bool `json:"strictHostKeyChecking,omitempty"` +} + +// HTTPGetAction hTTPGetAction describes an action based on HTTP Get requests. +type HTTPGetAction struct { + // Path - Path to access on the HTTP server. + Path *string `json:"path,omitempty"` + // Scheme - Scheme to use for connecting to the host. Defaults to HTTP. + // Possible enum values: + // - `"HTTP"` means that the scheme used will be http:// + // - `"HTTPS"` means that the scheme used will be https://. Possible values include: 'HTTPSchemeTypeHTTP', 'HTTPSchemeTypeHTTPS' + Scheme HTTPSchemeType `json:"scheme,omitempty"` + // Type - Possible values include: 'TypeBasicProbeActionTypeProbeAction', 'TypeBasicProbeActionTypeHTTPGetAction', 'TypeBasicProbeActionTypeExecAction', 'TypeBasicProbeActionTypeTCPSocketAction' + Type TypeBasicProbeAction `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for HTTPGetAction. +func (hga HTTPGetAction) MarshalJSON() ([]byte, error) { + hga.Type = TypeBasicProbeActionTypeHTTPGetAction + objectMap := make(map[string]interface{}) + if hga.Path != nil { + objectMap["path"] = hga.Path + } + if hga.Scheme != "" { + objectMap["scheme"] = hga.Scheme + } + if hga.Type != "" { + objectMap["type"] = hga.Type + } + return json.Marshal(objectMap) +} + +// AsHTTPGetAction is the BasicProbeAction implementation for HTTPGetAction. +func (hga HTTPGetAction) AsHTTPGetAction() (*HTTPGetAction, bool) { + return &hga, true +} + +// AsExecAction is the BasicProbeAction implementation for HTTPGetAction. +func (hga HTTPGetAction) AsExecAction() (*ExecAction, bool) { + return nil, false +} + +// AsTCPSocketAction is the BasicProbeAction implementation for HTTPGetAction. +func (hga HTTPGetAction) AsTCPSocketAction() (*TCPSocketAction, bool) { + return nil, false +} + +// AsProbeAction is the BasicProbeAction implementation for HTTPGetAction. +func (hga HTTPGetAction) AsProbeAction() (*ProbeAction, bool) { + return nil, false +} + +// AsBasicProbeAction is the BasicProbeAction implementation for HTTPGetAction. +func (hga HTTPGetAction) AsBasicProbeAction() (BasicProbeAction, bool) { + return &hga, true +} + +// ImageRegistryCredential credential of the image registry +type ImageRegistryCredential struct { + // Username - The username of the image registry credential + Username *string `json:"username,omitempty"` + // Password - The password of the image registry credential + Password *string `json:"password,omitempty"` +} + +// IngressConfig ingress configuration payload for Azure Spring Apps resource. +type IngressConfig struct { + // ReadTimeoutInSeconds - Ingress read time out in seconds. + ReadTimeoutInSeconds *int32 `json:"readTimeoutInSeconds,omitempty"` +} + +// JarUploadedUserSourceInfo uploaded Jar binary for a deployment +type JarUploadedUserSourceInfo struct { + // RuntimeVersion - Runtime version of the Jar file + RuntimeVersion *string `json:"runtimeVersion,omitempty"` + // JvmOptions - JVM parameter + JvmOptions *string `json:"jvmOptions,omitempty"` + // RelativePath - Relative path of the storage which stores the source + RelativePath *string `json:"relativePath,omitempty"` + // Version - Version of the source + Version *string `json:"version,omitempty"` + // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' + Type TypeBasicUserSourceInfo `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) MarshalJSON() ([]byte, error) { + juusi.Type = TypeBasicUserSourceInfoTypeJar + objectMap := make(map[string]interface{}) + if juusi.RuntimeVersion != nil { + objectMap["runtimeVersion"] = juusi.RuntimeVersion + } + if juusi.JvmOptions != nil { + objectMap["jvmOptions"] = juusi.JvmOptions + } + if juusi.RelativePath != nil { + objectMap["relativePath"] = juusi.RelativePath + } + if juusi.Version != nil { + objectMap["version"] = juusi.Version + } + if juusi.Type != "" { + objectMap["type"] = juusi.Type + } + return json.Marshal(objectMap) +} + +// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { + return &juusi, true +} + +// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { + return &juusi, true +} + +// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { + return nil, false +} + +// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { + return nil, false +} + +// AsUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { + return nil, false +} + +// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. +func (juusi JarUploadedUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { + return &juusi, true +} + +// KeyVaultCertificateProperties properties of certificate imported from key vault. +type KeyVaultCertificateProperties struct { + // VaultURI - The vault uri of user key vault. + VaultURI *string `json:"vaultUri,omitempty"` + // KeyVaultCertName - The certificate name of key vault. + KeyVaultCertName *string `json:"keyVaultCertName,omitempty"` + // CertVersion - The certificate version of key vault. + CertVersion *string `json:"certVersion,omitempty"` + // ExcludePrivateKey - Optional. If set to true, it will not import private key from key vault. + ExcludePrivateKey *bool `json:"excludePrivateKey,omitempty"` + // Thumbprint - READ-ONLY; The thumbprint of certificate. + Thumbprint *string `json:"thumbprint,omitempty"` + // Issuer - READ-ONLY; The issuer of certificate. + Issuer *string `json:"issuer,omitempty"` + // IssuedDate - READ-ONLY; The issue date of certificate. + IssuedDate *string `json:"issuedDate,omitempty"` + // ExpirationDate - READ-ONLY; The expiration date of certificate. + ExpirationDate *string `json:"expirationDate,omitempty"` + // ActivateDate - READ-ONLY; The activate date of certificate. + ActivateDate *string `json:"activateDate,omitempty"` + // SubjectName - READ-ONLY; The subject name of certificate. + SubjectName *string `json:"subjectName,omitempty"` + // DNSNames - READ-ONLY; The domain list of certificate. + DNSNames *[]string `json:"dnsNames,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the Certificate. Possible values include: 'CertificateResourceProvisioningStateCreating', 'CertificateResourceProvisioningStateUpdating', 'CertificateResourceProvisioningStateSucceeded', 'CertificateResourceProvisioningStateFailed', 'CertificateResourceProvisioningStateDeleting' + ProvisioningState CertificateResourceProvisioningState `json:"provisioningState,omitempty"` + // Type - Possible values include: 'TypeBasicCertificatePropertiesTypeCertificateProperties', 'TypeBasicCertificatePropertiesTypeKeyVaultCertificate', 'TypeBasicCertificatePropertiesTypeContentCertificate' + Type TypeBasicCertificateProperties `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for KeyVaultCertificateProperties. +func (kvcp KeyVaultCertificateProperties) MarshalJSON() ([]byte, error) { + kvcp.Type = TypeBasicCertificatePropertiesTypeKeyVaultCertificate + objectMap := make(map[string]interface{}) + if kvcp.VaultURI != nil { + objectMap["vaultUri"] = kvcp.VaultURI + } + if kvcp.KeyVaultCertName != nil { + objectMap["keyVaultCertName"] = kvcp.KeyVaultCertName + } + if kvcp.CertVersion != nil { + objectMap["certVersion"] = kvcp.CertVersion + } + if kvcp.ExcludePrivateKey != nil { + objectMap["excludePrivateKey"] = kvcp.ExcludePrivateKey + } + if kvcp.Type != "" { + objectMap["type"] = kvcp.Type + } + return json.Marshal(objectMap) +} + +// AsKeyVaultCertificateProperties is the BasicCertificateProperties implementation for KeyVaultCertificateProperties. +func (kvcp KeyVaultCertificateProperties) AsKeyVaultCertificateProperties() (*KeyVaultCertificateProperties, bool) { + return &kvcp, true +} + +// AsContentCertificateProperties is the BasicCertificateProperties implementation for KeyVaultCertificateProperties. +func (kvcp KeyVaultCertificateProperties) AsContentCertificateProperties() (*ContentCertificateProperties, bool) { + return nil, false +} + +// AsCertificateProperties is the BasicCertificateProperties implementation for KeyVaultCertificateProperties. +func (kvcp KeyVaultCertificateProperties) AsCertificateProperties() (*CertificateProperties, bool) { + return nil, false +} + +// AsBasicCertificateProperties is the BasicCertificateProperties implementation for KeyVaultCertificateProperties. +func (kvcp KeyVaultCertificateProperties) AsBasicCertificateProperties() (BasicCertificateProperties, bool) { + return &kvcp, true +} + +// LoadedCertificate loaded certificate payload +type LoadedCertificate struct { + // ResourceID - Resource Id of loaded certificate + ResourceID *string `json:"resourceId,omitempty"` + // LoadTrustStore - Indicate whether the certificate will be loaded into default trust store, only work for Java runtime. + LoadTrustStore *bool `json:"loadTrustStore,omitempty"` +} + +// LogFileURLResponse log file URL payload +type LogFileURLResponse struct { + autorest.Response `json:"-"` + // URL - URL of the log file + URL *string `json:"url,omitempty"` +} + +// LogSpecification specifications of the Log for Azure Monitoring +type LogSpecification struct { + // Name - Name of the log + Name *string `json:"name,omitempty"` + // DisplayName - Localized friendly display name of the log + DisplayName *string `json:"displayName,omitempty"` + // BlobDuration - Blob duration of the log + BlobDuration *string `json:"blobDuration,omitempty"` +} + +// ManagedIdentityProperties managed identity properties retrieved from ARM request headers. +type ManagedIdentityProperties struct { + // Type - Type of the managed identity. Possible values include: 'ManagedIdentityTypeNone', 'ManagedIdentityTypeSystemAssigned', 'ManagedIdentityTypeUserAssigned', 'ManagedIdentityTypeSystemAssignedUserAssigned' + Type ManagedIdentityType `json:"type,omitempty"` + // PrincipalID - Principal Id of system-assigned managed identity. + PrincipalID *string `json:"principalId,omitempty"` + // TenantID - Tenant Id of system-assigned managed identity. + TenantID *string `json:"tenantId,omitempty"` + // UserAssignedIdentities - Properties of user-assigned managed identities + UserAssignedIdentities map[string]*UserAssignedManagedIdentity `json:"userAssignedIdentities"` +} + +// MarshalJSON is the custom marshaler for ManagedIdentityProperties. +func (mip ManagedIdentityProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if mip.Type != "" { + objectMap["type"] = mip.Type + } + if mip.PrincipalID != nil { + objectMap["principalId"] = mip.PrincipalID + } + if mip.TenantID != nil { + objectMap["tenantId"] = mip.TenantID + } + if mip.UserAssignedIdentities != nil { + objectMap["userAssignedIdentities"] = mip.UserAssignedIdentities + } + return json.Marshal(objectMap) +} + +// MarketplaceResource purchasing 3rd Party product for one Azure Spring Apps instance +type MarketplaceResource struct { + // Plan - The plan id of the 3rd Party Artifact that is being procured. + Plan *string `json:"plan,omitempty"` + // Publisher - The publisher id of the 3rd Party Artifact that is being bought. + Publisher *string `json:"publisher,omitempty"` + // Product - The 3rd Party artifact that is being procured. + Product *string `json:"product,omitempty"` +} + +// MetricDimension specifications of the Dimension of metrics +type MetricDimension struct { + // Name - Name of the dimension + Name *string `json:"name,omitempty"` + // DisplayName - Localized friendly display name of the dimension + DisplayName *string `json:"displayName,omitempty"` + // ToBeExportedForShoebox - Whether this dimension should be included for the Shoebox export scenario + ToBeExportedForShoebox *bool `json:"toBeExportedForShoebox,omitempty"` +} + +// MetricSpecification specifications of the Metrics for Azure Monitoring +type MetricSpecification struct { + // Name - Name of the metric + Name *string `json:"name,omitempty"` + // DisplayName - Localized friendly display name of the metric + DisplayName *string `json:"displayName,omitempty"` + // DisplayDescription - Localized friendly description of the metric + DisplayDescription *string `json:"displayDescription,omitempty"` + // Unit - Unit that makes sense for the metric + Unit *string `json:"unit,omitempty"` + // Category - Name of the metric category that the metric belongs to. A metric can only belong to a single category. + Category *string `json:"category,omitempty"` + // AggregationType - Only provide one value for this field. Valid values: Average, Minimum, Maximum, Total, Count. + AggregationType *string `json:"aggregationType,omitempty"` + // SupportedAggregationTypes - Supported aggregation types + SupportedAggregationTypes *[]string `json:"supportedAggregationTypes,omitempty"` + // SupportedTimeGrainTypes - Supported time grain types + SupportedTimeGrainTypes *[]string `json:"supportedTimeGrainTypes,omitempty"` + // FillGapWithZero - Optional. If set to true, then zero will be returned for time duration where no metric is emitted/published. + FillGapWithZero *bool `json:"fillGapWithZero,omitempty"` + // Dimensions - Dimensions of the metric + Dimensions *[]MetricDimension `json:"dimensions,omitempty"` + // SourceMdmNamespace - Name of the MDM namespace. Optional. + SourceMdmNamespace *string `json:"sourceMdmNamespace,omitempty"` +} + +// MonitoringSettingProperties monitoring Setting properties payload +type MonitoringSettingProperties struct { + // ProvisioningState - READ-ONLY; State of the Monitoring Setting. Possible values include: 'MonitoringSettingStateNotAvailable', 'MonitoringSettingStateFailed', 'MonitoringSettingStateSucceeded', 'MonitoringSettingStateUpdating' + ProvisioningState MonitoringSettingState `json:"provisioningState,omitempty"` + // Error - Error when apply Monitoring Setting changes. + Error *Error `json:"error,omitempty"` + // TraceEnabled - Indicates whether enable the trace functionality, which will be deprecated since api version 2020-11-01-preview. Please leverage appInsightsInstrumentationKey to indicate if monitoringSettings enabled or not + TraceEnabled *bool `json:"traceEnabled,omitempty"` + // AppInsightsInstrumentationKey - Target application insight instrumentation key, null or whitespace include empty will disable monitoringSettings + AppInsightsInstrumentationKey *string `json:"appInsightsInstrumentationKey,omitempty"` + // AppInsightsSamplingRate - Indicates the sampling rate of application insight agent, should be in range [0.0, 100.0] + AppInsightsSamplingRate *float64 `json:"appInsightsSamplingRate,omitempty"` + // AppInsightsAgentVersions - Indicates the versions of application insight agent + AppInsightsAgentVersions *ApplicationInsightsAgentVersions `json:"appInsightsAgentVersions,omitempty"` +} + +// MarshalJSON is the custom marshaler for MonitoringSettingProperties. +func (msp MonitoringSettingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if msp.Error != nil { + objectMap["error"] = msp.Error + } + if msp.TraceEnabled != nil { + objectMap["traceEnabled"] = msp.TraceEnabled + } + if msp.AppInsightsInstrumentationKey != nil { + objectMap["appInsightsInstrumentationKey"] = msp.AppInsightsInstrumentationKey + } + if msp.AppInsightsSamplingRate != nil { + objectMap["appInsightsSamplingRate"] = msp.AppInsightsSamplingRate + } + if msp.AppInsightsAgentVersions != nil { + objectMap["appInsightsAgentVersions"] = msp.AppInsightsAgentVersions + } + return json.Marshal(objectMap) +} + +// MonitoringSettingResource monitoring Setting resource +type MonitoringSettingResource struct { + autorest.Response `json:"-"` + // Properties - Properties of the Monitoring Setting resource + Properties *MonitoringSettingProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for MonitoringSettingResource. +func (msr MonitoringSettingResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if msr.Properties != nil { + objectMap["properties"] = msr.Properties + } + if msr.SystemData != nil { + objectMap["systemData"] = msr.SystemData + } + return json.Marshal(objectMap) +} + +// MonitoringSettingsUpdatePatchFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type MonitoringSettingsUpdatePatchFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(MonitoringSettingsClient) (MonitoringSettingResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *MonitoringSettingsUpdatePatchFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for MonitoringSettingsUpdatePatchFuture.Result. +func (future *MonitoringSettingsUpdatePatchFuture) result(client MonitoringSettingsClient) (msr MonitoringSettingResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsUpdatePatchFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + msr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.MonitoringSettingsUpdatePatchFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if msr.Response.Response, err = future.GetResult(sender); err == nil && msr.Response.Response.StatusCode != http.StatusNoContent { + msr, err = client.UpdatePatchResponder(msr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsUpdatePatchFuture", "Result", msr.Response.Response, "Failure responding to request") + } + } + return +} + +// MonitoringSettingsUpdatePutFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type MonitoringSettingsUpdatePutFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(MonitoringSettingsClient) (MonitoringSettingResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *MonitoringSettingsUpdatePutFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for MonitoringSettingsUpdatePutFuture.Result. +func (future *MonitoringSettingsUpdatePutFuture) result(client MonitoringSettingsClient) (msr MonitoringSettingResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsUpdatePutFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + msr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.MonitoringSettingsUpdatePutFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if msr.Response.Response, err = future.GetResult(sender); err == nil && msr.Response.Response.StatusCode != http.StatusNoContent { + msr, err = client.UpdatePutResponder(msr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsUpdatePutFuture", "Result", msr.Response.Response, "Failure responding to request") + } + } + return +} + +// NameAvailability name availability result payload +type NameAvailability struct { + autorest.Response `json:"-"` + // NameAvailable - Indicates whether the name is available + NameAvailable *bool `json:"nameAvailable,omitempty"` + // Reason - Reason why the name is not available + Reason *string `json:"reason,omitempty"` + // Message - Message why the name is not available + Message *string `json:"message,omitempty"` +} + +// NameAvailabilityParameters name availability parameters payload +type NameAvailabilityParameters struct { + // Type - Type of the resource to check name availability + Type *string `json:"type,omitempty"` + // Name - Name to be checked + Name *string `json:"name,omitempty"` +} + +// NetCoreZipUploadedUserSourceInfo uploaded Jar binary for a deployment +type NetCoreZipUploadedUserSourceInfo struct { + // NetCoreMainEntryPath - The path to the .NET executable relative to zip root + NetCoreMainEntryPath *string `json:"netCoreMainEntryPath,omitempty"` + // RuntimeVersion - Runtime version of the .Net file + RuntimeVersion *string `json:"runtimeVersion,omitempty"` + // RelativePath - Relative path of the storage which stores the source + RelativePath *string `json:"relativePath,omitempty"` + // Version - Version of the source + Version *string `json:"version,omitempty"` + // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' + Type TypeBasicUserSourceInfo `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) MarshalJSON() ([]byte, error) { + nczuusi.Type = TypeBasicUserSourceInfoTypeNetCoreZip + objectMap := make(map[string]interface{}) + if nczuusi.NetCoreMainEntryPath != nil { + objectMap["netCoreMainEntryPath"] = nczuusi.NetCoreMainEntryPath + } + if nczuusi.RuntimeVersion != nil { + objectMap["runtimeVersion"] = nczuusi.RuntimeVersion + } + if nczuusi.RelativePath != nil { + objectMap["relativePath"] = nczuusi.RelativePath + } + if nczuusi.Version != nil { + objectMap["version"] = nczuusi.Version + } + if nczuusi.Type != "" { + objectMap["type"] = nczuusi.Type + } + return json.Marshal(objectMap) +} + +// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { + return &nczuusi, true +} + +// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { + return &nczuusi, true +} + +// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { + return nil, false +} + +// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { + return nil, false +} + +// AsUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { + return nil, false +} + +// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. +func (nczuusi NetCoreZipUploadedUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { + return &nczuusi, true +} + +// NetworkProfile service network profile payload +type NetworkProfile struct { + // ServiceRuntimeSubnetID - Fully qualified resource Id of the subnet to host Azure Spring Apps Service Runtime + ServiceRuntimeSubnetID *string `json:"serviceRuntimeSubnetId,omitempty"` + // AppSubnetID - Fully qualified resource Id of the subnet to host customer apps in Azure Spring Apps + AppSubnetID *string `json:"appSubnetId,omitempty"` + // ServiceCidr - Azure Spring Apps service reserved CIDR + ServiceCidr *string `json:"serviceCidr,omitempty"` + // ServiceRuntimeNetworkResourceGroup - Name of the resource group containing network resources of Azure Spring Apps Service Runtime + ServiceRuntimeNetworkResourceGroup *string `json:"serviceRuntimeNetworkResourceGroup,omitempty"` + // AppNetworkResourceGroup - Name of the resource group containing network resources for customer apps in Azure Spring Apps + AppNetworkResourceGroup *string `json:"appNetworkResourceGroup,omitempty"` + // OutboundIPs - READ-ONLY; Desired outbound IP resources for Azure Spring Apps resource. + OutboundIPs *NetworkProfileOutboundIPs `json:"outboundIPs,omitempty"` + // RequiredTraffics - READ-ONLY; Required inbound or outbound traffics for Azure Spring Apps resource. + RequiredTraffics *[]RequiredTraffic `json:"requiredTraffics,omitempty"` + // IngressConfig - Ingress configuration payload for Azure Spring Apps resource. + IngressConfig *IngressConfig `json:"ingressConfig,omitempty"` +} + +// MarshalJSON is the custom marshaler for NetworkProfile. +func (np NetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if np.ServiceRuntimeSubnetID != nil { + objectMap["serviceRuntimeSubnetId"] = np.ServiceRuntimeSubnetID + } + if np.AppSubnetID != nil { + objectMap["appSubnetId"] = np.AppSubnetID + } + if np.ServiceCidr != nil { + objectMap["serviceCidr"] = np.ServiceCidr + } + if np.ServiceRuntimeNetworkResourceGroup != nil { + objectMap["serviceRuntimeNetworkResourceGroup"] = np.ServiceRuntimeNetworkResourceGroup + } + if np.AppNetworkResourceGroup != nil { + objectMap["appNetworkResourceGroup"] = np.AppNetworkResourceGroup + } + if np.IngressConfig != nil { + objectMap["ingressConfig"] = np.IngressConfig + } + return json.Marshal(objectMap) +} + +// NetworkProfileOutboundIPs desired outbound IP resources for Azure Spring Apps resource. +type NetworkProfileOutboundIPs struct { + // PublicIPs - READ-ONLY; A list of public IP addresses. + PublicIPs *[]string `json:"publicIPs,omitempty"` +} + +// MarshalJSON is the custom marshaler for NetworkProfileOutboundIPs. +func (npP NetworkProfileOutboundIPs) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// OperationDetail operation detail payload +type OperationDetail struct { + // Name - Name of the operation + Name *string `json:"name,omitempty"` + // IsDataAction - Indicates whether the operation is a data action + IsDataAction *bool `json:"isDataAction,omitempty"` + // Display - Display of the operation + Display *OperationDisplay `json:"display,omitempty"` + // ActionType - READ-ONLY; Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. Possible values include: 'ActionTypeInternal' + ActionType ActionType `json:"actionType,omitempty"` + // Origin - Origin of the operation + Origin *string `json:"origin,omitempty"` + // Properties - Properties of the operation + Properties *OperationProperties `json:"properties,omitempty"` +} + +// MarshalJSON is the custom marshaler for OperationDetail. +func (od OperationDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if od.Name != nil { + objectMap["name"] = od.Name + } + if od.IsDataAction != nil { + objectMap["isDataAction"] = od.IsDataAction + } + if od.Display != nil { + objectMap["display"] = od.Display + } + if od.Origin != nil { + objectMap["origin"] = od.Origin + } + if od.Properties != nil { + objectMap["properties"] = od.Properties + } + return json.Marshal(objectMap) +} + +// OperationDisplay operation display payload +type OperationDisplay struct { + // Provider - Resource provider of the operation + Provider *string `json:"provider,omitempty"` + // Resource - Resource of the operation + Resource *string `json:"resource,omitempty"` + // Operation - Localized friendly name for the operation + Operation *string `json:"operation,omitempty"` + // Description - Localized friendly description for the operation + Description *string `json:"description,omitempty"` +} + +// OperationProperties extra Operation properties +type OperationProperties struct { + // ServiceSpecification - Service specifications of the operation + ServiceSpecification *ServiceSpecification `json:"serviceSpecification,omitempty"` +} + +// PersistentDisk persistent disk payload +type PersistentDisk struct { + // SizeInGB - Size of the persistent disk in GB + SizeInGB *int32 `json:"sizeInGB,omitempty"` + // UsedInGB - READ-ONLY; Size of the used persistent disk in GB + UsedInGB *int32 `json:"usedInGB,omitempty"` + // MountPath - Mount path of the persistent disk + MountPath *string `json:"mountPath,omitempty"` +} + +// MarshalJSON is the custom marshaler for PersistentDisk. +func (pd PersistentDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pd.SizeInGB != nil { + objectMap["sizeInGB"] = pd.SizeInGB + } + if pd.MountPath != nil { + objectMap["mountPath"] = pd.MountPath + } + return json.Marshal(objectMap) +} + +// Probe probe describes a health check to be performed against an App Instance to determine whether it is +// alive or ready to receive traffic. +type Probe struct { + // ProbeAction - The action of the probe. + ProbeAction BasicProbeAction `json:"probeAction,omitempty"` + // DisableProbe - Indicate whether the probe is disabled. + DisableProbe *bool `json:"disableProbe,omitempty"` + // InitialDelaySeconds - Number of seconds after the App Instance has started before probes are initiated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes + InitialDelaySeconds *int32 `json:"initialDelaySeconds,omitempty"` + // PeriodSeconds - How often (in seconds) to perform the probe. Minimum value is 1. + PeriodSeconds *int32 `json:"periodSeconds,omitempty"` + // TimeoutSeconds - Number of seconds after which the probe times out. Minimum value is 1. + TimeoutSeconds *int32 `json:"timeoutSeconds,omitempty"` + // FailureThreshold - Minimum consecutive failures for the probe to be considered failed after having succeeded. Minimum value is 1. + FailureThreshold *int32 `json:"failureThreshold,omitempty"` + // SuccessThreshold - Minimum consecutive successes for the probe to be considered successful after having failed. Must be 1 for liveness and startup. Minimum value is 1. + SuccessThreshold *int32 `json:"successThreshold,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for Probe struct. +func (p *Probe) 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 "probeAction": + if v != nil { + probeAction, err := unmarshalBasicProbeAction(*v) + if err != nil { + return err + } + p.ProbeAction = probeAction + } + case "disableProbe": + if v != nil { + var disableProbe bool + err = json.Unmarshal(*v, &disableProbe) + if err != nil { + return err + } + p.DisableProbe = &disableProbe + } + case "initialDelaySeconds": + if v != nil { + var initialDelaySeconds int32 + err = json.Unmarshal(*v, &initialDelaySeconds) + if err != nil { + return err + } + p.InitialDelaySeconds = &initialDelaySeconds + } + case "periodSeconds": + if v != nil { + var periodSeconds int32 + err = json.Unmarshal(*v, &periodSeconds) + if err != nil { + return err + } + p.PeriodSeconds = &periodSeconds + } + case "timeoutSeconds": + if v != nil { + var timeoutSeconds int32 + err = json.Unmarshal(*v, &timeoutSeconds) + if err != nil { + return err + } + p.TimeoutSeconds = &timeoutSeconds + } + case "failureThreshold": + if v != nil { + var failureThreshold int32 + err = json.Unmarshal(*v, &failureThreshold) + if err != nil { + return err + } + p.FailureThreshold = &failureThreshold + } + case "successThreshold": + if v != nil { + var successThreshold int32 + err = json.Unmarshal(*v, &successThreshold) + if err != nil { + return err + } + p.SuccessThreshold = &successThreshold + } + } + } + + return nil +} + +// BasicProbeAction the action of the probe. +type BasicProbeAction interface { + AsHTTPGetAction() (*HTTPGetAction, bool) + AsExecAction() (*ExecAction, bool) + AsTCPSocketAction() (*TCPSocketAction, bool) + AsProbeAction() (*ProbeAction, bool) +} + +// ProbeAction the action of the probe. +type ProbeAction struct { + // Type - Possible values include: 'TypeBasicProbeActionTypeProbeAction', 'TypeBasicProbeActionTypeHTTPGetAction', 'TypeBasicProbeActionTypeExecAction', 'TypeBasicProbeActionTypeTCPSocketAction' + Type TypeBasicProbeAction `json:"type,omitempty"` +} + +func unmarshalBasicProbeAction(body []byte) (BasicProbeAction, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["type"] { + case string(TypeBasicProbeActionTypeHTTPGetAction): + var hga HTTPGetAction + err := json.Unmarshal(body, &hga) + return hga, err + case string(TypeBasicProbeActionTypeExecAction): + var ea ExecAction + err := json.Unmarshal(body, &ea) + return ea, err + case string(TypeBasicProbeActionTypeTCPSocketAction): + var tsa TCPSocketAction + err := json.Unmarshal(body, &tsa) + return tsa, err + default: + var pa ProbeAction + err := json.Unmarshal(body, &pa) + return pa, err + } +} +func unmarshalBasicProbeActionArray(body []byte) ([]BasicProbeAction, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + paArray := make([]BasicProbeAction, len(rawMessages)) + + for index, rawMessage := range rawMessages { + pa, err := unmarshalBasicProbeAction(*rawMessage) + if err != nil { + return nil, err + } + paArray[index] = pa + } + return paArray, nil +} + +// MarshalJSON is the custom marshaler for ProbeAction. +func (pa ProbeAction) MarshalJSON() ([]byte, error) { + pa.Type = TypeBasicProbeActionTypeProbeAction + objectMap := make(map[string]interface{}) + if pa.Type != "" { + objectMap["type"] = pa.Type + } + return json.Marshal(objectMap) +} + +// AsHTTPGetAction is the BasicProbeAction implementation for ProbeAction. +func (pa ProbeAction) AsHTTPGetAction() (*HTTPGetAction, bool) { + return nil, false +} + +// AsExecAction is the BasicProbeAction implementation for ProbeAction. +func (pa ProbeAction) AsExecAction() (*ExecAction, bool) { + return nil, false +} + +// AsTCPSocketAction is the BasicProbeAction implementation for ProbeAction. +func (pa ProbeAction) AsTCPSocketAction() (*TCPSocketAction, bool) { + return nil, false +} + +// AsProbeAction is the BasicProbeAction implementation for ProbeAction. +func (pa ProbeAction) AsProbeAction() (*ProbeAction, bool) { + return &pa, true +} + +// AsBasicProbeAction is the BasicProbeAction implementation for ProbeAction. +func (pa ProbeAction) AsBasicProbeAction() (BasicProbeAction, bool) { + return &pa, true +} + +// ProxyResource the resource model definition for a ARM proxy resource. It will have everything other than +// required location and tags. +type ProxyResource struct { + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for ProxyResource. +func (pr ProxyResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pr.SystemData != nil { + objectMap["systemData"] = pr.SystemData + } + return json.Marshal(objectMap) +} + +// RegenerateTestKeyRequestPayload regenerate test key request payload +type RegenerateTestKeyRequestPayload struct { + // KeyType - Type of the test key. Possible values include: 'TestKeyTypePrimary', 'TestKeyTypeSecondary' + KeyType TestKeyType `json:"keyType,omitempty"` +} + +// RequiredTraffic required inbound or outbound traffic for Azure Spring Apps resource. +type RequiredTraffic struct { + // Protocol - READ-ONLY; The protocol of required traffic + Protocol *string `json:"protocol,omitempty"` + // Port - READ-ONLY; The port of required traffic + Port *int32 `json:"port,omitempty"` + // Ips - READ-ONLY; The ip list of required traffic + Ips *[]string `json:"ips,omitempty"` + // Fqdns - READ-ONLY; The FQDN list of required traffic + Fqdns *[]string `json:"fqdns,omitempty"` + // Direction - READ-ONLY; The direction of required traffic. Possible values include: 'TrafficDirectionInbound', 'TrafficDirectionOutbound' + Direction TrafficDirection `json:"direction,omitempty"` +} + +// MarshalJSON is the custom marshaler for RequiredTraffic. +func (rt RequiredTraffic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// Resource the core properties of ARM resources. +type Resource struct { + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if r.SystemData != nil { + objectMap["systemData"] = r.SystemData + } + return json.Marshal(objectMap) +} + +// ResourceRequests deployment resource request payload +type ResourceRequests struct { + // CPU - Required CPU. 1 core can be represented by 1 or 1000m. This should be 500m or 1 for Basic tier, and {500m, 1, 2, 3, 4} for Standard tier. + CPU *string `json:"cpu,omitempty"` + // Memory - Required memory. 1 GB can be represented by 1Gi or 1024Mi. This should be {512Mi, 1Gi, 2Gi} for Basic tier, and {512Mi, 1Gi, 2Gi, ..., 8Gi} for Standard tier. + Memory *string `json:"memory,omitempty"` +} + +// ResourceSku describes an available Azure Spring Apps SKU. +type ResourceSku struct { + // ResourceType - Gets the type of resource the SKU applies to. + ResourceType *string `json:"resourceType,omitempty"` + // Name - Gets the name of SKU. + Name *string `json:"name,omitempty"` + // Tier - Gets the tier of SKU. + Tier *string `json:"tier,omitempty"` + // Capacity - Gets the capacity of SKU. + Capacity *SkuCapacity `json:"capacity,omitempty"` + // Locations - Gets the set of locations that the SKU is available. + Locations *[]string `json:"locations,omitempty"` + // LocationInfo - Gets a list of locations and availability zones in those locations where the SKU is available. + LocationInfo *[]ResourceSkuLocationInfo `json:"locationInfo,omitempty"` + // Restrictions - Gets the restrictions because of which SKU cannot be used. This is + // empty if there are no restrictions. + Restrictions *[]ResourceSkuRestrictions `json:"restrictions,omitempty"` +} + +// ResourceSkuCapabilities ... +type ResourceSkuCapabilities struct { + // Name - Gets an invariant to describe the feature. + Name *string `json:"name,omitempty"` + // Value - Gets an invariant if the feature is measured by quantity. + Value *string `json:"value,omitempty"` +} + +// ResourceSkuCollection object that includes an array of Azure Spring Apps SKU and a possible link for +// next set +type ResourceSkuCollection struct { + autorest.Response `json:"-"` + // Value - Collection of resource SKU + Value *[]ResourceSku `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// ResourceSkuCollectionIterator provides access to a complete listing of ResourceSku values. +type ResourceSkuCollectionIterator struct { + i int + page ResourceSkuCollectionPage +} + +// NextWithContext 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 *ResourceSkuCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkuCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ResourceSkuCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ResourceSkuCollectionIterator) 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 ResourceSkuCollectionIterator) Response() ResourceSkuCollection { + 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 ResourceSkuCollectionIterator) Value() ResourceSku { + if !iter.page.NotDone() { + return ResourceSku{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ResourceSkuCollectionIterator type. +func NewResourceSkuCollectionIterator(page ResourceSkuCollectionPage) ResourceSkuCollectionIterator { + return ResourceSkuCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (rsc ResourceSkuCollection) IsEmpty() bool { + return rsc.Value == nil || len(*rsc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (rsc ResourceSkuCollection) hasNextLink() bool { + return rsc.NextLink != nil && len(*rsc.NextLink) != 0 +} + +// resourceSkuCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (rsc ResourceSkuCollection) resourceSkuCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !rsc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(rsc.NextLink))) +} + +// ResourceSkuCollectionPage contains a page of ResourceSku values. +type ResourceSkuCollectionPage struct { + fn func(context.Context, ResourceSkuCollection) (ResourceSkuCollection, error) + rsc ResourceSkuCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ResourceSkuCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkuCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.rsc) + if err != nil { + return err + } + page.rsc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ResourceSkuCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ResourceSkuCollectionPage) NotDone() bool { + return !page.rsc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ResourceSkuCollectionPage) Response() ResourceSkuCollection { + return page.rsc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ResourceSkuCollectionPage) Values() []ResourceSku { + if page.rsc.IsEmpty() { + return nil + } + return *page.rsc.Value +} + +// Creates a new instance of the ResourceSkuCollectionPage type. +func NewResourceSkuCollectionPage(cur ResourceSkuCollection, getNextPage func(context.Context, ResourceSkuCollection) (ResourceSkuCollection, error)) ResourceSkuCollectionPage { + return ResourceSkuCollectionPage{ + fn: getNextPage, + rsc: cur, + } +} + +// ResourceSkuLocationInfo locations and availability zones where the SKU is available +type ResourceSkuLocationInfo struct { + // Location - Gets location of the SKU + Location *string `json:"location,omitempty"` + // Zones - Gets list of availability zones where the SKU is supported. + Zones *[]string `json:"zones,omitempty"` + // ZoneDetails - Gets details of capabilities available to a SKU in specific zones. + ZoneDetails *[]ResourceSkuZoneDetails `json:"zoneDetails,omitempty"` +} + +// ResourceSkuRestrictionInfo information about the restriction where the SKU cannot be used +type ResourceSkuRestrictionInfo struct { + // Locations - Gets locations where the SKU is restricted + Locations *[]string `json:"locations,omitempty"` + // Zones - Gets list of availability zones where the SKU is restricted. + Zones *[]string `json:"zones,omitempty"` +} + +// ResourceSkuRestrictions restrictions where the SKU cannot be used +type ResourceSkuRestrictions struct { + // Type - Gets the type of restrictions. Possible values include: 'Location', 'Zone'. Possible values include: 'ResourceSkuRestrictionsTypeLocation', 'ResourceSkuRestrictionsTypeZone' + Type ResourceSkuRestrictionsType `json:"type,omitempty"` + // Values - Gets the value of restrictions. If the restriction type is set to + // location. This would be different locations where the SKU is restricted. + Values *[]string `json:"values,omitempty"` + // RestrictionInfo - Gets the information about the restriction where the SKU cannot be used. + RestrictionInfo *ResourceSkuRestrictionInfo `json:"restrictionInfo,omitempty"` + // ReasonCode - Gets the reason for restriction. Possible values include: 'QuotaId', 'NotAvailableForSubscription'. Possible values include: 'ResourceSkuRestrictionsReasonCodeQuotaID', 'ResourceSkuRestrictionsReasonCodeNotAvailableForSubscription' + ReasonCode ResourceSkuRestrictionsReasonCode `json:"reasonCode,omitempty"` +} + +// ResourceSkuZoneDetails details of capabilities available to a SKU in specific zones +type ResourceSkuZoneDetails struct { + // Name - Gets the set of zones that the SKU is available in with the + // specified capabilities. + Name *[]string `json:"name,omitempty"` + // Capabilities - Gets a list of capabilities that are available for the SKU in the + // specified list of zones. + Capabilities *[]ResourceSkuCapabilities `json:"capabilities,omitempty"` +} + +// ResourceUploadDefinition resource upload definition payload +type ResourceUploadDefinition struct { + autorest.Response `json:"-"` + // RelativePath - Source relative path + RelativePath *string `json:"relativePath,omitempty"` + // UploadURL - Upload URL + UploadURL *string `json:"uploadUrl,omitempty"` +} + +// ServiceRegistriesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ServiceRegistriesCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ServiceRegistriesClient) (ServiceRegistryResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ServiceRegistriesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ServiceRegistriesCreateOrUpdateFuture.Result. +func (future *ServiceRegistriesCreateOrUpdateFuture) result(client ServiceRegistriesClient) (srr ServiceRegistryResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + srr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ServiceRegistriesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if srr.Response.Response, err = future.GetResult(sender); err == nil && srr.Response.Response.StatusCode != http.StatusNoContent { + srr, err = client.CreateOrUpdateResponder(srr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesCreateOrUpdateFuture", "Result", srr.Response.Response, "Failure responding to request") + } + } + return +} + +// ServiceRegistriesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ServiceRegistriesDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ServiceRegistriesClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ServiceRegistriesDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ServiceRegistriesDeleteFuture.Result. +func (future *ServiceRegistriesDeleteFuture) result(client ServiceRegistriesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ServiceRegistriesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ServiceRegistryInstance collection of instances belong to the Service Registry +type ServiceRegistryInstance struct { + // Name - READ-ONLY; Name of the Service Registry instance + Name *string `json:"name,omitempty"` + // Status - READ-ONLY; Status of the Service Registry instance + Status *string `json:"status,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServiceRegistryInstance. +func (sri ServiceRegistryInstance) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// ServiceRegistryProperties service Registry properties payload +type ServiceRegistryProperties struct { + // ProvisioningState - READ-ONLY; State of the Service Registry. Possible values include: 'ServiceRegistryProvisioningStateCreating', 'ServiceRegistryProvisioningStateUpdating', 'ServiceRegistryProvisioningStateSucceeded', 'ServiceRegistryProvisioningStateFailed', 'ServiceRegistryProvisioningStateDeleting' + ProvisioningState ServiceRegistryProvisioningState `json:"provisioningState,omitempty"` + // ResourceRequests - The requested resource quantity for required CPU and Memory. + ResourceRequests *ServiceRegistryResourceRequests `json:"resourceRequests,omitempty"` + // Instances - READ-ONLY; Collection of instances belong to Service Registry. + Instances *[]ServiceRegistryInstance `json:"instances,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServiceRegistryProperties. +func (srp ServiceRegistryProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if srp.ResourceRequests != nil { + objectMap["resourceRequests"] = srp.ResourceRequests + } + return json.Marshal(objectMap) +} + +// ServiceRegistryResource service Registry resource +type ServiceRegistryResource struct { + autorest.Response `json:"-"` + Properties *ServiceRegistryProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServiceRegistryResource. +func (srr ServiceRegistryResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if srr.Properties != nil { + objectMap["properties"] = srr.Properties + } + if srr.SystemData != nil { + objectMap["systemData"] = srr.SystemData + } + return json.Marshal(objectMap) +} + +// ServiceRegistryResourceCollection object that includes an array of Service Registry resources and a +// possible link for next set +type ServiceRegistryResourceCollection struct { + autorest.Response `json:"-"` + // Value - Collection of Service Registry resources + Value *[]ServiceRegistryResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// ServiceRegistryResourceCollectionIterator provides access to a complete listing of +// ServiceRegistryResource values. +type ServiceRegistryResourceCollectionIterator struct { + i int + page ServiceRegistryResourceCollectionPage +} + +// NextWithContext 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 *ServiceRegistryResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistryResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ServiceRegistryResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ServiceRegistryResourceCollectionIterator) 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 ServiceRegistryResourceCollectionIterator) Response() ServiceRegistryResourceCollection { + 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 ServiceRegistryResourceCollectionIterator) Value() ServiceRegistryResource { + if !iter.page.NotDone() { + return ServiceRegistryResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ServiceRegistryResourceCollectionIterator type. +func NewServiceRegistryResourceCollectionIterator(page ServiceRegistryResourceCollectionPage) ServiceRegistryResourceCollectionIterator { + return ServiceRegistryResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (srrc ServiceRegistryResourceCollection) IsEmpty() bool { + return srrc.Value == nil || len(*srrc.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (srrc ServiceRegistryResourceCollection) hasNextLink() bool { + return srrc.NextLink != nil && len(*srrc.NextLink) != 0 +} + +// serviceRegistryResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (srrc ServiceRegistryResourceCollection) serviceRegistryResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !srrc.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(srrc.NextLink))) +} + +// ServiceRegistryResourceCollectionPage contains a page of ServiceRegistryResource values. +type ServiceRegistryResourceCollectionPage struct { + fn func(context.Context, ServiceRegistryResourceCollection) (ServiceRegistryResourceCollection, error) + srrc ServiceRegistryResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ServiceRegistryResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistryResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.srrc) + if err != nil { + return err + } + page.srrc = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ServiceRegistryResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ServiceRegistryResourceCollectionPage) NotDone() bool { + return !page.srrc.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ServiceRegistryResourceCollectionPage) Response() ServiceRegistryResourceCollection { + return page.srrc +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ServiceRegistryResourceCollectionPage) Values() []ServiceRegistryResource { + if page.srrc.IsEmpty() { + return nil + } + return *page.srrc.Value +} + +// Creates a new instance of the ServiceRegistryResourceCollectionPage type. +func NewServiceRegistryResourceCollectionPage(cur ServiceRegistryResourceCollection, getNextPage func(context.Context, ServiceRegistryResourceCollection) (ServiceRegistryResourceCollection, error)) ServiceRegistryResourceCollectionPage { + return ServiceRegistryResourceCollectionPage{ + fn: getNextPage, + srrc: cur, + } +} + +// ServiceRegistryResourceRequests resource request payload of Service Registry +type ServiceRegistryResourceRequests struct { + // CPU - READ-ONLY; Cpu allocated to each Service Registry instance + CPU *string `json:"cpu,omitempty"` + // Memory - READ-ONLY; Memory allocated to each Service Registry instance + Memory *string `json:"memory,omitempty"` + // InstanceCount - READ-ONLY; Instance count of the Service Registry + InstanceCount *int32 `json:"instanceCount,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServiceRegistryResourceRequests. +func (srrr ServiceRegistryResourceRequests) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// ServiceResource service resource +type ServiceResource struct { + autorest.Response `json:"-"` + // Properties - Properties of the Service resource + Properties *ClusterResourceProperties `json:"properties,omitempty"` + // Sku - Sku of the Service resource + Sku *Sku `json:"sku,omitempty"` + // Location - The GEO location of the resource. + Location *string `json:"location,omitempty"` + // Tags - Tags of the service which is a list of key value pairs that describe the resource. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServiceResource. +func (sr ServiceResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sr.Properties != nil { + objectMap["properties"] = sr.Properties + } + if sr.Sku != nil { + objectMap["sku"] = sr.Sku + } + if sr.Location != nil { + objectMap["location"] = sr.Location + } + if sr.Tags != nil { + objectMap["tags"] = sr.Tags + } + if sr.SystemData != nil { + objectMap["systemData"] = sr.SystemData + } + return json.Marshal(objectMap) +} + +// ServiceResourceList object that includes an array of Service resources and a possible link for next set +type ServiceResourceList struct { + autorest.Response `json:"-"` + // Value - Collection of Service resources + Value *[]ServiceResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// ServiceResourceListIterator provides access to a complete listing of ServiceResource values. +type ServiceResourceListIterator struct { + i int + page ServiceResourceListPage +} + +// NextWithContext 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 *ServiceResourceListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceResourceListIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ServiceResourceListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ServiceResourceListIterator) 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 ServiceResourceListIterator) Response() ServiceResourceList { + 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 ServiceResourceListIterator) Value() ServiceResource { + if !iter.page.NotDone() { + return ServiceResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ServiceResourceListIterator type. +func NewServiceResourceListIterator(page ServiceResourceListPage) ServiceResourceListIterator { + return ServiceResourceListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (srl ServiceResourceList) IsEmpty() bool { + return srl.Value == nil || len(*srl.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (srl ServiceResourceList) hasNextLink() bool { + return srl.NextLink != nil && len(*srl.NextLink) != 0 +} + +// serviceResourceListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (srl ServiceResourceList) serviceResourceListPreparer(ctx context.Context) (*http.Request, error) { + if !srl.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(srl.NextLink))) +} + +// ServiceResourceListPage contains a page of ServiceResource values. +type ServiceResourceListPage struct { + fn func(context.Context, ServiceResourceList) (ServiceResourceList, error) + srl ServiceResourceList +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ServiceResourceListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceResourceListPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.srl) + if err != nil { + return err + } + page.srl = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ServiceResourceListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ServiceResourceListPage) NotDone() bool { + return !page.srl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ServiceResourceListPage) Response() ServiceResourceList { + return page.srl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ServiceResourceListPage) Values() []ServiceResource { + if page.srl.IsEmpty() { + return nil + } + return *page.srl.Value +} + +// Creates a new instance of the ServiceResourceListPage type. +func NewServiceResourceListPage(cur ServiceResourceList, getNextPage func(context.Context, ServiceResourceList) (ServiceResourceList, error)) ServiceResourceListPage { + return ServiceResourceListPage{ + fn: getNextPage, + srl: cur, + } +} + +// ServicesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ServicesCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ServicesClient) (ServiceResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ServicesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ServicesCreateOrUpdateFuture.Result. +func (future *ServicesCreateOrUpdateFuture) result(client ServicesClient) (sr ServiceResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + sr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ServicesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if sr.Response.Response, err = future.GetResult(sender); err == nil && sr.Response.Response.StatusCode != http.StatusNoContent { + sr, err = client.CreateOrUpdateResponder(sr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesCreateOrUpdateFuture", "Result", sr.Response.Response, "Failure responding to request") + } + } + return +} + +// ServicesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ServicesDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ServicesClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ServicesDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ServicesDeleteFuture.Result. +func (future *ServicesDeleteFuture) result(client ServicesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ServicesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ServiceSpecification service specification payload +type ServiceSpecification struct { + // LogSpecifications - Specifications of the Log for Azure Monitoring + LogSpecifications *[]LogSpecification `json:"logSpecifications,omitempty"` + // MetricSpecifications - Specifications of the Metrics for Azure Monitoring + MetricSpecifications *[]MetricSpecification `json:"metricSpecifications,omitempty"` +} + +// ServicesStartFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ServicesStartFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ServicesClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ServicesStartFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ServicesStartFuture.Result. +func (future *ServicesStartFuture) result(client ServicesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesStartFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ServicesStartFuture") + return + } + ar.Response = future.Response() + return +} + +// ServicesStopFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ServicesStopFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ServicesClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ServicesStopFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ServicesStopFuture.Result. +func (future *ServicesStopFuture) result(client ServicesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesStopFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ServicesStopFuture") + return + } + ar.Response = future.Response() + return +} + +// ServicesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ServicesUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(ServicesClient) (ServiceResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *ServicesUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for ServicesUpdateFuture.Result. +func (future *ServicesUpdateFuture) result(client ServicesClient) (sr ServiceResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + sr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.ServicesUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if sr.Response.Response, err = future.GetResult(sender); err == nil && sr.Response.Response.StatusCode != http.StatusNoContent { + sr, err = client.UpdateResponder(sr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesUpdateFuture", "Result", sr.Response.Response, "Failure responding to request") + } + } + return +} + +// ServiceVNetAddons additional Service settings in vnet injection instance +type ServiceVNetAddons struct { + // LogStreamPublicEndpoint - Indicates whether the log stream in vnet injection instance could be accessed from internet. + LogStreamPublicEndpoint *bool `json:"logStreamPublicEndpoint,omitempty"` +} + +// Sku sku of Azure Spring Apps +type Sku struct { + // Name - Name of the Sku + Name *string `json:"name,omitempty"` + // Tier - Tier of the Sku + Tier *string `json:"tier,omitempty"` + // Capacity - Current capacity of the target resource + Capacity *int32 `json:"capacity,omitempty"` +} + +// SkuCapacity the SKU capacity +type SkuCapacity struct { + // Minimum - Gets or sets the minimum. + Minimum *int32 `json:"minimum,omitempty"` + // Maximum - Gets or sets the maximum. + Maximum *int32 `json:"maximum,omitempty"` + // Default - Gets or sets the default. + Default *int32 `json:"default,omitempty"` + // ScaleType - Gets or sets the type of the scale. Possible values include: 'SkuScaleTypeNone', 'SkuScaleTypeManual', 'SkuScaleTypeAutomatic' + ScaleType SkuScaleType `json:"scaleType,omitempty"` +} + +// SourceUploadedUserSourceInfo uploaded Java source code binary for a deployment +type SourceUploadedUserSourceInfo struct { + // ArtifactSelector - Selector for the artifact to be used for the deployment for multi-module projects. This should be + // the relative path to the target module/project. + ArtifactSelector *string `json:"artifactSelector,omitempty"` + // RuntimeVersion - Runtime version of the source file + RuntimeVersion *string `json:"runtimeVersion,omitempty"` + // RelativePath - Relative path of the storage which stores the source + RelativePath *string `json:"relativePath,omitempty"` + // Version - Version of the source + Version *string `json:"version,omitempty"` + // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' + Type TypeBasicUserSourceInfo `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) MarshalJSON() ([]byte, error) { + suusi.Type = TypeBasicUserSourceInfoTypeSource + objectMap := make(map[string]interface{}) + if suusi.ArtifactSelector != nil { + objectMap["artifactSelector"] = suusi.ArtifactSelector + } + if suusi.RuntimeVersion != nil { + objectMap["runtimeVersion"] = suusi.RuntimeVersion + } + if suusi.RelativePath != nil { + objectMap["relativePath"] = suusi.RelativePath + } + if suusi.Version != nil { + objectMap["version"] = suusi.Version + } + if suusi.Type != "" { + objectMap["type"] = suusi.Type + } + return json.Marshal(objectMap) +} + +// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { + return &suusi, true +} + +// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { + return &suusi, true +} + +// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { + return nil, false +} + +// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { + return nil, false +} + +// AsUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { + return nil, false +} + +// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. +func (suusi SourceUploadedUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { + return &suusi, true +} + +// SsoProperties single sign-on related configuration +type SsoProperties struct { + // Scope - It defines the specific actions applications can be allowed to do on a user's behalf + Scope *[]string `json:"scope,omitempty"` + // ClientID - The public identifier for the application + ClientID *string `json:"clientId,omitempty"` + // ClientSecret - The secret known only to the application and the authorization server + ClientSecret *string `json:"clientSecret,omitempty"` + // IssuerURI - The URI of Issuer Identifier + IssuerURI *string `json:"issuerUri,omitempty"` +} + +// StackProperties kPack ClusterStack properties payload +type StackProperties struct { + // ID - Id of the ClusterStack. + ID *string `json:"id,omitempty"` + // Version - Version of the ClusterStack + Version *string `json:"version,omitempty"` +} + +// StorageAccount storage resource of type Azure Storage Account. +type StorageAccount struct { + // AccountName - The account name of the Azure Storage Account. + AccountName *string `json:"accountName,omitempty"` + // AccountKey - The account key of the Azure Storage Account. + AccountKey *string `json:"accountKey,omitempty"` + // StorageType - Possible values include: 'StorageTypeStorageProperties', 'StorageTypeStorageAccount' + StorageType StorageType `json:"storageType,omitempty"` +} + +// MarshalJSON is the custom marshaler for StorageAccount. +func (sa StorageAccount) MarshalJSON() ([]byte, error) { + sa.StorageType = StorageTypeStorageAccount + objectMap := make(map[string]interface{}) + if sa.AccountName != nil { + objectMap["accountName"] = sa.AccountName + } + if sa.AccountKey != nil { + objectMap["accountKey"] = sa.AccountKey + } + if sa.StorageType != "" { + objectMap["storageType"] = sa.StorageType + } + return json.Marshal(objectMap) +} + +// AsStorageAccount is the BasicStorageProperties implementation for StorageAccount. +func (sa StorageAccount) AsStorageAccount() (*StorageAccount, bool) { + return &sa, true +} + +// AsStorageProperties is the BasicStorageProperties implementation for StorageAccount. +func (sa StorageAccount) AsStorageProperties() (*StorageProperties, bool) { + return nil, false +} + +// AsBasicStorageProperties is the BasicStorageProperties implementation for StorageAccount. +func (sa StorageAccount) AsBasicStorageProperties() (BasicStorageProperties, bool) { + return &sa, true +} + +// BasicStorageProperties storage resource payload. +type BasicStorageProperties interface { + AsStorageAccount() (*StorageAccount, bool) + AsStorageProperties() (*StorageProperties, bool) +} + +// StorageProperties storage resource payload. +type StorageProperties struct { + // StorageType - Possible values include: 'StorageTypeStorageProperties', 'StorageTypeStorageAccount' + StorageType StorageType `json:"storageType,omitempty"` +} + +func unmarshalBasicStorageProperties(body []byte) (BasicStorageProperties, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["storageType"] { + case string(StorageTypeStorageAccount): + var sa StorageAccount + err := json.Unmarshal(body, &sa) + return sa, err + default: + var sp StorageProperties + err := json.Unmarshal(body, &sp) + return sp, err + } +} +func unmarshalBasicStoragePropertiesArray(body []byte) ([]BasicStorageProperties, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + spArray := make([]BasicStorageProperties, len(rawMessages)) + + for index, rawMessage := range rawMessages { + sp, err := unmarshalBasicStorageProperties(*rawMessage) + if err != nil { + return nil, err + } + spArray[index] = sp + } + return spArray, nil +} + +// MarshalJSON is the custom marshaler for StorageProperties. +func (sp StorageProperties) MarshalJSON() ([]byte, error) { + sp.StorageType = StorageTypeStorageProperties + objectMap := make(map[string]interface{}) + if sp.StorageType != "" { + objectMap["storageType"] = sp.StorageType + } + return json.Marshal(objectMap) +} + +// AsStorageAccount is the BasicStorageProperties implementation for StorageProperties. +func (sp StorageProperties) AsStorageAccount() (*StorageAccount, bool) { + return nil, false +} + +// AsStorageProperties is the BasicStorageProperties implementation for StorageProperties. +func (sp StorageProperties) AsStorageProperties() (*StorageProperties, bool) { + return &sp, true +} + +// AsBasicStorageProperties is the BasicStorageProperties implementation for StorageProperties. +func (sp StorageProperties) AsBasicStorageProperties() (BasicStorageProperties, bool) { + return &sp, true +} + +// StorageResource storage resource payload. +type StorageResource struct { + autorest.Response `json:"-"` + // Properties - Properties of the storage resource payload. + Properties BasicStorageProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for StorageResource. +func (sr StorageResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + objectMap["properties"] = sr.Properties + if sr.SystemData != nil { + objectMap["systemData"] = sr.SystemData + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for StorageResource struct. +func (sr *StorageResource) 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 { + properties, err := unmarshalBasicStorageProperties(*v) + if err != nil { + return err + } + sr.Properties = properties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + sr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + sr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + sr.Type = &typeVar + } + case "systemData": + if v != nil { + var systemData SystemData + err = json.Unmarshal(*v, &systemData) + if err != nil { + return err + } + sr.SystemData = &systemData + } + } + } + + return nil +} + +// StorageResourceCollection collection compose of storage resources list and a possible link for next +// page. +type StorageResourceCollection struct { + autorest.Response `json:"-"` + // Value - The storage resources list. + Value *[]StorageResource `json:"value,omitempty"` + // NextLink - The link to next page of storage list. + NextLink *string `json:"nextLink,omitempty"` +} + +// StorageResourceCollectionIterator provides access to a complete listing of StorageResource values. +type StorageResourceCollectionIterator struct { + i int + page StorageResourceCollectionPage +} + +// NextWithContext 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 *StorageResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/StorageResourceCollectionIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *StorageResourceCollectionIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter StorageResourceCollectionIterator) 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 StorageResourceCollectionIterator) Response() StorageResourceCollection { + 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 StorageResourceCollectionIterator) Value() StorageResource { + if !iter.page.NotDone() { + return StorageResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the StorageResourceCollectionIterator type. +func NewStorageResourceCollectionIterator(page StorageResourceCollectionPage) StorageResourceCollectionIterator { + return StorageResourceCollectionIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (src StorageResourceCollection) IsEmpty() bool { + return src.Value == nil || len(*src.Value) == 0 +} + +// hasNextLink returns true if the NextLink is not empty. +func (src StorageResourceCollection) hasNextLink() bool { + return src.NextLink != nil && len(*src.NextLink) != 0 +} + +// storageResourceCollectionPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (src StorageResourceCollection) storageResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { + if !src.hasNextLink() { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(src.NextLink))) +} + +// StorageResourceCollectionPage contains a page of StorageResource values. +type StorageResourceCollectionPage struct { + fn func(context.Context, StorageResourceCollection) (StorageResourceCollection, error) + src StorageResourceCollection +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *StorageResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/StorageResourceCollectionPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + for { + next, err := page.fn(ctx, page.src) + if err != nil { + return err + } + page.src = next + if !next.hasNextLink() || !next.IsEmpty() { + break + } + } + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *StorageResourceCollectionPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page StorageResourceCollectionPage) NotDone() bool { + return !page.src.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page StorageResourceCollectionPage) Response() StorageResourceCollection { + return page.src +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page StorageResourceCollectionPage) Values() []StorageResource { + if page.src.IsEmpty() { + return nil + } + return *page.src.Value +} + +// Creates a new instance of the StorageResourceCollectionPage type. +func NewStorageResourceCollectionPage(cur StorageResourceCollection, getNextPage func(context.Context, StorageResourceCollection) (StorageResourceCollection, error)) StorageResourceCollectionPage { + return StorageResourceCollectionPage{ + fn: getNextPage, + src: cur, + } +} + +// StoragesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type StoragesCreateOrUpdateFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(StoragesClient) (StorageResource, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *StoragesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for StoragesCreateOrUpdateFuture.Result. +func (future *StoragesCreateOrUpdateFuture) result(client StoragesClient) (sr StorageResource, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + sr.Response.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.StoragesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if sr.Response.Response, err = future.GetResult(sender); err == nil && sr.Response.Response.StatusCode != http.StatusNoContent { + sr, err = client.CreateOrUpdateResponder(sr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesCreateOrUpdateFuture", "Result", sr.Response.Response, "Failure responding to request") + } + } + return +} + +// StoragesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type StoragesDeleteFuture struct { + azure.FutureAPI + // Result returns the result of the asynchronous operation. + // If the operation has not completed it will return an error. + Result func(StoragesClient) (autorest.Response, error) +} + +// UnmarshalJSON is the custom unmarshaller for CreateFuture. +func (future *StoragesDeleteFuture) UnmarshalJSON(body []byte) error { + var azFuture azure.Future + if err := json.Unmarshal(body, &azFuture); err != nil { + return err + } + future.FutureAPI = &azFuture + future.Result = future.result + return nil +} + +// result is the default implementation for StoragesDeleteFuture.Result. +func (future *StoragesDeleteFuture) result(client StoragesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + ar.Response = future.Response() + err = azure.NewAsyncOpIncompleteError("appplatform.StoragesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// SupportedBuildpackResource supported buildpack resource payload +type SupportedBuildpackResource struct { + autorest.Response `json:"-"` + Properties *SupportedBuildpackResourceProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for SupportedBuildpackResource. +func (sbr SupportedBuildpackResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sbr.Properties != nil { + objectMap["properties"] = sbr.Properties + } + if sbr.SystemData != nil { + objectMap["systemData"] = sbr.SystemData + } + return json.Marshal(objectMap) +} + +// SupportedBuildpackResourceProperties supported buildpack resource properties +type SupportedBuildpackResourceProperties struct { + // BuildpackID - The id of supported buildpack + BuildpackID *string `json:"buildpackId,omitempty"` +} + +// SupportedBuildpacksCollection object that includes an array of supported buildpacks resources and a +// possible link for next set +type SupportedBuildpacksCollection struct { + autorest.Response `json:"-"` + // Value - Collection of supported buildpacks resources + Value *[]SupportedBuildpackResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// SupportedRuntimeVersion supported deployment runtime version descriptor. +type SupportedRuntimeVersion struct { + // Value - The raw value which could be passed to deployment CRUD operations. Possible values include: 'SupportedRuntimeValueJava8', 'SupportedRuntimeValueJava11', 'SupportedRuntimeValueJava17', 'SupportedRuntimeValueNetCore31' + Value SupportedRuntimeValue `json:"value,omitempty"` + // Platform - The platform of this runtime version (possible values: "Java" or ".NET"). Possible values include: 'SupportedRuntimePlatformJava', 'SupportedRuntimePlatformNETCore' + Platform SupportedRuntimePlatform `json:"platform,omitempty"` + // Version - The detailed version (major.minor) of the platform. + Version *string `json:"version,omitempty"` +} + +// SupportedStackResource supported stack resource payload +type SupportedStackResource struct { + autorest.Response `json:"-"` + Properties *SupportedStackResourceProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,omitempty"` +} + +// MarshalJSON is the custom marshaler for SupportedStackResource. +func (ssr SupportedStackResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ssr.Properties != nil { + objectMap["properties"] = ssr.Properties + } + if ssr.SystemData != nil { + objectMap["systemData"] = ssr.SystemData + } + return json.Marshal(objectMap) +} + +// SupportedStackResourceProperties supported stack resource properties +type SupportedStackResourceProperties struct { + // StackID - The id of supported stack + StackID *string `json:"stackId,omitempty"` + // Version - The version of supported stack + Version *string `json:"version,omitempty"` +} + +// SupportedStacksCollection object that includes an array of supported stacks resources and a possible +// link for next set +type SupportedStacksCollection struct { + autorest.Response `json:"-"` + // Value - Collection of supported stacks resources + Value *[]SupportedStackResource `json:"value,omitempty"` + // NextLink - URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string `json:"nextLink,omitempty"` +} + +// SystemData metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // CreatedBy - The identity that created the resource. + CreatedBy *string `json:"createdBy,omitempty"` + // CreatedByType - The type of identity that created the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' + CreatedByType CreatedByType `json:"createdByType,omitempty"` + // CreatedAt - The timestamp of resource creation (UTC). + CreatedAt *date.Time `json:"createdAt,omitempty"` + // LastModifiedBy - The identity that last modified the resource. + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + // LastModifiedByType - The type of identity that last modified the resource. Possible values include: 'LastModifiedByTypeUser', 'LastModifiedByTypeApplication', 'LastModifiedByTypeManagedIdentity', 'LastModifiedByTypeKey' + LastModifiedByType LastModifiedByType `json:"lastModifiedByType,omitempty"` + // LastModifiedAt - The timestamp of resource modification (UTC). + LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` +} + +// TCPSocketAction tCPSocketAction describes an action based on opening a socket +type TCPSocketAction struct { + // Type - Possible values include: 'TypeBasicProbeActionTypeProbeAction', 'TypeBasicProbeActionTypeHTTPGetAction', 'TypeBasicProbeActionTypeExecAction', 'TypeBasicProbeActionTypeTCPSocketAction' + Type TypeBasicProbeAction `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for TCPSocketAction. +func (tsa TCPSocketAction) MarshalJSON() ([]byte, error) { + tsa.Type = TypeBasicProbeActionTypeTCPSocketAction + objectMap := make(map[string]interface{}) + if tsa.Type != "" { + objectMap["type"] = tsa.Type + } + return json.Marshal(objectMap) +} + +// AsHTTPGetAction is the BasicProbeAction implementation for TCPSocketAction. +func (tsa TCPSocketAction) AsHTTPGetAction() (*HTTPGetAction, bool) { + return nil, false +} + +// AsExecAction is the BasicProbeAction implementation for TCPSocketAction. +func (tsa TCPSocketAction) AsExecAction() (*ExecAction, bool) { + return nil, false +} + +// AsTCPSocketAction is the BasicProbeAction implementation for TCPSocketAction. +func (tsa TCPSocketAction) AsTCPSocketAction() (*TCPSocketAction, bool) { + return &tsa, true +} + +// AsProbeAction is the BasicProbeAction implementation for TCPSocketAction. +func (tsa TCPSocketAction) AsProbeAction() (*ProbeAction, bool) { + return nil, false +} + +// AsBasicProbeAction is the BasicProbeAction implementation for TCPSocketAction. +func (tsa TCPSocketAction) AsBasicProbeAction() (BasicProbeAction, bool) { + return &tsa, true +} + +// TemporaryDisk temporary disk payload +type TemporaryDisk struct { + // SizeInGB - Size of the temporary disk in GB + SizeInGB *int32 `json:"sizeInGB,omitempty"` + // MountPath - Mount path of the temporary disk + MountPath *string `json:"mountPath,omitempty"` +} + +// TestKeys test keys payload +type TestKeys struct { + autorest.Response `json:"-"` + // PrimaryKey - Primary key + PrimaryKey *string `json:"primaryKey,omitempty"` + // SecondaryKey - Secondary key + SecondaryKey *string `json:"secondaryKey,omitempty"` + // PrimaryTestEndpoint - Primary test endpoint + PrimaryTestEndpoint *string `json:"primaryTestEndpoint,omitempty"` + // SecondaryTestEndpoint - Secondary test endpoint + SecondaryTestEndpoint *string `json:"secondaryTestEndpoint,omitempty"` + // Enabled - Indicates whether the test endpoint feature enabled or not + Enabled *bool `json:"enabled,omitempty"` +} + +// TrackedResource the resource model definition for a ARM tracked top level resource. +type TrackedResource struct { + // Location - The GEO location of the resource. + Location *string `json:"location,omitempty"` + // Tags - Tags of the service which is a list of key value pairs that describe the resource. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Fully qualified resource Id for the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + SystemData *SystemData `json:"systemData,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.SystemData != nil { + objectMap["systemData"] = tr.SystemData + } + return json.Marshal(objectMap) +} + +// TriggeredBuildResult the build result triggered by a build +type TriggeredBuildResult struct { + // ID - The unique build id of this build result + ID *string `json:"id,omitempty"` +} + +// BasicUploadedUserSourceInfo source with uploaded location +type BasicUploadedUserSourceInfo interface { + AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) + AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) + AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) + AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) +} + +// UploadedUserSourceInfo source with uploaded location +type UploadedUserSourceInfo struct { + // RelativePath - Relative path of the storage which stores the source + RelativePath *string `json:"relativePath,omitempty"` + // Version - Version of the source + Version *string `json:"version,omitempty"` + // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' + Type TypeBasicUserSourceInfo `json:"type,omitempty"` +} + +func unmarshalBasicUploadedUserSourceInfo(body []byte) (BasicUploadedUserSourceInfo, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["type"] { + case string(TypeBasicUserSourceInfoTypeJar): + var juusi JarUploadedUserSourceInfo + err := json.Unmarshal(body, &juusi) + return juusi, err + case string(TypeBasicUserSourceInfoTypeSource): + var suusi SourceUploadedUserSourceInfo + err := json.Unmarshal(body, &suusi) + return suusi, err + case string(TypeBasicUserSourceInfoTypeNetCoreZip): + var nczuusi NetCoreZipUploadedUserSourceInfo + err := json.Unmarshal(body, &nczuusi) + return nczuusi, err + default: + var uusi UploadedUserSourceInfo + err := json.Unmarshal(body, &uusi) + return uusi, err + } +} +func unmarshalBasicUploadedUserSourceInfoArray(body []byte) ([]BasicUploadedUserSourceInfo, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + uusiArray := make([]BasicUploadedUserSourceInfo, len(rawMessages)) + + for index, rawMessage := range rawMessages { + uusi, err := unmarshalBasicUploadedUserSourceInfo(*rawMessage) + if err != nil { + return nil, err + } + uusiArray[index] = uusi + } + return uusiArray, nil +} + +// MarshalJSON is the custom marshaler for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) MarshalJSON() ([]byte, error) { + uusi.Type = TypeBasicUserSourceInfoTypeUploadedUserSourceInfo + objectMap := make(map[string]interface{}) + if uusi.RelativePath != nil { + objectMap["relativePath"] = uusi.RelativePath + } + if uusi.Version != nil { + objectMap["version"] = uusi.Version + } + if uusi.Type != "" { + objectMap["type"] = uusi.Type + } + return json.Marshal(objectMap) +} + +// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { + return &uusi, true +} + +// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { + return &uusi, true +} + +// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { + return nil, false +} + +// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { + return nil, false +} + +// AsUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { + return nil, false +} + +// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. +func (uusi UploadedUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { + return &uusi, true +} + +// UserAssignedManagedIdentity the details of the user-assigned managed identity assigned to an App. +type UserAssignedManagedIdentity struct { + // PrincipalID - READ-ONLY; Principal Id of user-assigned managed identity. + PrincipalID *string `json:"principalId,omitempty"` + // ClientID - READ-ONLY; Client Id of user-assigned managed identity. + ClientID *string `json:"clientId,omitempty"` +} + +// MarshalJSON is the custom marshaler for UserAssignedManagedIdentity. +func (uami UserAssignedManagedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// BasicUserSourceInfo source information for a deployment +type BasicUserSourceInfo interface { + AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) + AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) + AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) + AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) + AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) + AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) + AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) + AsUserSourceInfo() (*UserSourceInfo, bool) +} + +// UserSourceInfo source information for a deployment +type UserSourceInfo struct { + // Version - Version of the source + Version *string `json:"version,omitempty"` + // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' + Type TypeBasicUserSourceInfo `json:"type,omitempty"` +} + +func unmarshalBasicUserSourceInfo(body []byte) (BasicUserSourceInfo, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["type"] { + case string(TypeBasicUserSourceInfoTypeUploadedUserSourceInfo): + var uusi UploadedUserSourceInfo + err := json.Unmarshal(body, &uusi) + return uusi, err + case string(TypeBasicUserSourceInfoTypeJar): + var juusi JarUploadedUserSourceInfo + err := json.Unmarshal(body, &juusi) + return juusi, err + case string(TypeBasicUserSourceInfoTypeSource): + var suusi SourceUploadedUserSourceInfo + err := json.Unmarshal(body, &suusi) + return suusi, err + case string(TypeBasicUserSourceInfoTypeNetCoreZip): + var nczuusi NetCoreZipUploadedUserSourceInfo + err := json.Unmarshal(body, &nczuusi) + return nczuusi, err + case string(TypeBasicUserSourceInfoTypeBuildResult): + var brusi BuildResultUserSourceInfo + err := json.Unmarshal(body, &brusi) + return brusi, err + case string(TypeBasicUserSourceInfoTypeContainer): + var ccusi CustomContainerUserSourceInfo + err := json.Unmarshal(body, &ccusi) + return ccusi, err + default: + var usi UserSourceInfo + err := json.Unmarshal(body, &usi) + return usi, err + } +} +func unmarshalBasicUserSourceInfoArray(body []byte) ([]BasicUserSourceInfo, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + usiArray := make([]BasicUserSourceInfo, len(rawMessages)) + + for index, rawMessage := range rawMessages { + usi, err := unmarshalBasicUserSourceInfo(*rawMessage) + if err != nil { + return nil, err + } + usiArray[index] = usi + } + return usiArray, nil +} + +// MarshalJSON is the custom marshaler for UserSourceInfo. +func (usi UserSourceInfo) MarshalJSON() ([]byte, error) { + usi.Type = TypeBasicUserSourceInfoTypeUserSourceInfo + objectMap := make(map[string]interface{}) + if usi.Version != nil { + objectMap["version"] = usi.Version + } + if usi.Type != "" { + objectMap["type"] = usi.Type + } + return json.Marshal(objectMap) +} + +// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. +func (usi UserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. +func (usi UserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. +func (usi UserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. +func (usi UserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. +func (usi UserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { + return nil, false +} + +// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. +func (usi UserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { + return nil, false +} + +// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. +func (usi UserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { + return nil, false +} + +// AsUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. +func (usi UserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { + return &usi, true +} + +// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. +func (usi UserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { + return &usi, true +} + +// ValidationMessages validate messages of the configuration service git repositories +type ValidationMessages struct { + // Name - The name of the configuration service git repository. + Name *string `json:"name,omitempty"` + // Messages - Detailed validation messages. + Messages *[]string `json:"messages,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/monitoringsettings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/monitoringsettings.go new file mode 100644 index 000000000000..aaa5cd07ce58 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/monitoringsettings.go @@ -0,0 +1,287 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// MonitoringSettingsClient is the REST API for Azure Spring Apps +type MonitoringSettingsClient struct { + BaseClient +} + +// NewMonitoringSettingsClient creates an instance of the MonitoringSettingsClient client. +func NewMonitoringSettingsClient(subscriptionID string) MonitoringSettingsClient { + return NewMonitoringSettingsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewMonitoringSettingsClientWithBaseURI creates an instance of the MonitoringSettingsClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewMonitoringSettingsClientWithBaseURI(baseURI string, subscriptionID string) MonitoringSettingsClient { + return MonitoringSettingsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get get the Monitoring Setting and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client MonitoringSettingsClient) Get(ctx context.Context, resourceGroupName string, serviceName string) (result MonitoringSettingResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/MonitoringSettingsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client MonitoringSettingsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/monitoringSettings/default", 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 MonitoringSettingsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client MonitoringSettingsClient) GetResponder(resp *http.Response) (result MonitoringSettingResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// UpdatePatch update the Monitoring Setting. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// monitoringSettingResource - parameters for the update operation +func (client MonitoringSettingsClient) UpdatePatch(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource) (result MonitoringSettingsUpdatePatchFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/MonitoringSettingsClient.UpdatePatch") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePatchPreparer(ctx, resourceGroupName, serviceName, monitoringSettingResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "UpdatePatch", nil, "Failure preparing request") + return + } + + result, err = client.UpdatePatchSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "UpdatePatch", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePatchPreparer prepares the UpdatePatch request. +func (client MonitoringSettingsClient) UpdatePatchPreparer(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/monitoringSettings/default", pathParameters), + autorest.WithJSON(monitoringSettingResource), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdatePatchSender sends the UpdatePatch request. The method will close the +// http.Response Body if it receives an error. +func (client MonitoringSettingsClient) UpdatePatchSender(req *http.Request) (future MonitoringSettingsUpdatePatchFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdatePatchResponder handles the response to the UpdatePatch request. The method always +// closes the http.Response Body. +func (client MonitoringSettingsClient) UpdatePatchResponder(resp *http.Response) (result MonitoringSettingResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// UpdatePut update the Monitoring Setting. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// monitoringSettingResource - parameters for the update operation +func (client MonitoringSettingsClient) UpdatePut(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource) (result MonitoringSettingsUpdatePutFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/MonitoringSettingsClient.UpdatePut") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: monitoringSettingResource, + Constraints: []validation.Constraint{{Target: "monitoringSettingResource.Properties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "monitoringSettingResource.Properties.AppInsightsSamplingRate", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "monitoringSettingResource.Properties.AppInsightsSamplingRate", Name: validation.InclusiveMaximum, Rule: float64(100), Chain: nil}, + {Target: "monitoringSettingResource.Properties.AppInsightsSamplingRate", Name: validation.InclusiveMinimum, Rule: float64(0), Chain: nil}, + }}, + }}}}}); err != nil { + return result, validation.NewError("appplatform.MonitoringSettingsClient", "UpdatePut", err.Error()) + } + + req, err := client.UpdatePutPreparer(ctx, resourceGroupName, serviceName, monitoringSettingResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "UpdatePut", nil, "Failure preparing request") + return + } + + result, err = client.UpdatePutSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "UpdatePut", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePutPreparer prepares the UpdatePut request. +func (client MonitoringSettingsClient) UpdatePutPreparer(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/monitoringSettings/default", pathParameters), + autorest.WithJSON(monitoringSettingResource), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdatePutSender sends the UpdatePut request. The method will close the +// http.Response Body if it receives an error. +func (client MonitoringSettingsClient) UpdatePutSender(req *http.Request) (future MonitoringSettingsUpdatePutFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdatePutResponder handles the response to the UpdatePut request. The method always +// closes the http.Response Body. +func (client MonitoringSettingsClient) UpdatePutResponder(resp *http.Response) (result MonitoringSettingResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/operations.go new file mode 100644 index 000000000000..83707cfec137 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/operations.go @@ -0,0 +1,140 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// OperationsClient is the REST API for Azure Spring Apps +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 using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists all of the available REST API operations of the Microsoft.AppPlatform provider. +func (client OperationsClient) List(ctx context.Context) (result AvailableOperationsPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") + defer func() { + sc := -1 + if result.ao.Response.Response != nil { + sc = result.ao.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.OperationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.ao.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.OperationsClient", "List", resp, "Failure sending request") + return + } + + result.ao, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.OperationsClient", "List", resp, "Failure responding to request") + return + } + if result.ao.hasNextLink() && result.ao.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.AppPlatform/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 client.Send(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 AvailableOperations, err error) { + err = autorest.Respond( + resp, + 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(ctx context.Context, lastResults AvailableOperations) (result AvailableOperations, err error) { + req, err := lastResults.availableOperationsPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.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, "appplatform.OperationsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.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 AvailableOperationsIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/runtimeversions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/runtimeversions.go new file mode 100644 index 000000000000..a4e59680f208 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/runtimeversions.go @@ -0,0 +1,98 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// RuntimeVersionsClient is the REST API for Azure Spring Apps +type RuntimeVersionsClient struct { + BaseClient +} + +// NewRuntimeVersionsClient creates an instance of the RuntimeVersionsClient client. +func NewRuntimeVersionsClient(subscriptionID string) RuntimeVersionsClient { + return NewRuntimeVersionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewRuntimeVersionsClientWithBaseURI creates an instance of the RuntimeVersionsClient client using a custom endpoint. +// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewRuntimeVersionsClientWithBaseURI(baseURI string, subscriptionID string) RuntimeVersionsClient { + return RuntimeVersionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// ListRuntimeVersions lists all of the available runtime versions supported by Microsoft.AppPlatform provider. +func (client RuntimeVersionsClient) ListRuntimeVersions(ctx context.Context) (result AvailableRuntimeVersions, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/RuntimeVersionsClient.ListRuntimeVersions") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListRuntimeVersionsPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.RuntimeVersionsClient", "ListRuntimeVersions", nil, "Failure preparing request") + return + } + + resp, err := client.ListRuntimeVersionsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.RuntimeVersionsClient", "ListRuntimeVersions", resp, "Failure sending request") + return + } + + result, err = client.ListRuntimeVersionsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.RuntimeVersionsClient", "ListRuntimeVersions", resp, "Failure responding to request") + return + } + + return +} + +// ListRuntimeVersionsPreparer prepares the ListRuntimeVersions request. +func (client RuntimeVersionsClient) ListRuntimeVersionsPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.AppPlatform/runtimeVersions"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListRuntimeVersionsSender sends the ListRuntimeVersions request. The method will close the +// http.Response Body if it receives an error. +func (client RuntimeVersionsClient) ListRuntimeVersionsSender(req *http.Request) (*http.Response, error) { + return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// ListRuntimeVersionsResponder handles the response to the ListRuntimeVersions request. The method always +// closes the http.Response Body. +func (client RuntimeVersionsClient) ListRuntimeVersionsResponder(resp *http.Response) (result AvailableRuntimeVersions, err error) { + err = autorest.Respond( + resp, + 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/serviceregistries.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/serviceregistries.go new file mode 100644 index 000000000000..ca0ad3e92377 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/serviceregistries.go @@ -0,0 +1,393 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// ServiceRegistriesClient is the REST API for Azure Spring Apps +type ServiceRegistriesClient struct { + BaseClient +} + +// NewServiceRegistriesClient creates an instance of the ServiceRegistriesClient client. +func NewServiceRegistriesClient(subscriptionID string) ServiceRegistriesClient { + return NewServiceRegistriesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewServiceRegistriesClientWithBaseURI creates an instance of the ServiceRegistriesClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewServiceRegistriesClientWithBaseURI(baseURI string, subscriptionID string) ServiceRegistriesClient { + return ServiceRegistriesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create the default Service Registry or update the existing Service Registry. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// serviceRegistryName - the name of Service Registry. +func (client ServiceRegistriesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (result ServiceRegistriesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, serviceRegistryName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ServiceRegistriesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "serviceRegistryName": autorest.Encode("path", serviceRegistryName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/serviceRegistries/{serviceRegistryName}", pathParameters), + 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 ServiceRegistriesClient) CreateOrUpdateSender(req *http.Request) (future ServiceRegistriesCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ServiceRegistriesClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceRegistryResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete disable the default Service Registry. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// serviceRegistryName - the name of Service Registry. +func (client ServiceRegistriesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (result ServiceRegistriesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, serviceRegistryName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ServiceRegistriesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "serviceRegistryName": autorest.Encode("path", serviceRegistryName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/serviceRegistries/{serviceRegistryName}", 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 ServiceRegistriesClient) DeleteSender(req *http.Request) (future ServiceRegistriesDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ServiceRegistriesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the Service Registry and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// serviceRegistryName - the name of Service Registry. +func (client ServiceRegistriesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (result ServiceRegistryResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, serviceRegistryName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client ServiceRegistriesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "serviceRegistryName": autorest.Encode("path", serviceRegistryName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/serviceRegistries/{serviceRegistryName}", 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 ServiceRegistriesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ServiceRegistriesClient) GetResponder(resp *http.Response) (result ServiceRegistryResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handles requests to list all resources in a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ServiceRegistriesClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result ServiceRegistryResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.List") + defer func() { + sc := -1 + if result.srrc.Response.Response != nil { + sc = result.srrc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.srrc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "List", resp, "Failure sending request") + return + } + + result.srrc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "List", resp, "Failure responding to request") + return + } + if result.srrc.hasNextLink() && result.srrc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client ServiceRegistriesClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/serviceRegistries", 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 ServiceRegistriesClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ServiceRegistriesClient) ListResponder(resp *http.Response) (result ServiceRegistryResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 ServiceRegistriesClient) listNextResults(ctx context.Context, lastResults ServiceRegistryResourceCollection) (result ServiceRegistryResourceCollection, err error) { + req, err := lastResults.serviceRegistryResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "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, "appplatform.ServiceRegistriesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ServiceRegistriesClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result ServiceRegistryResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/services.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/services.go new file mode 100644 index 000000000000..e96ba204297a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/services.go @@ -0,0 +1,1136 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ServicesClient is the REST API for Azure Spring Apps +type ServicesClient struct { + BaseClient +} + +// NewServicesClient creates an instance of the ServicesClient client. +func NewServicesClient(subscriptionID string) ServicesClient { + return NewServicesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewServicesClientWithBaseURI creates an instance of the ServicesClient client using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewServicesClientWithBaseURI(baseURI string, subscriptionID string) ServicesClient { + return ServicesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability checks that the resource name is valid and is not already in use. +// Parameters: +// location - the region +// availabilityParameters - parameters supplied to the operation. +func (client ServicesClient) CheckNameAvailability(ctx context.Context, location string, availabilityParameters NameAvailabilityParameters) (result NameAvailability, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.CheckNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: availabilityParameters, + Constraints: []validation.Constraint{{Target: "availabilityParameters.Type", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "availabilityParameters.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("appplatform.ServicesClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, location, availabilityParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CheckNameAvailability", resp, "Failure responding to request") + return + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client ServicesClient) CheckNameAvailabilityPreparer(ctx context.Context, location string, availabilityParameters NameAvailabilityParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/locations/{location}/checkNameAvailability", pathParameters), + autorest.WithJSON(availabilityParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client ServicesClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client ServicesClient) CheckNameAvailabilityResponder(resp *http.Response) (result NameAvailability, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate create a new Service or update an exiting Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// resource - parameters for the create or update operation +func (client ServicesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (result ServicesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, resource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ServicesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}", pathParameters), + autorest.WithJSON(resource), + 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 ServicesClient) CreateOrUpdateSender(req *http.Request) (future ServicesCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ServicesClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete operation to delete a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ServicesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string) (result ServicesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}", 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 ServicesClient) DeleteSender(req *http.Request) (future ServicesDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ServicesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// DisableTestEndpoint disable test endpoint functionality for a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ServicesClient) DisableTestEndpoint(ctx context.Context, resourceGroupName string, serviceName string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.DisableTestEndpoint") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DisableTestEndpointPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "DisableTestEndpoint", nil, "Failure preparing request") + return + } + + resp, err := client.DisableTestEndpointSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "DisableTestEndpoint", resp, "Failure sending request") + return + } + + result, err = client.DisableTestEndpointResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "DisableTestEndpoint", resp, "Failure responding to request") + return + } + + return +} + +// DisableTestEndpointPreparer prepares the DisableTestEndpoint request. +func (client ServicesClient) DisableTestEndpointPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/disableTestEndpoint", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DisableTestEndpointSender sends the DisableTestEndpoint request. The method will close the +// http.Response Body if it receives an error. +func (client ServicesClient) DisableTestEndpointSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// DisableTestEndpointResponder handles the response to the DisableTestEndpoint request. The method always +// closes the http.Response Body. +func (client ServicesClient) DisableTestEndpointResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// EnableTestEndpoint enable test endpoint functionality for a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ServicesClient) EnableTestEndpoint(ctx context.Context, resourceGroupName string, serviceName string) (result TestKeys, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.EnableTestEndpoint") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.EnableTestEndpointPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "EnableTestEndpoint", nil, "Failure preparing request") + return + } + + resp, err := client.EnableTestEndpointSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "EnableTestEndpoint", resp, "Failure sending request") + return + } + + result, err = client.EnableTestEndpointResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "EnableTestEndpoint", resp, "Failure responding to request") + return + } + + return +} + +// EnableTestEndpointPreparer prepares the EnableTestEndpoint request. +func (client ServicesClient) EnableTestEndpointPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/enableTestEndpoint", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// EnableTestEndpointSender sends the EnableTestEndpoint request. The method will close the +// http.Response Body if it receives an error. +func (client ServicesClient) EnableTestEndpointSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// EnableTestEndpointResponder handles the response to the EnableTestEndpoint request. The method always +// closes the http.Response Body. +func (client ServicesClient) EnableTestEndpointResponder(resp *http.Response) (result TestKeys, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get get a Service and its properties. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ServicesClient) Get(ctx context.Context, resourceGroupName string, serviceName string) (result ServiceResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client ServicesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}", 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 ServicesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ServicesClient) GetResponder(resp *http.Response) (result ServiceResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List handles requests to list all resources in a resource group. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +func (client ServicesClient) List(ctx context.Context, resourceGroupName string) (result ServiceResourceListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.List") + defer func() { + sc := -1 + if result.srl.Response.Response != nil { + sc = result.srl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.srl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "List", resp, "Failure sending request") + return + } + + result.srl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "List", resp, "Failure responding to request") + return + } + if result.srl.hasNextLink() && result.srl.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client ServicesClient) ListPreparer(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 = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring", 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 ServicesClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ServicesClient) ListResponder(resp *http.Response) (result ServiceResourceList, err error) { + err = autorest.Respond( + resp, + 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 ServicesClient) listNextResults(ctx context.Context, lastResults ServiceResourceList) (result ServiceResourceList, err error) { + req, err := lastResults.serviceResourceListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.ServicesClient", "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, "appplatform.ServicesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ServicesClient) ListComplete(ctx context.Context, resourceGroupName string) (result ServiceResourceListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName) + return +} + +// ListBySubscription handles requests to list all resources in a subscription. +func (client ServicesClient) ListBySubscription(ctx context.Context) (result ServiceResourceListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.ListBySubscription") + defer func() { + sc := -1 + if result.srl.Response.Response != nil { + sc = result.srl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.srl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result.srl, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListBySubscription", resp, "Failure responding to request") + return + } + if result.srl.hasNextLink() && result.srl.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client ServicesClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AppPlatform/Spring", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client ServicesClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client ServicesClient) ListBySubscriptionResponder(resp *http.Response) (result ServiceResourceList, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client ServicesClient) listBySubscriptionNextResults(ctx context.Context, lastResults ServiceResourceList) (result ServiceResourceList, err error) { + req, err := lastResults.serviceResourceListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.ServicesClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "appplatform.ServicesClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client ServicesClient) ListBySubscriptionComplete(ctx context.Context) (result ServiceResourceListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.ListBySubscription") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListBySubscription(ctx) + return +} + +// ListTestKeys list test keys for a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ServicesClient) ListTestKeys(ctx context.Context, resourceGroupName string, serviceName string) (result TestKeys, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.ListTestKeys") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListTestKeysPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListTestKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListTestKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListTestKeys", resp, "Failure sending request") + return + } + + result, err = client.ListTestKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListTestKeys", resp, "Failure responding to request") + return + } + + return +} + +// ListTestKeysPreparer prepares the ListTestKeys request. +func (client ServicesClient) ListTestKeysPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/listTestKeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListTestKeysSender sends the ListTestKeys request. The method will close the +// http.Response Body if it receives an error. +func (client ServicesClient) ListTestKeysSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListTestKeysResponder handles the response to the ListTestKeys request. The method always +// closes the http.Response Body. +func (client ServicesClient) ListTestKeysResponder(resp *http.Response) (result TestKeys, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// RegenerateTestKey regenerate a test key for a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// regenerateTestKeyRequest - parameters for the operation +func (client ServicesClient) RegenerateTestKey(ctx context.Context, resourceGroupName string, serviceName string, regenerateTestKeyRequest RegenerateTestKeyRequestPayload) (result TestKeys, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.RegenerateTestKey") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RegenerateTestKeyPreparer(ctx, resourceGroupName, serviceName, regenerateTestKeyRequest) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "RegenerateTestKey", nil, "Failure preparing request") + return + } + + resp, err := client.RegenerateTestKeySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "RegenerateTestKey", resp, "Failure sending request") + return + } + + result, err = client.RegenerateTestKeyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "RegenerateTestKey", resp, "Failure responding to request") + return + } + + return +} + +// RegenerateTestKeyPreparer prepares the RegenerateTestKey request. +func (client ServicesClient) RegenerateTestKeyPreparer(ctx context.Context, resourceGroupName string, serviceName string, regenerateTestKeyRequest RegenerateTestKeyRequestPayload) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/regenerateTestKey", pathParameters), + autorest.WithJSON(regenerateTestKeyRequest), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RegenerateTestKeySender sends the RegenerateTestKey request. The method will close the +// http.Response Body if it receives an error. +func (client ServicesClient) RegenerateTestKeySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// RegenerateTestKeyResponder handles the response to the RegenerateTestKey request. The method always +// closes the http.Response Body. +func (client ServicesClient) RegenerateTestKeyResponder(resp *http.Response) (result TestKeys, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Start start a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ServicesClient) Start(ctx context.Context, resourceGroupName string, serviceName string) (result ServicesStartFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Start") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StartPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Start", nil, "Failure preparing request") + return + } + + result, err = client.StartSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Start", result.Response(), "Failure sending request") + return + } + + return +} + +// StartPreparer prepares the Start request. +func (client ServicesClient) StartPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/start", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StartSender sends the Start request. The method will close the +// http.Response Body if it receives an error. +func (client ServicesClient) StartSender(req *http.Request) (future ServicesStartFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// StartResponder handles the response to the Start request. The method always +// closes the http.Response Body. +func (client ServicesClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Stop stop a Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client ServicesClient) Stop(ctx context.Context, resourceGroupName string, serviceName string) (result ServicesStopFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Stop") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StopPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Stop", nil, "Failure preparing request") + return + } + + result, err = client.StopSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Stop", result.Response(), "Failure sending request") + return + } + + return +} + +// StopPreparer prepares the Stop request. +func (client ServicesClient) StopPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/stop", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StopSender sends the Stop request. The method will close the +// http.Response Body if it receives an error. +func (client ServicesClient) StopSender(req *http.Request) (future ServicesStopFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// StopResponder handles the response to the Stop request. The method always +// closes the http.Response Body. +func (client ServicesClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update operation to update an exiting Service. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// resource - parameters for the update operation +func (client ServicesClient) Update(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (result ServicesUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Update") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, resource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ServicesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}", pathParameters), + autorest.WithJSON(resource), + 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 ServicesClient) UpdateSender(req *http.Request) (future ServicesUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ServicesClient) UpdateResponder(resp *http.Response) (result ServiceResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-05-01-preview/appplatform/skus.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/skus.go new file mode 100644 index 000000000000..949a9a06d917 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/skus.go @@ -0,0 +1,144 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// SkusClient is the REST API for Azure Spring Apps +type SkusClient struct { + BaseClient +} + +// NewSkusClient creates an instance of the SkusClient client. +func NewSkusClient(subscriptionID string) SkusClient { + return NewSkusClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewSkusClientWithBaseURI creates an instance of the SkusClient client using a custom endpoint. Use this when +// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewSkusClientWithBaseURI(baseURI string, subscriptionID string) SkusClient { + return SkusClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists all of the available skus of the Microsoft.AppPlatform provider. +func (client SkusClient) List(ctx context.Context) (result ResourceSkuCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SkusClient.List") + defer func() { + sc := -1 + if result.rsc.Response.Response != nil { + sc = result.rsc.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.SkusClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.rsc.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.SkusClient", "List", resp, "Failure sending request") + return + } + + result.rsc, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.SkusClient", "List", resp, "Failure responding to request") + return + } + if result.rsc.hasNextLink() && result.rsc.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client SkusClient) ListPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AppPlatform/skus", 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 SkusClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client SkusClient) ListResponder(resp *http.Response) (result ResourceSkuCollection, err error) { + err = autorest.Respond( + resp, + 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 SkusClient) listNextResults(ctx context.Context, lastResults ResourceSkuCollection) (result ResourceSkuCollection, err error) { + req, err := lastResults.resourceSkuCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.SkusClient", "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, "appplatform.SkusClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.SkusClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client SkusClient) ListComplete(ctx context.Context) (result ResourceSkuCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SkusClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/storages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/storages.go new file mode 100644 index 000000000000..86805955513e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/storages.go @@ -0,0 +1,395 @@ +package appplatform + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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/tracing" + "net/http" +) + +// StoragesClient is the REST API for Azure Spring Apps +type StoragesClient struct { + BaseClient +} + +// NewStoragesClient creates an instance of the StoragesClient client. +func NewStoragesClient(subscriptionID string) StoragesClient { + return NewStoragesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewStoragesClientWithBaseURI creates an instance of the StoragesClient client using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewStoragesClientWithBaseURI(baseURI string, subscriptionID string) StoragesClient { + return StoragesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or update storage resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// storageName - the name of the storage resource. +// storageResource - parameters for the create or update operation +func (client StoragesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, storageName string, storageResource StorageResource) (result StoragesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, storageName, storageResource) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client StoragesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, storageName string, storageResource StorageResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "storageName": autorest.Encode("path", storageName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + 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.AppPlatform/Spring/{serviceName}/storages/{storageName}", pathParameters), + autorest.WithJSON(storageResource), + 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 StoragesClient) CreateOrUpdateSender(req *http.Request) (future StoragesCreateOrUpdateFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client StoragesClient) CreateOrUpdateResponder(resp *http.Response) (result StorageResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete the storage resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// storageName - the name of the storage resource. +func (client StoragesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, storageName string) (result StoragesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.Delete") + defer func() { + sc := -1 + if result.FutureAPI != nil && result.FutureAPI.Response() != nil { + sc = result.FutureAPI.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, storageName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client StoragesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, storageName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "storageName": autorest.Encode("path", storageName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/storages/{storageName}", 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 StoragesClient) DeleteSender(req *http.Request) (future StoragesDeleteFuture, err error) { + var resp *http.Response + future.FutureAPI = &azure.Future{} + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + var azf azure.Future + azf, err = azure.NewFutureFromResponse(resp) + future.FutureAPI = &azf + future.Result = future.result + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client StoragesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the storage resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +// storageName - the name of the storage resource. +func (client StoragesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, storageName string) (result StorageResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, storageName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Get", resp, "Failure responding to request") + return + } + + return +} + +// GetPreparer prepares the Get request. +func (client StoragesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, storageName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "storageName": autorest.Encode("path", storageName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/storages/{storageName}", 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 StoragesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client StoragesClient) GetResponder(resp *http.Response) (result StorageResource, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List list all the storages of one Azure Spring Apps resource. +// Parameters: +// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value +// from the Azure Resource Manager API or the portal. +// serviceName - the name of the Service resource. +func (client StoragesClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result StorageResourceCollectionPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.List") + defer func() { + sc := -1 + if result.src.Response.Response != nil { + sc = result.src.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.src.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "List", resp, "Failure sending request") + return + } + + result.src, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "List", resp, "Failure responding to request") + return + } + if result.src.hasNextLink() && result.src.IsEmpty() { + err = result.NextWithContext(ctx) + return + } + + return +} + +// ListPreparer prepares the List request. +func (client StoragesClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2022-05-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/storages", 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 StoragesClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client StoragesClient) ListResponder(resp *http.Response) (result StorageResourceCollection, err error) { + err = autorest.Respond( + resp, + 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 StoragesClient) listNextResults(ctx context.Context, lastResults StorageResourceCollection) (result StorageResourceCollection, err error) { + req, err := lastResults.storageResourceCollectionPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "appplatform.StoragesClient", "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, "appplatform.StoragesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client StoragesClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result StorageResourceCollectionIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, serviceName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/version.go new file mode 100644 index 000000000000..7ab799fb5ab4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform/version.go @@ -0,0 +1,19 @@ +package appplatform + +import "github.com/Azure/azure-sdk-for-go/version" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// +// 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() + " appplatform/2022-05-01-preview" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go b/vendor/github.com/Azure/azure-sdk-for-go/version/version.go index 7a4b91975f03..c4aee486fa06 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/version/version.go @@ -4,4 +4,4 @@ package version // Licensed under the MIT License. See License.txt in the project root for license information. // Number contains the semantic version of this SDK. -const Number = "v64.1.0" +const Number = "v65.0.0" diff --git a/vendor/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md index 5c751f2158cb..5152bf59bf8e 100644 --- a/vendor/github.com/fatih/color/README.md +++ b/vendor/github.com/fatih/color/README.md @@ -78,7 +78,7 @@ notice("Don't forget this...") ### Custom fprint functions (FprintFunc) ```go -blue := color.New(FgBlue).FprintfFunc() +blue := color.New(color.FgBlue).FprintfFunc() blue(myWriter, "important notice: %s", stars) // Mix up with multiple attributes diff --git a/vendor/github.com/golang/protobuf/jsonpb/decode.go b/vendor/github.com/golang/protobuf/jsonpb/decode.go new file mode 100644 index 000000000000..60e82caa9a2d --- /dev/null +++ b/vendor/github.com/golang/protobuf/jsonpb/decode.go @@ -0,0 +1,524 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsonpb + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "math" + "reflect" + "strconv" + "strings" + "time" + + "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/encoding/protojson" + protoV2 "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +const wrapJSONUnmarshalV2 = false + +// UnmarshalNext unmarshals the next JSON object from d into m. +func UnmarshalNext(d *json.Decoder, m proto.Message) error { + return new(Unmarshaler).UnmarshalNext(d, m) +} + +// Unmarshal unmarshals a JSON object from r into m. +func Unmarshal(r io.Reader, m proto.Message) error { + return new(Unmarshaler).Unmarshal(r, m) +} + +// UnmarshalString unmarshals a JSON object from s into m. +func UnmarshalString(s string, m proto.Message) error { + return new(Unmarshaler).Unmarshal(strings.NewReader(s), m) +} + +// Unmarshaler is a configurable object for converting from a JSON +// representation to a protocol buffer object. +type Unmarshaler struct { + // AllowUnknownFields specifies whether to allow messages to contain + // unknown JSON fields, as opposed to failing to unmarshal. + AllowUnknownFields bool + + // AnyResolver is used to resolve the google.protobuf.Any well-known type. + // If unset, the global registry is used by default. + AnyResolver AnyResolver +} + +// JSONPBUnmarshaler is implemented by protobuf messages that customize the way +// they are unmarshaled from JSON. Messages that implement this should also +// implement JSONPBMarshaler so that the custom format can be produced. +// +// The JSON unmarshaling must follow the JSON to proto specification: +// https://developers.google.com/protocol-buffers/docs/proto3#json +// +// Deprecated: Custom types should implement protobuf reflection instead. +type JSONPBUnmarshaler interface { + UnmarshalJSONPB(*Unmarshaler, []byte) error +} + +// Unmarshal unmarshals a JSON object from r into m. +func (u *Unmarshaler) Unmarshal(r io.Reader, m proto.Message) error { + return u.UnmarshalNext(json.NewDecoder(r), m) +} + +// UnmarshalNext unmarshals the next JSON object from d into m. +func (u *Unmarshaler) UnmarshalNext(d *json.Decoder, m proto.Message) error { + if m == nil { + return errors.New("invalid nil message") + } + + // Parse the next JSON object from the stream. + raw := json.RawMessage{} + if err := d.Decode(&raw); err != nil { + return err + } + + // Check for custom unmarshalers first since they may not properly + // implement protobuf reflection that the logic below relies on. + if jsu, ok := m.(JSONPBUnmarshaler); ok { + return jsu.UnmarshalJSONPB(u, raw) + } + + mr := proto.MessageReflect(m) + + // NOTE: For historical reasons, a top-level null is treated as a noop. + // This is incorrect, but kept for compatibility. + if string(raw) == "null" && mr.Descriptor().FullName() != "google.protobuf.Value" { + return nil + } + + if wrapJSONUnmarshalV2 { + // NOTE: If input message is non-empty, we need to preserve merge semantics + // of the old jsonpb implementation. These semantics are not supported by + // the protobuf JSON specification. + isEmpty := true + mr.Range(func(protoreflect.FieldDescriptor, protoreflect.Value) bool { + isEmpty = false // at least one iteration implies non-empty + return false + }) + if !isEmpty { + // Perform unmarshaling into a newly allocated, empty message. + mr = mr.New() + + // Use a defer to copy all unmarshaled fields into the original message. + dst := proto.MessageReflect(m) + defer mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + dst.Set(fd, v) + return true + }) + } + + // Unmarshal using the v2 JSON unmarshaler. + opts := protojson.UnmarshalOptions{ + DiscardUnknown: u.AllowUnknownFields, + } + if u.AnyResolver != nil { + opts.Resolver = anyResolver{u.AnyResolver} + } + return opts.Unmarshal(raw, mr.Interface()) + } else { + if err := u.unmarshalMessage(mr, raw); err != nil { + return err + } + return protoV2.CheckInitialized(mr.Interface()) + } +} + +func (u *Unmarshaler) unmarshalMessage(m protoreflect.Message, in []byte) error { + md := m.Descriptor() + fds := md.Fields() + + if jsu, ok := proto.MessageV1(m.Interface()).(JSONPBUnmarshaler); ok { + return jsu.UnmarshalJSONPB(u, in) + } + + if string(in) == "null" && md.FullName() != "google.protobuf.Value" { + return nil + } + + switch wellKnownType(md.FullName()) { + case "Any": + var jsonObject map[string]json.RawMessage + if err := json.Unmarshal(in, &jsonObject); err != nil { + return err + } + + rawTypeURL, ok := jsonObject["@type"] + if !ok { + return errors.New("Any JSON doesn't have '@type'") + } + typeURL, err := unquoteString(string(rawTypeURL)) + if err != nil { + return fmt.Errorf("can't unmarshal Any's '@type': %q", rawTypeURL) + } + m.Set(fds.ByNumber(1), protoreflect.ValueOfString(typeURL)) + + var m2 protoreflect.Message + if u.AnyResolver != nil { + mi, err := u.AnyResolver.Resolve(typeURL) + if err != nil { + return err + } + m2 = proto.MessageReflect(mi) + } else { + mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL) + if err != nil { + if err == protoregistry.NotFound { + return fmt.Errorf("could not resolve Any message type: %v", typeURL) + } + return err + } + m2 = mt.New() + } + + if wellKnownType(m2.Descriptor().FullName()) != "" { + rawValue, ok := jsonObject["value"] + if !ok { + return errors.New("Any JSON doesn't have 'value'") + } + if err := u.unmarshalMessage(m2, rawValue); err != nil { + return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err) + } + } else { + delete(jsonObject, "@type") + rawJSON, err := json.Marshal(jsonObject) + if err != nil { + return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err) + } + if err = u.unmarshalMessage(m2, rawJSON); err != nil { + return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err) + } + } + + rawWire, err := protoV2.Marshal(m2.Interface()) + if err != nil { + return fmt.Errorf("can't marshal proto %v into Any.Value: %v", typeURL, err) + } + m.Set(fds.ByNumber(2), protoreflect.ValueOfBytes(rawWire)) + return nil + case "BoolValue", "BytesValue", "StringValue", + "Int32Value", "UInt32Value", "FloatValue", + "Int64Value", "UInt64Value", "DoubleValue": + fd := fds.ByNumber(1) + v, err := u.unmarshalValue(m.NewField(fd), in, fd) + if err != nil { + return err + } + m.Set(fd, v) + return nil + case "Duration": + v, err := unquoteString(string(in)) + if err != nil { + return err + } + d, err := time.ParseDuration(v) + if err != nil { + return fmt.Errorf("bad Duration: %v", err) + } + + sec := d.Nanoseconds() / 1e9 + nsec := d.Nanoseconds() % 1e9 + m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec))) + m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec))) + return nil + case "Timestamp": + v, err := unquoteString(string(in)) + if err != nil { + return err + } + t, err := time.Parse(time.RFC3339Nano, v) + if err != nil { + return fmt.Errorf("bad Timestamp: %v", err) + } + + sec := t.Unix() + nsec := t.Nanosecond() + m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec))) + m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec))) + return nil + case "Value": + switch { + case string(in) == "null": + m.Set(fds.ByNumber(1), protoreflect.ValueOfEnum(0)) + case string(in) == "true": + m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(true)) + case string(in) == "false": + m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(false)) + case hasPrefixAndSuffix('"', in, '"'): + s, err := unquoteString(string(in)) + if err != nil { + return fmt.Errorf("unrecognized type for Value %q", in) + } + m.Set(fds.ByNumber(3), protoreflect.ValueOfString(s)) + case hasPrefixAndSuffix('[', in, ']'): + v := m.Mutable(fds.ByNumber(6)) + return u.unmarshalMessage(v.Message(), in) + case hasPrefixAndSuffix('{', in, '}'): + v := m.Mutable(fds.ByNumber(5)) + return u.unmarshalMessage(v.Message(), in) + default: + f, err := strconv.ParseFloat(string(in), 0) + if err != nil { + return fmt.Errorf("unrecognized type for Value %q", in) + } + m.Set(fds.ByNumber(2), protoreflect.ValueOfFloat64(f)) + } + return nil + case "ListValue": + var jsonArray []json.RawMessage + if err := json.Unmarshal(in, &jsonArray); err != nil { + return fmt.Errorf("bad ListValue: %v", err) + } + + lv := m.Mutable(fds.ByNumber(1)).List() + for _, raw := range jsonArray { + ve := lv.NewElement() + if err := u.unmarshalMessage(ve.Message(), raw); err != nil { + return err + } + lv.Append(ve) + } + return nil + case "Struct": + var jsonObject map[string]json.RawMessage + if err := json.Unmarshal(in, &jsonObject); err != nil { + return fmt.Errorf("bad StructValue: %v", err) + } + + mv := m.Mutable(fds.ByNumber(1)).Map() + for key, raw := range jsonObject { + kv := protoreflect.ValueOf(key).MapKey() + vv := mv.NewValue() + if err := u.unmarshalMessage(vv.Message(), raw); err != nil { + return fmt.Errorf("bad value in StructValue for key %q: %v", key, err) + } + mv.Set(kv, vv) + } + return nil + } + + var jsonObject map[string]json.RawMessage + if err := json.Unmarshal(in, &jsonObject); err != nil { + return err + } + + // Handle known fields. + for i := 0; i < fds.Len(); i++ { + fd := fds.Get(i) + if fd.IsWeak() && fd.Message().IsPlaceholder() { + continue // weak reference is not linked in + } + + // Search for any raw JSON value associated with this field. + var raw json.RawMessage + name := string(fd.Name()) + if fd.Kind() == protoreflect.GroupKind { + name = string(fd.Message().Name()) + } + if v, ok := jsonObject[name]; ok { + delete(jsonObject, name) + raw = v + } + name = string(fd.JSONName()) + if v, ok := jsonObject[name]; ok { + delete(jsonObject, name) + raw = v + } + + field := m.NewField(fd) + // Unmarshal the field value. + if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd) && !isSingularJSONPBUnmarshaler(field, fd)) { + continue + } + v, err := u.unmarshalValue(field, raw, fd) + if err != nil { + return err + } + m.Set(fd, v) + } + + // Handle extension fields. + for name, raw := range jsonObject { + if !strings.HasPrefix(name, "[") || !strings.HasSuffix(name, "]") { + continue + } + + // Resolve the extension field by name. + xname := protoreflect.FullName(name[len("[") : len(name)-len("]")]) + xt, _ := protoregistry.GlobalTypes.FindExtensionByName(xname) + if xt == nil && isMessageSet(md) { + xt, _ = protoregistry.GlobalTypes.FindExtensionByName(xname.Append("message_set_extension")) + } + if xt == nil { + continue + } + delete(jsonObject, name) + fd := xt.TypeDescriptor() + if fd.ContainingMessage().FullName() != m.Descriptor().FullName() { + return fmt.Errorf("extension field %q does not extend message %q", xname, m.Descriptor().FullName()) + } + + field := m.NewField(fd) + // Unmarshal the field value. + if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd) && !isSingularJSONPBUnmarshaler(field, fd)) { + continue + } + v, err := u.unmarshalValue(field, raw, fd) + if err != nil { + return err + } + m.Set(fd, v) + } + + if !u.AllowUnknownFields && len(jsonObject) > 0 { + for name := range jsonObject { + return fmt.Errorf("unknown field %q in %v", name, md.FullName()) + } + } + return nil +} + +func isSingularWellKnownValue(fd protoreflect.FieldDescriptor) bool { + if md := fd.Message(); md != nil { + return md.FullName() == "google.protobuf.Value" && fd.Cardinality() != protoreflect.Repeated + } + return false +} + +func isSingularJSONPBUnmarshaler(v protoreflect.Value, fd protoreflect.FieldDescriptor) bool { + if fd.Message() != nil && fd.Cardinality() != protoreflect.Repeated { + _, ok := proto.MessageV1(v.Interface()).(JSONPBUnmarshaler) + return ok + } + return false +} + +func (u *Unmarshaler) unmarshalValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { + switch { + case fd.IsList(): + var jsonArray []json.RawMessage + if err := json.Unmarshal(in, &jsonArray); err != nil { + return v, err + } + lv := v.List() + for _, raw := range jsonArray { + ve, err := u.unmarshalSingularValue(lv.NewElement(), raw, fd) + if err != nil { + return v, err + } + lv.Append(ve) + } + return v, nil + case fd.IsMap(): + var jsonObject map[string]json.RawMessage + if err := json.Unmarshal(in, &jsonObject); err != nil { + return v, err + } + kfd := fd.MapKey() + vfd := fd.MapValue() + mv := v.Map() + for key, raw := range jsonObject { + var kv protoreflect.MapKey + if kfd.Kind() == protoreflect.StringKind { + kv = protoreflect.ValueOf(key).MapKey() + } else { + v, err := u.unmarshalSingularValue(kfd.Default(), []byte(key), kfd) + if err != nil { + return v, err + } + kv = v.MapKey() + } + + vv, err := u.unmarshalSingularValue(mv.NewValue(), raw, vfd) + if err != nil { + return v, err + } + mv.Set(kv, vv) + } + return v, nil + default: + return u.unmarshalSingularValue(v, in, fd) + } +} + +var nonFinite = map[string]float64{ + `"NaN"`: math.NaN(), + `"Infinity"`: math.Inf(+1), + `"-Infinity"`: math.Inf(-1), +} + +func (u *Unmarshaler) unmarshalSingularValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { + switch fd.Kind() { + case protoreflect.BoolKind: + return unmarshalValue(in, new(bool)) + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: + return unmarshalValue(trimQuote(in), new(int32)) + case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + return unmarshalValue(trimQuote(in), new(int64)) + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: + return unmarshalValue(trimQuote(in), new(uint32)) + case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + return unmarshalValue(trimQuote(in), new(uint64)) + case protoreflect.FloatKind: + if f, ok := nonFinite[string(in)]; ok { + return protoreflect.ValueOfFloat32(float32(f)), nil + } + return unmarshalValue(trimQuote(in), new(float32)) + case protoreflect.DoubleKind: + if f, ok := nonFinite[string(in)]; ok { + return protoreflect.ValueOfFloat64(float64(f)), nil + } + return unmarshalValue(trimQuote(in), new(float64)) + case protoreflect.StringKind: + return unmarshalValue(in, new(string)) + case protoreflect.BytesKind: + return unmarshalValue(in, new([]byte)) + case protoreflect.EnumKind: + if hasPrefixAndSuffix('"', in, '"') { + vd := fd.Enum().Values().ByName(protoreflect.Name(trimQuote(in))) + if vd == nil { + return v, fmt.Errorf("unknown value %q for enum %s", in, fd.Enum().FullName()) + } + return protoreflect.ValueOfEnum(vd.Number()), nil + } + return unmarshalValue(in, new(protoreflect.EnumNumber)) + case protoreflect.MessageKind, protoreflect.GroupKind: + err := u.unmarshalMessage(v.Message(), in) + return v, err + default: + panic(fmt.Sprintf("invalid kind %v", fd.Kind())) + } +} + +func unmarshalValue(in []byte, v interface{}) (protoreflect.Value, error) { + err := json.Unmarshal(in, v) + return protoreflect.ValueOf(reflect.ValueOf(v).Elem().Interface()), err +} + +func unquoteString(in string) (out string, err error) { + err = json.Unmarshal([]byte(in), &out) + return out, err +} + +func hasPrefixAndSuffix(prefix byte, in []byte, suffix byte) bool { + if len(in) >= 2 && in[0] == prefix && in[len(in)-1] == suffix { + return true + } + return false +} + +// trimQuote is like unquoteString but simply strips surrounding quotes. +// This is incorrect, but is behavior done by the legacy implementation. +func trimQuote(in []byte) []byte { + if len(in) >= 2 && in[0] == '"' && in[len(in)-1] == '"' { + in = in[1 : len(in)-1] + } + return in +} diff --git a/vendor/github.com/golang/protobuf/jsonpb/encode.go b/vendor/github.com/golang/protobuf/jsonpb/encode.go new file mode 100644 index 000000000000..685c80a62bc9 --- /dev/null +++ b/vendor/github.com/golang/protobuf/jsonpb/encode.go @@ -0,0 +1,559 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package jsonpb + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "math" + "reflect" + "sort" + "strconv" + "strings" + "time" + + "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/encoding/protojson" + protoV2 "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +const wrapJSONMarshalV2 = false + +// Marshaler is a configurable object for marshaling protocol buffer messages +// to the specified JSON representation. +type Marshaler struct { + // OrigName specifies whether to use the original protobuf name for fields. + OrigName bool + + // EnumsAsInts specifies whether to render enum values as integers, + // as opposed to string values. + EnumsAsInts bool + + // EmitDefaults specifies whether to render fields with zero values. + EmitDefaults bool + + // Indent controls whether the output is compact or not. + // If empty, the output is compact JSON. Otherwise, every JSON object + // entry and JSON array value will be on its own line. + // Each line will be preceded by repeated copies of Indent, where the + // number of copies is the current indentation depth. + Indent string + + // AnyResolver is used to resolve the google.protobuf.Any well-known type. + // If unset, the global registry is used by default. + AnyResolver AnyResolver +} + +// JSONPBMarshaler is implemented by protobuf messages that customize the +// way they are marshaled to JSON. Messages that implement this should also +// implement JSONPBUnmarshaler so that the custom format can be parsed. +// +// The JSON marshaling must follow the proto to JSON specification: +// https://developers.google.com/protocol-buffers/docs/proto3#json +// +// Deprecated: Custom types should implement protobuf reflection instead. +type JSONPBMarshaler interface { + MarshalJSONPB(*Marshaler) ([]byte, error) +} + +// Marshal serializes a protobuf message as JSON into w. +func (jm *Marshaler) Marshal(w io.Writer, m proto.Message) error { + b, err := jm.marshal(m) + if len(b) > 0 { + if _, err := w.Write(b); err != nil { + return err + } + } + return err +} + +// MarshalToString serializes a protobuf message as JSON in string form. +func (jm *Marshaler) MarshalToString(m proto.Message) (string, error) { + b, err := jm.marshal(m) + if err != nil { + return "", err + } + return string(b), nil +} + +func (jm *Marshaler) marshal(m proto.Message) ([]byte, error) { + v := reflect.ValueOf(m) + if m == nil || (v.Kind() == reflect.Ptr && v.IsNil()) { + return nil, errors.New("Marshal called with nil") + } + + // Check for custom marshalers first since they may not properly + // implement protobuf reflection that the logic below relies on. + if jsm, ok := m.(JSONPBMarshaler); ok { + return jsm.MarshalJSONPB(jm) + } + + if wrapJSONMarshalV2 { + opts := protojson.MarshalOptions{ + UseProtoNames: jm.OrigName, + UseEnumNumbers: jm.EnumsAsInts, + EmitUnpopulated: jm.EmitDefaults, + Indent: jm.Indent, + } + if jm.AnyResolver != nil { + opts.Resolver = anyResolver{jm.AnyResolver} + } + return opts.Marshal(proto.MessageReflect(m).Interface()) + } else { + // Check for unpopulated required fields first. + m2 := proto.MessageReflect(m) + if err := protoV2.CheckInitialized(m2.Interface()); err != nil { + return nil, err + } + + w := jsonWriter{Marshaler: jm} + err := w.marshalMessage(m2, "", "") + return w.buf, err + } +} + +type jsonWriter struct { + *Marshaler + buf []byte +} + +func (w *jsonWriter) write(s string) { + w.buf = append(w.buf, s...) +} + +func (w *jsonWriter) marshalMessage(m protoreflect.Message, indent, typeURL string) error { + if jsm, ok := proto.MessageV1(m.Interface()).(JSONPBMarshaler); ok { + b, err := jsm.MarshalJSONPB(w.Marshaler) + if err != nil { + return err + } + if typeURL != "" { + // we are marshaling this object to an Any type + var js map[string]*json.RawMessage + if err = json.Unmarshal(b, &js); err != nil { + return fmt.Errorf("type %T produced invalid JSON: %v", m.Interface(), err) + } + turl, err := json.Marshal(typeURL) + if err != nil { + return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err) + } + js["@type"] = (*json.RawMessage)(&turl) + if b, err = json.Marshal(js); err != nil { + return err + } + } + w.write(string(b)) + return nil + } + + md := m.Descriptor() + fds := md.Fields() + + // Handle well-known types. + const secondInNanos = int64(time.Second / time.Nanosecond) + switch wellKnownType(md.FullName()) { + case "Any": + return w.marshalAny(m, indent) + case "BoolValue", "BytesValue", "StringValue", + "Int32Value", "UInt32Value", "FloatValue", + "Int64Value", "UInt64Value", "DoubleValue": + fd := fds.ByNumber(1) + return w.marshalValue(fd, m.Get(fd), indent) + case "Duration": + const maxSecondsInDuration = 315576000000 + // "Generated output always contains 0, 3, 6, or 9 fractional digits, + // depending on required precision." + s := m.Get(fds.ByNumber(1)).Int() + ns := m.Get(fds.ByNumber(2)).Int() + if s < -maxSecondsInDuration || s > maxSecondsInDuration { + return fmt.Errorf("seconds out of range %v", s) + } + if ns <= -secondInNanos || ns >= secondInNanos { + return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos) + } + if (s > 0 && ns < 0) || (s < 0 && ns > 0) { + return errors.New("signs of seconds and nanos do not match") + } + var sign string + if s < 0 || ns < 0 { + sign, s, ns = "-", -1*s, -1*ns + } + x := fmt.Sprintf("%s%d.%09d", sign, s, ns) + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + w.write(fmt.Sprintf(`"%vs"`, x)) + return nil + case "Timestamp": + // "RFC 3339, where generated output will always be Z-normalized + // and uses 0, 3, 6 or 9 fractional digits." + s := m.Get(fds.ByNumber(1)).Int() + ns := m.Get(fds.ByNumber(2)).Int() + if ns < 0 || ns >= secondInNanos { + return fmt.Errorf("ns out of range [0, %v)", secondInNanos) + } + t := time.Unix(s, ns).UTC() + // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits). + x := t.Format("2006-01-02T15:04:05.000000000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + w.write(fmt.Sprintf(`"%vZ"`, x)) + return nil + case "Value": + // JSON value; which is a null, number, string, bool, object, or array. + od := md.Oneofs().Get(0) + fd := m.WhichOneof(od) + if fd == nil { + return errors.New("nil Value") + } + return w.marshalValue(fd, m.Get(fd), indent) + case "Struct", "ListValue": + // JSON object or array. + fd := fds.ByNumber(1) + return w.marshalValue(fd, m.Get(fd), indent) + } + + w.write("{") + if w.Indent != "" { + w.write("\n") + } + + firstField := true + if typeURL != "" { + if err := w.marshalTypeURL(indent, typeURL); err != nil { + return err + } + firstField = false + } + + for i := 0; i < fds.Len(); { + fd := fds.Get(i) + if od := fd.ContainingOneof(); od != nil { + fd = m.WhichOneof(od) + i += od.Fields().Len() + if fd == nil { + continue + } + } else { + i++ + } + + v := m.Get(fd) + + if !m.Has(fd) { + if !w.EmitDefaults || fd.ContainingOneof() != nil { + continue + } + if fd.Cardinality() != protoreflect.Repeated && (fd.Message() != nil || fd.Syntax() == protoreflect.Proto2) { + v = protoreflect.Value{} // use "null" for singular messages or proto2 scalars + } + } + + if !firstField { + w.writeComma() + } + if err := w.marshalField(fd, v, indent); err != nil { + return err + } + firstField = false + } + + // Handle proto2 extensions. + if md.ExtensionRanges().Len() > 0 { + // Collect a sorted list of all extension descriptor and values. + type ext struct { + desc protoreflect.FieldDescriptor + val protoreflect.Value + } + var exts []ext + m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + if fd.IsExtension() { + exts = append(exts, ext{fd, v}) + } + return true + }) + sort.Slice(exts, func(i, j int) bool { + return exts[i].desc.Number() < exts[j].desc.Number() + }) + + for _, ext := range exts { + if !firstField { + w.writeComma() + } + if err := w.marshalField(ext.desc, ext.val, indent); err != nil { + return err + } + firstField = false + } + } + + if w.Indent != "" { + w.write("\n") + w.write(indent) + } + w.write("}") + return nil +} + +func (w *jsonWriter) writeComma() { + if w.Indent != "" { + w.write(",\n") + } else { + w.write(",") + } +} + +func (w *jsonWriter) marshalAny(m protoreflect.Message, indent string) error { + // "If the Any contains a value that has a special JSON mapping, + // it will be converted as follows: {"@type": xxx, "value": yyy}. + // Otherwise, the value will be converted into a JSON object, + // and the "@type" field will be inserted to indicate the actual data type." + md := m.Descriptor() + typeURL := m.Get(md.Fields().ByNumber(1)).String() + rawVal := m.Get(md.Fields().ByNumber(2)).Bytes() + + var m2 protoreflect.Message + if w.AnyResolver != nil { + mi, err := w.AnyResolver.Resolve(typeURL) + if err != nil { + return err + } + m2 = proto.MessageReflect(mi) + } else { + mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL) + if err != nil { + return err + } + m2 = mt.New() + } + + if err := protoV2.Unmarshal(rawVal, m2.Interface()); err != nil { + return err + } + + if wellKnownType(m2.Descriptor().FullName()) == "" { + return w.marshalMessage(m2, indent, typeURL) + } + + w.write("{") + if w.Indent != "" { + w.write("\n") + } + if err := w.marshalTypeURL(indent, typeURL); err != nil { + return err + } + w.writeComma() + if w.Indent != "" { + w.write(indent) + w.write(w.Indent) + w.write(`"value": `) + } else { + w.write(`"value":`) + } + if err := w.marshalMessage(m2, indent+w.Indent, ""); err != nil { + return err + } + if w.Indent != "" { + w.write("\n") + w.write(indent) + } + w.write("}") + return nil +} + +func (w *jsonWriter) marshalTypeURL(indent, typeURL string) error { + if w.Indent != "" { + w.write(indent) + w.write(w.Indent) + } + w.write(`"@type":`) + if w.Indent != "" { + w.write(" ") + } + b, err := json.Marshal(typeURL) + if err != nil { + return err + } + w.write(string(b)) + return nil +} + +// marshalField writes field description and value to the Writer. +func (w *jsonWriter) marshalField(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error { + if w.Indent != "" { + w.write(indent) + w.write(w.Indent) + } + w.write(`"`) + switch { + case fd.IsExtension(): + // For message set, use the fname of the message as the extension name. + name := string(fd.FullName()) + if isMessageSet(fd.ContainingMessage()) { + name = strings.TrimSuffix(name, ".message_set_extension") + } + + w.write("[" + name + "]") + case w.OrigName: + name := string(fd.Name()) + if fd.Kind() == protoreflect.GroupKind { + name = string(fd.Message().Name()) + } + w.write(name) + default: + w.write(string(fd.JSONName())) + } + w.write(`":`) + if w.Indent != "" { + w.write(" ") + } + return w.marshalValue(fd, v, indent) +} + +func (w *jsonWriter) marshalValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error { + switch { + case fd.IsList(): + w.write("[") + comma := "" + lv := v.List() + for i := 0; i < lv.Len(); i++ { + w.write(comma) + if w.Indent != "" { + w.write("\n") + w.write(indent) + w.write(w.Indent) + w.write(w.Indent) + } + if err := w.marshalSingularValue(fd, lv.Get(i), indent+w.Indent); err != nil { + return err + } + comma = "," + } + if w.Indent != "" { + w.write("\n") + w.write(indent) + w.write(w.Indent) + } + w.write("]") + return nil + case fd.IsMap(): + kfd := fd.MapKey() + vfd := fd.MapValue() + mv := v.Map() + + // Collect a sorted list of all map keys and values. + type entry struct{ key, val protoreflect.Value } + var entries []entry + mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { + entries = append(entries, entry{k.Value(), v}) + return true + }) + sort.Slice(entries, func(i, j int) bool { + switch kfd.Kind() { + case protoreflect.BoolKind: + return !entries[i].key.Bool() && entries[j].key.Bool() + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + return entries[i].key.Int() < entries[j].key.Int() + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + return entries[i].key.Uint() < entries[j].key.Uint() + case protoreflect.StringKind: + return entries[i].key.String() < entries[j].key.String() + default: + panic("invalid kind") + } + }) + + w.write(`{`) + comma := "" + for _, entry := range entries { + w.write(comma) + if w.Indent != "" { + w.write("\n") + w.write(indent) + w.write(w.Indent) + w.write(w.Indent) + } + + s := fmt.Sprint(entry.key.Interface()) + b, err := json.Marshal(s) + if err != nil { + return err + } + w.write(string(b)) + + w.write(`:`) + if w.Indent != "" { + w.write(` `) + } + + if err := w.marshalSingularValue(vfd, entry.val, indent+w.Indent); err != nil { + return err + } + comma = "," + } + if w.Indent != "" { + w.write("\n") + w.write(indent) + w.write(w.Indent) + } + w.write(`}`) + return nil + default: + return w.marshalSingularValue(fd, v, indent) + } +} + +func (w *jsonWriter) marshalSingularValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error { + switch { + case !v.IsValid(): + w.write("null") + return nil + case fd.Message() != nil: + return w.marshalMessage(v.Message(), indent+w.Indent, "") + case fd.Enum() != nil: + if fd.Enum().FullName() == "google.protobuf.NullValue" { + w.write("null") + return nil + } + + vd := fd.Enum().Values().ByNumber(v.Enum()) + if vd == nil || w.EnumsAsInts { + w.write(strconv.Itoa(int(v.Enum()))) + } else { + w.write(`"` + string(vd.Name()) + `"`) + } + return nil + default: + switch v.Interface().(type) { + case float32, float64: + switch { + case math.IsInf(v.Float(), +1): + w.write(`"Infinity"`) + return nil + case math.IsInf(v.Float(), -1): + w.write(`"-Infinity"`) + return nil + case math.IsNaN(v.Float()): + w.write(`"NaN"`) + return nil + } + case int64, uint64: + w.write(fmt.Sprintf(`"%d"`, v.Interface())) + return nil + } + + b, err := json.Marshal(v.Interface()) + if err != nil { + return err + } + w.write(string(b)) + return nil + } +} diff --git a/vendor/github.com/golang/protobuf/jsonpb/json.go b/vendor/github.com/golang/protobuf/jsonpb/json.go new file mode 100644 index 000000000000..480e2448de66 --- /dev/null +++ b/vendor/github.com/golang/protobuf/jsonpb/json.go @@ -0,0 +1,69 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package jsonpb provides functionality to marshal and unmarshal between a +// protocol buffer message and JSON. It follows the specification at +// https://developers.google.com/protocol-buffers/docs/proto3#json. +// +// Do not rely on the default behavior of the standard encoding/json package +// when called on generated message types as it does not operate correctly. +// +// Deprecated: Use the "google.golang.org/protobuf/encoding/protojson" +// package instead. +package jsonpb + +import ( + "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/runtime/protoimpl" +) + +// AnyResolver takes a type URL, present in an Any message, +// and resolves it into an instance of the associated message. +type AnyResolver interface { + Resolve(typeURL string) (proto.Message, error) +} + +type anyResolver struct{ AnyResolver } + +func (r anyResolver) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) { + return r.FindMessageByURL(string(message)) +} + +func (r anyResolver) FindMessageByURL(url string) (protoreflect.MessageType, error) { + m, err := r.Resolve(url) + if err != nil { + return nil, err + } + return protoimpl.X.MessageTypeOf(m), nil +} + +func (r anyResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { + return protoregistry.GlobalTypes.FindExtensionByName(field) +} + +func (r anyResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { + return protoregistry.GlobalTypes.FindExtensionByNumber(message, field) +} + +func wellKnownType(s protoreflect.FullName) string { + if s.Parent() == "google.protobuf" { + switch s.Name() { + case "Empty", "Any", + "BoolValue", "BytesValue", "StringValue", + "Int32Value", "UInt32Value", "FloatValue", + "Int64Value", "UInt64Value", "DoubleValue", + "Duration", "Timestamp", + "NullValue", "Struct", "Value", "ListValue": + return string(s.Name()) + } + } + return "" +} + +func isMessageSet(md protoreflect.MessageDescriptor) bool { + ms, ok := md.(interface{ IsMessageSet() bool }) + return ok && ms.IsMessageSet() +} diff --git a/vendor/github.com/hashicorp/go-azure-helpers/authentication/environment.go b/vendor/github.com/hashicorp/go-azure-helpers/authentication/environment.go index 05910ffbdf82..69ec44474411 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/authentication/environment.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/authentication/environment.go @@ -114,10 +114,16 @@ func AzureEnvironmentByNameFromEndpoint(ctx context.Context, endpoint string, en // while the array contains values for _, env := range environments { if strings.EqualFold(env.Name, environmentName) { + // if resourceManager endpoint is empty, assume it's the provided endpoint + if env.ResourceManager == "" { + env.ResourceManager = fmt.Sprintf("https://%s/", endpoint) + } + aEnv, err := buildAzureEnvironment(env) if err != nil { return nil, err } + return aEnv, nil } } diff --git a/vendor/github.com/hashicorp/go-azure-helpers/lang/response/response.go b/vendor/github.com/hashicorp/go-azure-helpers/lang/response/response.go index 9f0e1b506f55..74495589d8bc 100644 --- a/vendor/github.com/hashicorp/go-azure-helpers/lang/response/response.go +++ b/vendor/github.com/hashicorp/go-azure-helpers/lang/response/response.go @@ -6,20 +6,22 @@ import ( // WasBadRequest returns true if the HttpResponse is non-nil and has a status code of BadRequest func WasBadRequest(resp *http.Response) bool { - return responseWasStatusCode(resp, http.StatusBadRequest) + return WasStatusCode(resp, http.StatusBadRequest) } // WasConflict returns true if the HttpResponse is non-nil and has a status code of Conflict func WasConflict(resp *http.Response) bool { - return responseWasStatusCode(resp, http.StatusConflict) + return WasStatusCode(resp, http.StatusConflict) } // WasNotFound returns true if the HttpResponse is non-nil and has a status code of NotFound func WasNotFound(resp *http.Response) bool { - return responseWasStatusCode(resp, http.StatusNotFound) + return WasStatusCode(resp, http.StatusNotFound) } -func responseWasStatusCode(resp *http.Response, statusCode int) bool { +// WasStatusCode returns true if the HttpResponse is non-nil and matches the Status Code +// It's recommended to use WasBadRequest/WasConflict/WasNotFound where possible instead +func WasStatusCode(resp *http.Response, statusCode int) bool { if r := resp; r != nil { if r.StatusCode == statusCode { return true diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/README.md new file mode 100644 index 000000000000..46d87b64f81f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/README.md @@ -0,0 +1,154 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores` Documentation + +The `configurationstores` SDK allows for interaction with the Azure Resource Manager Service `appconfiguration` (API Version `2022-05-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores" +``` + + +### Client Initialization + +```go +client := configurationstores.NewConfigurationStoresClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `ConfigurationStoresClient.Create` + +```go +ctx := context.TODO() +id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") + +payload := configurationstores.ConfigurationStore{ + // ... +} + + +if err := client.CreateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `ConfigurationStoresClient.Delete` + +```go +ctx := context.TODO() +id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") + +if err := client.DeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `ConfigurationStoresClient.Get` + +```go +ctx := context.TODO() +id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ConfigurationStoresClient.List` + +```go +ctx := context.TODO() +id := configurationstores.NewSubscriptionID() + +// alternatively `client.List(ctx, id)` can be used to do batched pagination +items, err := client.ListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `ConfigurationStoresClient.ListByResourceGroup` + +```go +ctx := context.TODO() +id := configurationstores.NewResourceGroupID() + +// alternatively `client.ListByResourceGroup(ctx, id)` can be used to do batched pagination +items, err := client.ListByResourceGroupComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `ConfigurationStoresClient.ListKeys` + +```go +ctx := context.TODO() +id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") + +// alternatively `client.ListKeys(ctx, id)` can be used to do batched pagination +items, err := client.ListKeysComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `ConfigurationStoresClient.RegenerateKey` + +```go +ctx := context.TODO() +id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") + +payload := configurationstores.RegenerateKeyParameters{ + // ... +} + + +read, err := client.RegenerateKey(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ConfigurationStoresClient.Update` + +```go +ctx := context.TODO() +id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") + +payload := configurationstores.ConfigurationStoreUpdateParameters{ + // ... +} + + +if err := client.UpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/client.go new file mode 100644 index 000000000000..a8a958bcfcfe --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/client.go @@ -0,0 +1,18 @@ +package configurationstores + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConfigurationStoresClient struct { + Client autorest.Client + baseUri string +} + +func NewConfigurationStoresClientWithBaseURI(endpoint string) ConfigurationStoresClient { + return ConfigurationStoresClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/constants.go new file mode 100644 index 000000000000..75cdd3baed8e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/constants.go @@ -0,0 +1,164 @@ +package configurationstores + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ActionsRequired string + +const ( + ActionsRequiredNone ActionsRequired = "None" + ActionsRequiredRecreate ActionsRequired = "Recreate" +) + +func PossibleValuesForActionsRequired() []string { + return []string{ + string(ActionsRequiredNone), + string(ActionsRequiredRecreate), + } +} + +func parseActionsRequired(input string) (*ActionsRequired, error) { + vals := map[string]ActionsRequired{ + "none": ActionsRequiredNone, + "recreate": ActionsRequiredRecreate, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ActionsRequired(input) + return &out, nil +} + +type ConnectionStatus string + +const ( + ConnectionStatusApproved ConnectionStatus = "Approved" + ConnectionStatusDisconnected ConnectionStatus = "Disconnected" + ConnectionStatusPending ConnectionStatus = "Pending" + ConnectionStatusRejected ConnectionStatus = "Rejected" +) + +func PossibleValuesForConnectionStatus() []string { + return []string{ + string(ConnectionStatusApproved), + string(ConnectionStatusDisconnected), + string(ConnectionStatusPending), + string(ConnectionStatusRejected), + } +} + +func parseConnectionStatus(input string) (*ConnectionStatus, error) { + vals := map[string]ConnectionStatus{ + "approved": ConnectionStatusApproved, + "disconnected": ConnectionStatusDisconnected, + "pending": ConnectionStatusPending, + "rejected": ConnectionStatusRejected, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ConnectionStatus(input) + return &out, nil +} + +type CreateMode string + +const ( + CreateModeDefault CreateMode = "Default" + CreateModeRecover CreateMode = "Recover" +) + +func PossibleValuesForCreateMode() []string { + return []string{ + string(CreateModeDefault), + string(CreateModeRecover), + } +} + +func parseCreateMode(input string) (*CreateMode, error) { + vals := map[string]CreateMode{ + "default": CreateModeDefault, + "recover": CreateModeRecover, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := CreateMode(input) + return &out, nil +} + +type ProvisioningState string + +const ( + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +func PossibleValuesForProvisioningState() []string { + return []string{ + string(ProvisioningStateCanceled), + string(ProvisioningStateCreating), + string(ProvisioningStateDeleting), + string(ProvisioningStateFailed), + string(ProvisioningStateSucceeded), + string(ProvisioningStateUpdating), + } +} + +func parseProvisioningState(input string) (*ProvisioningState, error) { + vals := map[string]ProvisioningState{ + "canceled": ProvisioningStateCanceled, + "creating": ProvisioningStateCreating, + "deleting": ProvisioningStateDeleting, + "failed": ProvisioningStateFailed, + "succeeded": ProvisioningStateSucceeded, + "updating": ProvisioningStateUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ProvisioningState(input) + return &out, nil +} + +type PublicNetworkAccess string + +const ( + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +func PossibleValuesForPublicNetworkAccess() []string { + return []string{ + string(PublicNetworkAccessDisabled), + string(PublicNetworkAccessEnabled), + } +} + +func parsePublicNetworkAccess(input string) (*PublicNetworkAccess, error) { + vals := map[string]PublicNetworkAccess{ + "disabled": PublicNetworkAccessDisabled, + "enabled": PublicNetworkAccessEnabled, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := PublicNetworkAccess(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/id_configurationstore.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/id_configurationstore.go new file mode 100644 index 000000000000..5e9fc5e6977b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/id_configurationstore.go @@ -0,0 +1,124 @@ +package configurationstores + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ConfigurationStoreId{} + +// ConfigurationStoreId is a struct representing the Resource ID for a Configuration Store +type ConfigurationStoreId struct { + SubscriptionId string + ResourceGroupName string + ConfigStoreName string +} + +// NewConfigurationStoreID returns a new ConfigurationStoreId struct +func NewConfigurationStoreID(subscriptionId string, resourceGroupName string, configStoreName string) ConfigurationStoreId { + return ConfigurationStoreId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ConfigStoreName: configStoreName, + } +} + +// ParseConfigurationStoreID parses 'input' into a ConfigurationStoreId +func ParseConfigurationStoreID(input string) (*ConfigurationStoreId, error) { + parser := resourceids.NewParserFromResourceIdType(ConfigurationStoreId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ConfigurationStoreId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ConfigStoreName, ok = parsed.Parsed["configStoreName"]; !ok { + return nil, fmt.Errorf("the segment 'configStoreName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseConfigurationStoreIDInsensitively parses 'input' case-insensitively into a ConfigurationStoreId +// note: this method should only be used for API response data and not user input +func ParseConfigurationStoreIDInsensitively(input string) (*ConfigurationStoreId, error) { + parser := resourceids.NewParserFromResourceIdType(ConfigurationStoreId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ConfigurationStoreId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ConfigStoreName, ok = parsed.Parsed["configStoreName"]; !ok { + return nil, fmt.Errorf("the segment 'configStoreName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateConfigurationStoreID checks that 'input' can be parsed as a Configuration Store ID +func ValidateConfigurationStoreID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseConfigurationStoreID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Configuration Store ID +func (id ConfigurationStoreId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.AppConfiguration/configurationStores/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ConfigStoreName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Configuration Store ID +func (id ConfigurationStoreId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftAppConfiguration", "Microsoft.AppConfiguration", "Microsoft.AppConfiguration"), + resourceids.StaticSegment("staticConfigurationStores", "configurationStores", "configurationStores"), + resourceids.UserSpecifiedSegment("configStoreName", "configStoreValue"), + } +} + +// String returns a human-readable description of this Configuration Store ID +func (id ConfigurationStoreId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Config Store Name: %q", id.ConfigStoreName), + } + return fmt.Sprintf("Configuration Store (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_create_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_create_autorest.go new file mode 100644 index 000000000000..584ebb8933eb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_create_autorest.go @@ -0,0 +1,79 @@ +package configurationstores + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Create ... +func (c ConfigurationStoresClient) Create(ctx context.Context, id ConfigurationStoreId, input ConfigurationStore) (result CreateOperationResponse, err error) { + req, err := c.preparerForCreate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Create", nil, "Failure preparing request") + return + } + + result, err = c.senderForCreate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Create", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CreateThenPoll performs Create then polls until it's completed +func (c ConfigurationStoresClient) CreateThenPoll(ctx context.Context, id ConfigurationStoreId, input ConfigurationStore) error { + result, err := c.Create(ctx, id, input) + if err != nil { + return fmt.Errorf("performing Create: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Create: %+v", err) + } + + return nil +} + +// preparerForCreate prepares the Create request. +func (c ConfigurationStoresClient) preparerForCreate(ctx context.Context, id ConfigurationStoreId, input ConfigurationStore) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCreate sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (c ConfigurationStoresClient) senderForCreate(ctx context.Context, req *http.Request) (future CreateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_delete_autorest.go new file mode 100644 index 000000000000..aaff0f3cd6d6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_delete_autorest.go @@ -0,0 +1,78 @@ +package configurationstores + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Delete ... +func (c ConfigurationStoresClient) Delete(ctx context.Context, id ConfigurationStoreId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = c.senderForDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// DeleteThenPoll performs Delete then polls until it's completed +func (c ConfigurationStoresClient) DeleteThenPoll(ctx context.Context, id ConfigurationStoreId) error { + result, err := c.Delete(ctx, id) + if err != nil { + return fmt.Errorf("performing Delete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Delete: %+v", err) + } + + return nil +} + +// preparerForDelete prepares the Delete request. +func (c ConfigurationStoresClient) preparerForDelete(ctx context.Context, id ConfigurationStoreId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForDelete sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (c ConfigurationStoresClient) senderForDelete(ctx context.Context, req *http.Request) (future DeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_get_autorest.go new file mode 100644 index 000000000000..4428f3531bff --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_get_autorest.go @@ -0,0 +1,67 @@ +package configurationstores + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *ConfigurationStore +} + +// Get ... +func (c ConfigurationStoresClient) Get(ctx context.Context, id ConfigurationStoreId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c ConfigurationStoresClient) preparerForGet(ctx context.Context, id ConfigurationStoreId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c ConfigurationStoresClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_list_autorest.go new file mode 100644 index 000000000000..1cf6264b5b35 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_list_autorest.go @@ -0,0 +1,187 @@ +package configurationstores + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *[]ConfigurationStore + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) +} + +type ListCompleteResult struct { + Items []ConfigurationStore +} + +func (r ListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// List ... +func (c ConfigurationStoresClient) List(ctx context.Context, id commonids.SubscriptionId) (resp ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListComplete retrieves all of the results into a single object +func (c ConfigurationStoresClient) ListComplete(ctx context.Context, id commonids.SubscriptionId) (ListCompleteResult, error) { + return c.ListCompleteMatchingPredicate(ctx, id, ConfigurationStoreOperationPredicate{}) +} + +// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c ConfigurationStoresClient) ListCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate ConfigurationStoreOperationPredicate) (resp ListCompleteResult, err error) { + items := make([]ConfigurationStore, 0) + + page, err := c.List(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForList prepares the List request. +func (c ConfigurationStoresClient) preparerForList(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.AppConfiguration/configurationStores", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListWithNextLink prepares the List request with the given nextLink token. +func (c ConfigurationStoresClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c ConfigurationStoresClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + type page struct { + Values []ConfigurationStore `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { + req, err := c.preparerForListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_listbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_listbyresourcegroup_autorest.go new file mode 100644 index 000000000000..06c80ed42a17 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_listbyresourcegroup_autorest.go @@ -0,0 +1,187 @@ +package configurationstores + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]ConfigurationStore + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByResourceGroupOperationResponse, error) +} + +type ListByResourceGroupCompleteResult struct { + Items []ConfigurationStore +} + +func (r ListByResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ListByResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListByResourceGroup ... +func (c ConfigurationStoresClient) ListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByResourceGroupComplete retrieves all of the results into a single object +func (c ConfigurationStoresClient) ListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ListByResourceGroupCompleteResult, error) { + return c.ListByResourceGroupCompleteMatchingPredicate(ctx, id, ConfigurationStoreOperationPredicate{}) +} + +// ListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c ConfigurationStoresClient) ListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate ConfigurationStoreOperationPredicate) (resp ListByResourceGroupCompleteResult, err error) { + items := make([]ConfigurationStore, 0) + + page, err := c.ListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByResourceGroup prepares the ListByResourceGroup request. +func (c ConfigurationStoresClient) preparerForListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.AppConfiguration/configurationStores", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByResourceGroupWithNextLink prepares the ListByResourceGroup request with the given nextLink token. +func (c ConfigurationStoresClient) preparerForListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByResourceGroup handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (c ConfigurationStoresClient) responderForListByResourceGroup(resp *http.Response) (result ListByResourceGroupOperationResponse, err error) { + type page struct { + Values []ConfigurationStore `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_listkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_listkeys_autorest.go new file mode 100644 index 000000000000..0220a22f719b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_listkeys_autorest.go @@ -0,0 +1,186 @@ +package configurationstores + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListKeysOperationResponse struct { + HttpResponse *http.Response + Model *[]ApiKey + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListKeysOperationResponse, error) +} + +type ListKeysCompleteResult struct { + Items []ApiKey +} + +func (r ListKeysOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListKeysOperationResponse) LoadMore(ctx context.Context) (resp ListKeysOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListKeys ... +func (c ConfigurationStoresClient) ListKeys(ctx context.Context, id ConfigurationStoreId) (resp ListKeysOperationResponse, err error) { + req, err := c.preparerForListKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListKeys(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListKeysComplete retrieves all of the results into a single object +func (c ConfigurationStoresClient) ListKeysComplete(ctx context.Context, id ConfigurationStoreId) (ListKeysCompleteResult, error) { + return c.ListKeysCompleteMatchingPredicate(ctx, id, ApiKeyOperationPredicate{}) +} + +// ListKeysCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c ConfigurationStoresClient) ListKeysCompleteMatchingPredicate(ctx context.Context, id ConfigurationStoreId, predicate ApiKeyOperationPredicate) (resp ListKeysCompleteResult, err error) { + items := make([]ApiKey, 0) + + page, err := c.ListKeys(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListKeysCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListKeys prepares the ListKeys request. +func (c ConfigurationStoresClient) preparerForListKeys(ctx context.Context, id ConfigurationStoreId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListKeysWithNextLink prepares the ListKeys request with the given nextLink token. +func (c ConfigurationStoresClient) preparerForListKeysWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListKeys handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (c ConfigurationStoresClient) responderForListKeys(resp *http.Response) (result ListKeysOperationResponse, err error) { + type page struct { + Values []ApiKey `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListKeysOperationResponse, err error) { + req, err := c.preparerForListKeysWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_regeneratekey_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_regeneratekey_autorest.go new file mode 100644 index 000000000000..2ec1bcb15921 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_regeneratekey_autorest.go @@ -0,0 +1,69 @@ +package configurationstores + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateKeyOperationResponse struct { + HttpResponse *http.Response + Model *ApiKey +} + +// RegenerateKey ... +func (c ConfigurationStoresClient) RegenerateKey(ctx context.Context, id ConfigurationStoreId, input RegenerateKeyParameters) (result RegenerateKeyOperationResponse, err error) { + req, err := c.preparerForRegenerateKey(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "RegenerateKey", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "RegenerateKey", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRegenerateKey(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "RegenerateKey", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRegenerateKey prepares the RegenerateKey request. +func (c ConfigurationStoresClient) preparerForRegenerateKey(ctx context.Context, id ConfigurationStoreId, input RegenerateKeyParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/regenerateKey", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRegenerateKey handles the response to the RegenerateKey request. The method always +// closes the http.Response Body. +func (c ConfigurationStoresClient) responderForRegenerateKey(resp *http.Response) (result RegenerateKeyOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_update_autorest.go new file mode 100644 index 000000000000..970cc76c2972 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/method_update_autorest.go @@ -0,0 +1,79 @@ +package configurationstores + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Update ... +func (c ConfigurationStoresClient) Update(ctx context.Context, id ConfigurationStoreId, input ConfigurationStoreUpdateParameters) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Update", nil, "Failure preparing request") + return + } + + result, err = c.senderForUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// UpdateThenPoll performs Update then polls until it's completed +func (c ConfigurationStoresClient) UpdateThenPoll(ctx context.Context, id ConfigurationStoreId, input ConfigurationStoreUpdateParameters) error { + result, err := c.Update(ctx, id, input) + if err != nil { + return fmt.Errorf("performing Update: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Update: %+v", err) + } + + return nil +} + +// preparerForUpdate prepares the Update request. +func (c ConfigurationStoresClient) preparerForUpdate(ctx context.Context, id ConfigurationStoreId, input ConfigurationStoreUpdateParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForUpdate sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (c ConfigurationStoresClient) senderForUpdate(ctx context.Context, req *http.Request) (future UpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_apikey.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_apikey.go new file mode 100644 index 000000000000..9fa93145170e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_apikey.go @@ -0,0 +1,31 @@ +package configurationstores + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ApiKey struct { + ConnectionString *string `json:"connectionString,omitempty"` + Id *string `json:"id,omitempty"` + LastModified *string `json:"lastModified,omitempty"` + Name *string `json:"name,omitempty"` + ReadOnly *bool `json:"readOnly,omitempty"` + Value *string `json:"value,omitempty"` +} + +func (o *ApiKey) GetLastModifiedAsTime() (*time.Time, error) { + if o.LastModified == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastModified, "2006-01-02T15:04:05Z07:00") +} + +func (o *ApiKey) SetLastModifiedAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastModified = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstore.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstore.go new file mode 100644 index 000000000000..2eb894bdf5c8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstore.go @@ -0,0 +1,21 @@ +package configurationstores + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConfigurationStore struct { + Id *string `json:"id,omitempty"` + Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties *ConfigurationStoreProperties `json:"properties,omitempty"` + Sku Sku `json:"sku"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstoreproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstoreproperties.go new file mode 100644 index 000000000000..7dac08f3e245 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstoreproperties.go @@ -0,0 +1,35 @@ +package configurationstores + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConfigurationStoreProperties struct { + CreateMode *CreateMode `json:"createMode,omitempty"` + CreationDate *string `json:"creationDate,omitempty"` + DisableLocalAuth *bool `json:"disableLocalAuth,omitempty"` + EnablePurgeProtection *bool `json:"enablePurgeProtection,omitempty"` + Encryption *EncryptionProperties `json:"encryption,omitempty"` + Endpoint *string `json:"endpoint,omitempty"` + PrivateEndpointConnections *[]PrivateEndpointConnectionReference `json:"privateEndpointConnections,omitempty"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` + PublicNetworkAccess *PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + SoftDeleteRetentionInDays *int64 `json:"softDeleteRetentionInDays,omitempty"` +} + +func (o *ConfigurationStoreProperties) GetCreationDateAsTime() (*time.Time, error) { + if o.CreationDate == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreationDate, "2006-01-02T15:04:05Z07:00") +} + +func (o *ConfigurationStoreProperties) SetCreationDateAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreationDate = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstorepropertiesupdateparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstorepropertiesupdateparameters.go new file mode 100644 index 000000000000..dd82fc76a73d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstorepropertiesupdateparameters.go @@ -0,0 +1,11 @@ +package configurationstores + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConfigurationStorePropertiesUpdateParameters struct { + DisableLocalAuth *bool `json:"disableLocalAuth,omitempty"` + EnablePurgeProtection *bool `json:"enablePurgeProtection,omitempty"` + Encryption *EncryptionProperties `json:"encryption,omitempty"` + PublicNetworkAccess *PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstoreupdateparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstoreupdateparameters.go new file mode 100644 index 000000000000..f616d2a98ec3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_configurationstoreupdateparameters.go @@ -0,0 +1,15 @@ +package configurationstores + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConfigurationStoreUpdateParameters struct { + Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` + Properties *ConfigurationStorePropertiesUpdateParameters `json:"properties,omitempty"` + Sku *Sku `json:"sku,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_encryptionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_encryptionproperties.go new file mode 100644 index 000000000000..be0340c7047a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_encryptionproperties.go @@ -0,0 +1,8 @@ +package configurationstores + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EncryptionProperties struct { + KeyVaultProperties *KeyVaultProperties `json:"keyVaultProperties,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_keyvaultproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_keyvaultproperties.go new file mode 100644 index 000000000000..1e6e63eb2f8c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_keyvaultproperties.go @@ -0,0 +1,9 @@ +package configurationstores + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type KeyVaultProperties struct { + IdentityClientId *string `json:"identityClientId,omitempty"` + KeyIdentifier *string `json:"keyIdentifier,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpoint.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpoint.go new file mode 100644 index 000000000000..e52ec48dad00 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpoint.go @@ -0,0 +1,8 @@ +package configurationstores + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpoint struct { + Id *string `json:"id,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpointconnectionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpointconnectionproperties.go new file mode 100644 index 000000000000..7bd6508894c9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpointconnectionproperties.go @@ -0,0 +1,10 @@ +package configurationstores + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionProperties struct { + PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` + PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpointconnectionreference.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpointconnectionreference.go new file mode 100644 index 000000000000..3a67ff547973 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privateendpointconnectionreference.go @@ -0,0 +1,11 @@ +package configurationstores + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionReference struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *PrivateEndpointConnectionProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privatelinkserviceconnectionstate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privatelinkserviceconnectionstate.go new file mode 100644 index 000000000000..f6c8547cb4fb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_privatelinkserviceconnectionstate.go @@ -0,0 +1,10 @@ +package configurationstores + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateLinkServiceConnectionState struct { + ActionsRequired *ActionsRequired `json:"actionsRequired,omitempty"` + Description *string `json:"description,omitempty"` + Status *ConnectionStatus `json:"status,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_regeneratekeyparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_regeneratekeyparameters.go new file mode 100644 index 000000000000..f84013d2630f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_regeneratekeyparameters.go @@ -0,0 +1,8 @@ +package configurationstores + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateKeyParameters struct { + Id *string `json:"id,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_sku.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_sku.go new file mode 100644 index 000000000000..6472ed882f43 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/model_sku.go @@ -0,0 +1,8 @@ +package configurationstores + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Sku struct { + Name string `json:"name"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/predicates.go new file mode 100644 index 000000000000..d4541357a232 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/predicates.go @@ -0,0 +1,67 @@ +package configurationstores + +type ApiKeyOperationPredicate struct { + ConnectionString *string + Id *string + LastModified *string + Name *string + ReadOnly *bool + Value *string +} + +func (p ApiKeyOperationPredicate) Matches(input ApiKey) bool { + + if p.ConnectionString != nil && (input.ConnectionString == nil && *p.ConnectionString != *input.ConnectionString) { + return false + } + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.LastModified != nil && (input.LastModified == nil && *p.LastModified != *input.LastModified) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.ReadOnly != nil && (input.ReadOnly == nil && *p.ReadOnly != *input.ReadOnly) { + return false + } + + if p.Value != nil && (input.Value == nil && *p.Value != *input.Value) { + return false + } + + return true +} + +type ConfigurationStoreOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p ConfigurationStoreOperationPredicate) Matches(input ConfigurationStore) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/version.go new file mode 100644 index 000000000000..2b9a9f58cee9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores/version.go @@ -0,0 +1,12 @@ +package configurationstores + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2022-05-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/configurationstores/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/README.md new file mode 100644 index 000000000000..ae6dba0fb510 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/README.md @@ -0,0 +1,110 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights` Documentation + +The `applicationinsights` SDK allows for interaction with the Azure Resource Manager Service `applicationinsights` (API Version `2020-11-20`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights" +``` + + +### Client Initialization + +```go +client := applicationinsights.NewApplicationInsightsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `ApplicationInsightsClient.WorkbookTemplatesCreateOrUpdate` + +```go +ctx := context.TODO() +id := applicationinsights.NewWorkbookTemplateID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +payload := applicationinsights.WorkbookTemplate{ + // ... +} + + +read, err := client.WorkbookTemplatesCreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ApplicationInsightsClient.WorkbookTemplatesDelete` + +```go +ctx := context.TODO() +id := applicationinsights.NewWorkbookTemplateID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +read, err := client.WorkbookTemplatesDelete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ApplicationInsightsClient.WorkbookTemplatesGet` + +```go +ctx := context.TODO() +id := applicationinsights.NewWorkbookTemplateID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +read, err := client.WorkbookTemplatesGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ApplicationInsightsClient.WorkbookTemplatesListByResourceGroup` + +```go +ctx := context.TODO() +id := applicationinsights.NewResourceGroupID() + +read, err := client.WorkbookTemplatesListByResourceGroup(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ApplicationInsightsClient.WorkbookTemplatesUpdate` + +```go +ctx := context.TODO() +id := applicationinsights.NewWorkbookTemplateID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +payload := applicationinsights.WorkbookTemplateUpdateParameters{ + // ... +} + + +read, err := client.WorkbookTemplatesUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/client.go new file mode 100644 index 000000000000..f35cbf2494aa --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/client.go @@ -0,0 +1,18 @@ +package applicationinsights + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ApplicationInsightsClient struct { + Client autorest.Client + baseUri string +} + +func NewApplicationInsightsClientWithBaseURI(endpoint string) ApplicationInsightsClient { + return ApplicationInsightsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/id_workbooktemplate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/id_workbooktemplate.go new file mode 100644 index 000000000000..21ad2013cf86 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/id_workbooktemplate.go @@ -0,0 +1,124 @@ +package applicationinsights + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = WorkbookTemplateId{} + +// WorkbookTemplateId is a struct representing the Resource ID for a Workbook Template +type WorkbookTemplateId struct { + SubscriptionId string + ResourceGroupName string + ResourceName string +} + +// NewWorkbookTemplateID returns a new WorkbookTemplateId struct +func NewWorkbookTemplateID(subscriptionId string, resourceGroupName string, resourceName string) WorkbookTemplateId { + return WorkbookTemplateId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ResourceName: resourceName, + } +} + +// ParseWorkbookTemplateID parses 'input' into a WorkbookTemplateId +func ParseWorkbookTemplateID(input string) (*WorkbookTemplateId, error) { + parser := resourceids.NewParserFromResourceIdType(WorkbookTemplateId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := WorkbookTemplateId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseWorkbookTemplateIDInsensitively parses 'input' case-insensitively into a WorkbookTemplateId +// note: this method should only be used for API response data and not user input +func ParseWorkbookTemplateIDInsensitively(input string) (*WorkbookTemplateId, error) { + parser := resourceids.NewParserFromResourceIdType(WorkbookTemplateId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := WorkbookTemplateId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateWorkbookTemplateID checks that 'input' can be parsed as a Workbook Template ID +func ValidateWorkbookTemplateID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseWorkbookTemplateID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Workbook Template ID +func (id WorkbookTemplateId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Insights/workbookTemplates/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ResourceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Workbook Template ID +func (id WorkbookTemplateId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftInsights", "Microsoft.Insights", "Microsoft.Insights"), + resourceids.StaticSegment("staticWorkbookTemplates", "workbookTemplates", "workbookTemplates"), + resourceids.UserSpecifiedSegment("resourceName", "resourceValue"), + } +} + +// String returns a human-readable description of this Workbook Template ID +func (id WorkbookTemplateId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Resource Name: %q", id.ResourceName), + } + return fmt.Sprintf("Workbook Template (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatescreateorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatescreateorupdate_autorest.go new file mode 100644 index 000000000000..43c3d52ed6e4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatescreateorupdate_autorest.go @@ -0,0 +1,68 @@ +package applicationinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplatesCreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *WorkbookTemplate +} + +// WorkbookTemplatesCreateOrUpdate ... +func (c ApplicationInsightsClient) WorkbookTemplatesCreateOrUpdate(ctx context.Context, id WorkbookTemplateId, input WorkbookTemplate) (result WorkbookTemplatesCreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForWorkbookTemplatesCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesCreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesCreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForWorkbookTemplatesCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesCreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForWorkbookTemplatesCreateOrUpdate prepares the WorkbookTemplatesCreateOrUpdate request. +func (c ApplicationInsightsClient) preparerForWorkbookTemplatesCreateOrUpdate(ctx context.Context, id WorkbookTemplateId, input WorkbookTemplate) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForWorkbookTemplatesCreateOrUpdate handles the response to the WorkbookTemplatesCreateOrUpdate request. The method always +// closes the http.Response Body. +func (c ApplicationInsightsClient) responderForWorkbookTemplatesCreateOrUpdate(resp *http.Response) (result WorkbookTemplatesCreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesdelete_autorest.go new file mode 100644 index 000000000000..a8d8153c8b18 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesdelete_autorest.go @@ -0,0 +1,65 @@ +package applicationinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplatesDeleteOperationResponse struct { + HttpResponse *http.Response +} + +// WorkbookTemplatesDelete ... +func (c ApplicationInsightsClient) WorkbookTemplatesDelete(ctx context.Context, id WorkbookTemplateId) (result WorkbookTemplatesDeleteOperationResponse, err error) { + req, err := c.preparerForWorkbookTemplatesDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesDelete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesDelete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForWorkbookTemplatesDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesDelete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForWorkbookTemplatesDelete prepares the WorkbookTemplatesDelete request. +func (c ApplicationInsightsClient) preparerForWorkbookTemplatesDelete(ctx context.Context, id WorkbookTemplateId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForWorkbookTemplatesDelete handles the response to the WorkbookTemplatesDelete request. The method always +// closes the http.Response Body. +func (c ApplicationInsightsClient) responderForWorkbookTemplatesDelete(resp *http.Response) (result WorkbookTemplatesDeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesget_autorest.go new file mode 100644 index 000000000000..f13cb1e9fb2c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesget_autorest.go @@ -0,0 +1,67 @@ +package applicationinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplatesGetOperationResponse struct { + HttpResponse *http.Response + Model *WorkbookTemplate +} + +// WorkbookTemplatesGet ... +func (c ApplicationInsightsClient) WorkbookTemplatesGet(ctx context.Context, id WorkbookTemplateId) (result WorkbookTemplatesGetOperationResponse, err error) { + req, err := c.preparerForWorkbookTemplatesGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForWorkbookTemplatesGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForWorkbookTemplatesGet prepares the WorkbookTemplatesGet request. +func (c ApplicationInsightsClient) preparerForWorkbookTemplatesGet(ctx context.Context, id WorkbookTemplateId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForWorkbookTemplatesGet handles the response to the WorkbookTemplatesGet request. The method always +// closes the http.Response Body. +func (c ApplicationInsightsClient) responderForWorkbookTemplatesGet(resp *http.Response) (result WorkbookTemplatesGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplateslistbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplateslistbyresourcegroup_autorest.go new file mode 100644 index 000000000000..039b198a6bc4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplateslistbyresourcegroup_autorest.go @@ -0,0 +1,69 @@ +package applicationinsights + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplatesListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *WorkbookTemplatesListResult +} + +// WorkbookTemplatesListByResourceGroup ... +func (c ApplicationInsightsClient) WorkbookTemplatesListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (result WorkbookTemplatesListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForWorkbookTemplatesListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForWorkbookTemplatesListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForWorkbookTemplatesListByResourceGroup prepares the WorkbookTemplatesListByResourceGroup request. +func (c ApplicationInsightsClient) preparerForWorkbookTemplatesListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.Insights/workbookTemplates", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForWorkbookTemplatesListByResourceGroup handles the response to the WorkbookTemplatesListByResourceGroup request. The method always +// closes the http.Response Body. +func (c ApplicationInsightsClient) responderForWorkbookTemplatesListByResourceGroup(resp *http.Response) (result WorkbookTemplatesListByResourceGroupOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesupdate_autorest.go new file mode 100644 index 000000000000..3194faaf2ebd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/method_workbooktemplatesupdate_autorest.go @@ -0,0 +1,68 @@ +package applicationinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplatesUpdateOperationResponse struct { + HttpResponse *http.Response + Model *WorkbookTemplate +} + +// WorkbookTemplatesUpdate ... +func (c ApplicationInsightsClient) WorkbookTemplatesUpdate(ctx context.Context, id WorkbookTemplateId, input WorkbookTemplateUpdateParameters) (result WorkbookTemplatesUpdateOperationResponse, err error) { + req, err := c.preparerForWorkbookTemplatesUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForWorkbookTemplatesUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "applicationinsights.ApplicationInsightsClient", "WorkbookTemplatesUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForWorkbookTemplatesUpdate prepares the WorkbookTemplatesUpdate request. +func (c ApplicationInsightsClient) preparerForWorkbookTemplatesUpdate(ctx context.Context, id WorkbookTemplateId, input WorkbookTemplateUpdateParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForWorkbookTemplatesUpdate handles the response to the WorkbookTemplatesUpdate request. The method always +// closes the http.Response Body. +func (c ApplicationInsightsClient) responderForWorkbookTemplatesUpdate(resp *http.Response) (result WorkbookTemplatesUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplate.go new file mode 100644 index 000000000000..a70bfa79a358 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplate.go @@ -0,0 +1,13 @@ +package applicationinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplate struct { + Id *string `json:"id,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties *WorkbookTemplateProperties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplategallery.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplategallery.go new file mode 100644 index 000000000000..4459f03c6d28 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplategallery.go @@ -0,0 +1,12 @@ +package applicationinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplateGallery struct { + Category *string `json:"category,omitempty"` + Name *string `json:"name,omitempty"` + Order *int64 `json:"order,omitempty"` + ResourceType *string `json:"resourceType,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplatelocalizedgallery.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplatelocalizedgallery.go new file mode 100644 index 000000000000..ef525ea0c307 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplatelocalizedgallery.go @@ -0,0 +1,9 @@ +package applicationinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplateLocalizedGallery struct { + Galleries *[]WorkbookTemplateGallery `json:"galleries,omitempty"` + TemplateData *interface{} `json:"templateData,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateproperties.go new file mode 100644 index 000000000000..15c0eb32a94d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateproperties.go @@ -0,0 +1,12 @@ +package applicationinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplateProperties struct { + Author *string `json:"author,omitempty"` + Galleries []WorkbookTemplateGallery `json:"galleries"` + Localized *map[string][]WorkbookTemplateLocalizedGallery `json:"localized,omitempty"` + Priority *int64 `json:"priority,omitempty"` + TemplateData interface{} `json:"templateData"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateslistresult.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateslistresult.go new file mode 100644 index 000000000000..0acb197b2f67 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateslistresult.go @@ -0,0 +1,8 @@ +package applicationinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplatesListResult struct { + Value *[]WorkbookTemplate `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateupdateparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateupdateparameters.go new file mode 100644 index 000000000000..e8a88aa86fcb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/model_workbooktemplateupdateparameters.go @@ -0,0 +1,9 @@ +package applicationinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkbookTemplateUpdateParameters struct { + Properties *WorkbookTemplateProperties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/version.go new file mode 100644 index 000000000000..2dc2d21c4d96 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights/version.go @@ -0,0 +1,12 @@ +package applicationinsights + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2020-11-20" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/applicationinsights/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/README.md new file mode 100644 index 000000000000..115cf52381f8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/README.md @@ -0,0 +1,144 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets` Documentation + +The `availabilitysets` SDK allows for interaction with the Azure Resource Manager Service `compute` (API Version `2021-11-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets" +``` + + +### Client Initialization + +```go +client := availabilitysets.NewAvailabilitySetsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `AvailabilitySetsClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := availabilitysets.NewAvailabilitySetID("12345678-1234-9876-4563-123456789012", "example-resource-group", "availabilitySetValue") + +payload := availabilitysets.AvailabilitySet{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AvailabilitySetsClient.Delete` + +```go +ctx := context.TODO() +id := availabilitysets.NewAvailabilitySetID("12345678-1234-9876-4563-123456789012", "example-resource-group", "availabilitySetValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AvailabilitySetsClient.Get` + +```go +ctx := context.TODO() +id := availabilitysets.NewAvailabilitySetID("12345678-1234-9876-4563-123456789012", "example-resource-group", "availabilitySetValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AvailabilitySetsClient.List` + +```go +ctx := context.TODO() +id := availabilitysets.NewResourceGroupID() + +// alternatively `client.List(ctx, id)` can be used to do batched pagination +items, err := client.ListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `AvailabilitySetsClient.ListAvailableSizes` + +```go +ctx := context.TODO() +id := availabilitysets.NewAvailabilitySetID("12345678-1234-9876-4563-123456789012", "example-resource-group", "availabilitySetValue") + +read, err := client.ListAvailableSizes(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AvailabilitySetsClient.ListBySubscription` + +```go +ctx := context.TODO() +id := availabilitysets.NewSubscriptionID() + +// alternatively `client.ListBySubscription(ctx, id, availabilitysets.DefaultListBySubscriptionOperationOptions())` can be used to do batched pagination +items, err := client.ListBySubscriptionComplete(ctx, id, availabilitysets.DefaultListBySubscriptionOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `AvailabilitySetsClient.Update` + +```go +ctx := context.TODO() +id := availabilitysets.NewAvailabilitySetID("12345678-1234-9876-4563-123456789012", "example-resource-group", "availabilitySetValue") + +payload := availabilitysets.AvailabilitySetUpdate{ + // ... +} + + +read, err := client.Update(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/client.go new file mode 100644 index 000000000000..fbd6545125ad --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/client.go @@ -0,0 +1,18 @@ +package availabilitysets + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AvailabilitySetsClient struct { + Client autorest.Client + baseUri string +} + +func NewAvailabilitySetsClientWithBaseURI(endpoint string) AvailabilitySetsClient { + return AvailabilitySetsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/constants.go new file mode 100644 index 000000000000..22121b1b4b80 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/constants.go @@ -0,0 +1,37 @@ +package availabilitysets + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type StatusLevelTypes string + +const ( + StatusLevelTypesError StatusLevelTypes = "Error" + StatusLevelTypesInfo StatusLevelTypes = "Info" + StatusLevelTypesWarning StatusLevelTypes = "Warning" +) + +func PossibleValuesForStatusLevelTypes() []string { + return []string{ + string(StatusLevelTypesError), + string(StatusLevelTypesInfo), + string(StatusLevelTypesWarning), + } +} + +func parseStatusLevelTypes(input string) (*StatusLevelTypes, error) { + vals := map[string]StatusLevelTypes{ + "error": StatusLevelTypesError, + "info": StatusLevelTypesInfo, + "warning": StatusLevelTypesWarning, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := StatusLevelTypes(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/id_availabilityset.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/id_availabilityset.go new file mode 100644 index 000000000000..b539e5ddae9e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/id_availabilityset.go @@ -0,0 +1,124 @@ +package availabilitysets + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = AvailabilitySetId{} + +// AvailabilitySetId is a struct representing the Resource ID for a Availability Set +type AvailabilitySetId struct { + SubscriptionId string + ResourceGroupName string + AvailabilitySetName string +} + +// NewAvailabilitySetID returns a new AvailabilitySetId struct +func NewAvailabilitySetID(subscriptionId string, resourceGroupName string, availabilitySetName string) AvailabilitySetId { + return AvailabilitySetId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AvailabilitySetName: availabilitySetName, + } +} + +// ParseAvailabilitySetID parses 'input' into a AvailabilitySetId +func ParseAvailabilitySetID(input string) (*AvailabilitySetId, error) { + parser := resourceids.NewParserFromResourceIdType(AvailabilitySetId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AvailabilitySetId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AvailabilitySetName, ok = parsed.Parsed["availabilitySetName"]; !ok { + return nil, fmt.Errorf("the segment 'availabilitySetName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseAvailabilitySetIDInsensitively parses 'input' case-insensitively into a AvailabilitySetId +// note: this method should only be used for API response data and not user input +func ParseAvailabilitySetIDInsensitively(input string) (*AvailabilitySetId, error) { + parser := resourceids.NewParserFromResourceIdType(AvailabilitySetId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AvailabilitySetId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AvailabilitySetName, ok = parsed.Parsed["availabilitySetName"]; !ok { + return nil, fmt.Errorf("the segment 'availabilitySetName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateAvailabilitySetID checks that 'input' can be parsed as a Availability Set ID +func ValidateAvailabilitySetID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseAvailabilitySetID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Availability Set ID +func (id AvailabilitySetId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/availabilitySets/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AvailabilitySetName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Availability Set ID +func (id AvailabilitySetId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftCompute", "Microsoft.Compute", "Microsoft.Compute"), + resourceids.StaticSegment("staticAvailabilitySets", "availabilitySets", "availabilitySets"), + resourceids.UserSpecifiedSegment("availabilitySetName", "availabilitySetValue"), + } +} + +// String returns a human-readable description of this Availability Set ID +func (id AvailabilitySetId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Availability Set Name: %q", id.AvailabilitySetName), + } + return fmt.Sprintf("Availability Set (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_createorupdate_autorest.go new file mode 100644 index 000000000000..270e2c8fa541 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package availabilitysets + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *AvailabilitySet +} + +// CreateOrUpdate ... +func (c AvailabilitySetsClient) CreateOrUpdate(ctx context.Context, id AvailabilitySetId, input AvailabilitySet) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c AvailabilitySetsClient) preparerForCreateOrUpdate(ctx context.Context, id AvailabilitySetId, input AvailabilitySet) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c AvailabilitySetsClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_delete_autorest.go new file mode 100644 index 000000000000..df626fae16e0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_delete_autorest.go @@ -0,0 +1,65 @@ +package availabilitysets + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c AvailabilitySetsClient) Delete(ctx context.Context, id AvailabilitySetId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c AvailabilitySetsClient) preparerForDelete(ctx context.Context, id AvailabilitySetId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c AvailabilitySetsClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_get_autorest.go new file mode 100644 index 000000000000..fc6367e469de --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_get_autorest.go @@ -0,0 +1,67 @@ +package availabilitysets + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *AvailabilitySet +} + +// Get ... +func (c AvailabilitySetsClient) Get(ctx context.Context, id AvailabilitySetId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c AvailabilitySetsClient) preparerForGet(ctx context.Context, id AvailabilitySetId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c AvailabilitySetsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_list_autorest.go new file mode 100644 index 000000000000..1deee2bda46c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_list_autorest.go @@ -0,0 +1,187 @@ +package availabilitysets + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *[]AvailabilitySet + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) +} + +type ListCompleteResult struct { + Items []AvailabilitySet +} + +func (r ListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// List ... +func (c AvailabilitySetsClient) List(ctx context.Context, id commonids.ResourceGroupId) (resp ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "List", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "List", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "List", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListComplete retrieves all of the results into a single object +func (c AvailabilitySetsClient) ListComplete(ctx context.Context, id commonids.ResourceGroupId) (ListCompleteResult, error) { + return c.ListCompleteMatchingPredicate(ctx, id, AvailabilitySetOperationPredicate{}) +} + +// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c AvailabilitySetsClient) ListCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate AvailabilitySetOperationPredicate) (resp ListCompleteResult, err error) { + items := make([]AvailabilitySet, 0) + + page, err := c.List(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForList prepares the List request. +func (c AvailabilitySetsClient) preparerForList(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.Compute/availabilitySets", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListWithNextLink prepares the List request with the given nextLink token. +func (c AvailabilitySetsClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c AvailabilitySetsClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + type page struct { + Values []AvailabilitySet `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { + req, err := c.preparerForListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_listavailablesizes_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_listavailablesizes_autorest.go new file mode 100644 index 000000000000..659fbfd5489d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_listavailablesizes_autorest.go @@ -0,0 +1,68 @@ +package availabilitysets + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListAvailableSizesOperationResponse struct { + HttpResponse *http.Response + Model *VirtualMachineSizeListResult +} + +// ListAvailableSizes ... +func (c AvailabilitySetsClient) ListAvailableSizes(ctx context.Context, id AvailabilitySetId) (result ListAvailableSizesOperationResponse, err error) { + req, err := c.preparerForListAvailableSizes(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "ListAvailableSizes", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "ListAvailableSizes", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListAvailableSizes(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "ListAvailableSizes", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForListAvailableSizes prepares the ListAvailableSizes request. +func (c AvailabilitySetsClient) preparerForListAvailableSizes(ctx context.Context, id AvailabilitySetId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/vmSizes", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListAvailableSizes handles the response to the ListAvailableSizes request. The method always +// closes the http.Response Body. +func (c AvailabilitySetsClient) responderForListAvailableSizes(resp *http.Response) (result ListAvailableSizesOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_listbysubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_listbysubscription_autorest.go new file mode 100644 index 000000000000..2b7e026a0b9b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_listbysubscription_autorest.go @@ -0,0 +1,216 @@ +package availabilitysets + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListBySubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *[]AvailabilitySet + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListBySubscriptionOperationResponse, error) +} + +type ListBySubscriptionCompleteResult struct { + Items []AvailabilitySet +} + +func (r ListBySubscriptionOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListBySubscriptionOperationResponse) LoadMore(ctx context.Context) (resp ListBySubscriptionOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type ListBySubscriptionOperationOptions struct { + Expand *string +} + +func DefaultListBySubscriptionOperationOptions() ListBySubscriptionOperationOptions { + return ListBySubscriptionOperationOptions{} +} + +func (o ListBySubscriptionOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o ListBySubscriptionOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Expand != nil { + out["$expand"] = *o.Expand + } + + return out +} + +// ListBySubscription ... +func (c AvailabilitySetsClient) ListBySubscription(ctx context.Context, id commonids.SubscriptionId, options ListBySubscriptionOperationOptions) (resp ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscription(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "ListBySubscription", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListBySubscription(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "ListBySubscription", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListBySubscriptionComplete retrieves all of the results into a single object +func (c AvailabilitySetsClient) ListBySubscriptionComplete(ctx context.Context, id commonids.SubscriptionId, options ListBySubscriptionOperationOptions) (ListBySubscriptionCompleteResult, error) { + return c.ListBySubscriptionCompleteMatchingPredicate(ctx, id, options, AvailabilitySetOperationPredicate{}) +} + +// ListBySubscriptionCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c AvailabilitySetsClient) ListBySubscriptionCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, options ListBySubscriptionOperationOptions, predicate AvailabilitySetOperationPredicate) (resp ListBySubscriptionCompleteResult, err error) { + items := make([]AvailabilitySet, 0) + + page, err := c.ListBySubscription(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListBySubscriptionCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListBySubscription prepares the ListBySubscription request. +func (c AvailabilitySetsClient) preparerForListBySubscription(ctx context.Context, id commonids.SubscriptionId, options ListBySubscriptionOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.Compute/availabilitySets", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListBySubscriptionWithNextLink prepares the ListBySubscription request with the given nextLink token. +func (c AvailabilitySetsClient) preparerForListBySubscriptionWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListBySubscription handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (c AvailabilitySetsClient) responderForListBySubscription(resp *http.Response) (result ListBySubscriptionOperationResponse, err error) { + type page struct { + Values []AvailabilitySet `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscriptionWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "ListBySubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListBySubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "ListBySubscription", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_update_autorest.go new file mode 100644 index 000000000000..6015ccee987d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/method_update_autorest.go @@ -0,0 +1,68 @@ +package availabilitysets + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + HttpResponse *http.Response + Model *AvailabilitySet +} + +// Update ... +func (c AvailabilitySetsClient) Update(ctx context.Context, id AvailabilitySetId, input AvailabilitySetUpdate) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "Update", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "availabilitysets.AvailabilitySetsClient", "Update", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForUpdate prepares the Update request. +func (c AvailabilitySetsClient) preparerForUpdate(ctx context.Context, id AvailabilitySetId, input AvailabilitySetUpdate) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForUpdate handles the response to the Update request. The method always +// closes the http.Response Body. +func (c AvailabilitySetsClient) responderForUpdate(resp *http.Response) (result UpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilityset.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilityset.go new file mode 100644 index 000000000000..49248ed2f4ac --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilityset.go @@ -0,0 +1,14 @@ +package availabilitysets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AvailabilitySet struct { + Id *string `json:"id,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties *AvailabilitySetProperties `json:"properties,omitempty"` + Sku *Sku `json:"sku,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilitysetproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilitysetproperties.go new file mode 100644 index 000000000000..3e1e7585608d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilitysetproperties.go @@ -0,0 +1,12 @@ +package availabilitysets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AvailabilitySetProperties struct { + PlatformFaultDomainCount *int64 `json:"platformFaultDomainCount,omitempty"` + PlatformUpdateDomainCount *int64 `json:"platformUpdateDomainCount,omitempty"` + ProximityPlacementGroup *SubResource `json:"proximityPlacementGroup,omitempty"` + Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` + VirtualMachines *[]SubResource `json:"virtualMachines,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilitysetupdate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilitysetupdate.go new file mode 100644 index 000000000000..04ce035cd463 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_availabilitysetupdate.go @@ -0,0 +1,10 @@ +package availabilitysets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AvailabilitySetUpdate struct { + Properties *AvailabilitySetProperties `json:"properties,omitempty"` + Sku *Sku `json:"sku,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_instanceviewstatus.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_instanceviewstatus.go new file mode 100644 index 000000000000..038a3c1dd32b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_instanceviewstatus.go @@ -0,0 +1,30 @@ +package availabilitysets + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type InstanceViewStatus struct { + Code *string `json:"code,omitempty"` + DisplayStatus *string `json:"displayStatus,omitempty"` + Level *StatusLevelTypes `json:"level,omitempty"` + Message *string `json:"message,omitempty"` + Time *string `json:"time,omitempty"` +} + +func (o *InstanceViewStatus) GetTimeAsTime() (*time.Time, error) { + if o.Time == nil { + return nil, nil + } + return dates.ParseAsFormat(o.Time, "2006-01-02T15:04:05Z07:00") +} + +func (o *InstanceViewStatus) SetTimeAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.Time = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_sku.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_sku.go new file mode 100644 index 000000000000..9e275b34b2a9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_sku.go @@ -0,0 +1,10 @@ +package availabilitysets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Sku struct { + Capacity *int64 `json:"capacity,omitempty"` + Name *string `json:"name,omitempty"` + Tier *string `json:"tier,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_subresource.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_subresource.go new file mode 100644 index 000000000000..9890abb18c98 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_subresource.go @@ -0,0 +1,8 @@ +package availabilitysets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SubResource struct { + Id *string `json:"id,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_virtualmachinesize.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_virtualmachinesize.go new file mode 100644 index 000000000000..d9b2adc37582 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_virtualmachinesize.go @@ -0,0 +1,13 @@ +package availabilitysets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VirtualMachineSize struct { + MaxDataDiskCount *int64 `json:"maxDataDiskCount,omitempty"` + MemoryInMB *int64 `json:"memoryInMB,omitempty"` + Name *string `json:"name,omitempty"` + NumberOfCores *int64 `json:"numberOfCores,omitempty"` + OsDiskSizeInMB *int64 `json:"osDiskSizeInMB,omitempty"` + ResourceDiskSizeInMB *int64 `json:"resourceDiskSizeInMB,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_virtualmachinesizelistresult.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_virtualmachinesizelistresult.go new file mode 100644 index 000000000000..190cfb1b6703 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/model_virtualmachinesizelistresult.go @@ -0,0 +1,8 @@ +package availabilitysets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VirtualMachineSizeListResult struct { + Value *[]VirtualMachineSize `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/predicates.go new file mode 100644 index 000000000000..224859f306a4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/predicates.go @@ -0,0 +1,29 @@ +package availabilitysets + +type AvailabilitySetOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p AvailabilitySetOperationPredicate) Matches(input AvailabilitySet) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/version.go new file mode 100644 index 000000000000..f51ca52b5548 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets/version.go @@ -0,0 +1,12 @@ +package availabilitysets + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-11-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/availabilitysets/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/README.md new file mode 100644 index 000000000000..fdcfb4ad34c3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/README.md @@ -0,0 +1,144 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys` Documentation + +The `sshpublickeys` SDK allows for interaction with the Azure Resource Manager Service `compute` (API Version `2021-11-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys" +``` + + +### Client Initialization + +```go +client := sshpublickeys.NewSshPublicKeysClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `SshPublicKeysClient.Create` + +```go +ctx := context.TODO() +id := sshpublickeys.NewSshPublicKeyID("12345678-1234-9876-4563-123456789012", "example-resource-group", "sshPublicKeyValue") + +payload := sshpublickeys.SshPublicKeyResource{ + // ... +} + + +read, err := client.Create(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SshPublicKeysClient.Delete` + +```go +ctx := context.TODO() +id := sshpublickeys.NewSshPublicKeyID("12345678-1234-9876-4563-123456789012", "example-resource-group", "sshPublicKeyValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SshPublicKeysClient.GenerateKeyPair` + +```go +ctx := context.TODO() +id := sshpublickeys.NewSshPublicKeyID("12345678-1234-9876-4563-123456789012", "example-resource-group", "sshPublicKeyValue") + +read, err := client.GenerateKeyPair(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SshPublicKeysClient.Get` + +```go +ctx := context.TODO() +id := sshpublickeys.NewSshPublicKeyID("12345678-1234-9876-4563-123456789012", "example-resource-group", "sshPublicKeyValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SshPublicKeysClient.ListByResourceGroup` + +```go +ctx := context.TODO() +id := sshpublickeys.NewResourceGroupID() + +// alternatively `client.ListByResourceGroup(ctx, id)` can be used to do batched pagination +items, err := client.ListByResourceGroupComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SshPublicKeysClient.ListBySubscription` + +```go +ctx := context.TODO() +id := sshpublickeys.NewSubscriptionID() + +// alternatively `client.ListBySubscription(ctx, id)` can be used to do batched pagination +items, err := client.ListBySubscriptionComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SshPublicKeysClient.Update` + +```go +ctx := context.TODO() +id := sshpublickeys.NewSshPublicKeyID("12345678-1234-9876-4563-123456789012", "example-resource-group", "sshPublicKeyValue") + +payload := sshpublickeys.SshPublicKeyUpdateResource{ + // ... +} + + +read, err := client.Update(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/client.go new file mode 100644 index 000000000000..e7322535ac38 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/client.go @@ -0,0 +1,18 @@ +package sshpublickeys + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SshPublicKeysClient struct { + Client autorest.Client + baseUri string +} + +func NewSshPublicKeysClientWithBaseURI(endpoint string) SshPublicKeysClient { + return SshPublicKeysClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/id_sshpublickey.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/id_sshpublickey.go new file mode 100644 index 000000000000..1cdafea9f5d8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/id_sshpublickey.go @@ -0,0 +1,124 @@ +package sshpublickeys + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = SshPublicKeyId{} + +// SshPublicKeyId is a struct representing the Resource ID for a Ssh Public Key +type SshPublicKeyId struct { + SubscriptionId string + ResourceGroupName string + SshPublicKeyName string +} + +// NewSshPublicKeyID returns a new SshPublicKeyId struct +func NewSshPublicKeyID(subscriptionId string, resourceGroupName string, sshPublicKeyName string) SshPublicKeyId { + return SshPublicKeyId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + SshPublicKeyName: sshPublicKeyName, + } +} + +// ParseSshPublicKeyID parses 'input' into a SshPublicKeyId +func ParseSshPublicKeyID(input string) (*SshPublicKeyId, error) { + parser := resourceids.NewParserFromResourceIdType(SshPublicKeyId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SshPublicKeyId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.SshPublicKeyName, ok = parsed.Parsed["sshPublicKeyName"]; !ok { + return nil, fmt.Errorf("the segment 'sshPublicKeyName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseSshPublicKeyIDInsensitively parses 'input' case-insensitively into a SshPublicKeyId +// note: this method should only be used for API response data and not user input +func ParseSshPublicKeyIDInsensitively(input string) (*SshPublicKeyId, error) { + parser := resourceids.NewParserFromResourceIdType(SshPublicKeyId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SshPublicKeyId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.SshPublicKeyName, ok = parsed.Parsed["sshPublicKeyName"]; !ok { + return nil, fmt.Errorf("the segment 'sshPublicKeyName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateSshPublicKeyID checks that 'input' can be parsed as a Ssh Public Key ID +func ValidateSshPublicKeyID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseSshPublicKeyID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Ssh Public Key ID +func (id SshPublicKeyId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/sshPublicKeys/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.SshPublicKeyName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Ssh Public Key ID +func (id SshPublicKeyId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftCompute", "Microsoft.Compute", "Microsoft.Compute"), + resourceids.StaticSegment("staticSshPublicKeys", "sshPublicKeys", "sshPublicKeys"), + resourceids.UserSpecifiedSegment("sshPublicKeyName", "sshPublicKeyValue"), + } +} + +// String returns a human-readable description of this Ssh Public Key ID +func (id SshPublicKeyId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Ssh Public Key Name: %q", id.SshPublicKeyName), + } + return fmt.Sprintf("Ssh Public Key (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_create_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_create_autorest.go new file mode 100644 index 000000000000..f345d2d5248b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_create_autorest.go @@ -0,0 +1,68 @@ +package sshpublickeys + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOperationResponse struct { + HttpResponse *http.Response + Model *SshPublicKeyResource +} + +// Create ... +func (c SshPublicKeysClient) Create(ctx context.Context, id SshPublicKeyId, input SshPublicKeyResource) (result CreateOperationResponse, err error) { + req, err := c.preparerForCreate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Create", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Create", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Create", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreate prepares the Create request. +func (c SshPublicKeysClient) preparerForCreate(ctx context.Context, id SshPublicKeyId, input SshPublicKeyResource) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreate handles the response to the Create request. The method always +// closes the http.Response Body. +func (c SshPublicKeysClient) responderForCreate(resp *http.Response) (result CreateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_delete_autorest.go new file mode 100644 index 000000000000..391c3818fb84 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_delete_autorest.go @@ -0,0 +1,65 @@ +package sshpublickeys + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c SshPublicKeysClient) Delete(ctx context.Context, id SshPublicKeyId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c SshPublicKeysClient) preparerForDelete(ctx context.Context, id SshPublicKeyId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c SshPublicKeysClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_generatekeypair_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_generatekeypair_autorest.go new file mode 100644 index 000000000000..6a3f9a5c2379 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_generatekeypair_autorest.go @@ -0,0 +1,68 @@ +package sshpublickeys + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GenerateKeyPairOperationResponse struct { + HttpResponse *http.Response + Model *SshPublicKeyGenerateKeyPairResult +} + +// GenerateKeyPair ... +func (c SshPublicKeysClient) GenerateKeyPair(ctx context.Context, id SshPublicKeyId) (result GenerateKeyPairOperationResponse, err error) { + req, err := c.preparerForGenerateKeyPair(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "GenerateKeyPair", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "GenerateKeyPair", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGenerateKeyPair(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "GenerateKeyPair", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGenerateKeyPair prepares the GenerateKeyPair request. +func (c SshPublicKeysClient) preparerForGenerateKeyPair(ctx context.Context, id SshPublicKeyId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/generateKeyPair", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGenerateKeyPair handles the response to the GenerateKeyPair request. The method always +// closes the http.Response Body. +func (c SshPublicKeysClient) responderForGenerateKeyPair(resp *http.Response) (result GenerateKeyPairOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_get_autorest.go new file mode 100644 index 000000000000..13aa31199484 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_get_autorest.go @@ -0,0 +1,67 @@ +package sshpublickeys + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *SshPublicKeyResource +} + +// Get ... +func (c SshPublicKeysClient) Get(ctx context.Context, id SshPublicKeyId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c SshPublicKeysClient) preparerForGet(ctx context.Context, id SshPublicKeyId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c SshPublicKeysClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_listbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_listbyresourcegroup_autorest.go new file mode 100644 index 000000000000..96103a131fd3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_listbyresourcegroup_autorest.go @@ -0,0 +1,187 @@ +package sshpublickeys + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]SshPublicKeyResource + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByResourceGroupOperationResponse, error) +} + +type ListByResourceGroupCompleteResult struct { + Items []SshPublicKeyResource +} + +func (r ListByResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ListByResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListByResourceGroup ... +func (c SshPublicKeysClient) ListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByResourceGroupComplete retrieves all of the results into a single object +func (c SshPublicKeysClient) ListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ListByResourceGroupCompleteResult, error) { + return c.ListByResourceGroupCompleteMatchingPredicate(ctx, id, SshPublicKeyResourceOperationPredicate{}) +} + +// ListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SshPublicKeysClient) ListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate SshPublicKeyResourceOperationPredicate) (resp ListByResourceGroupCompleteResult, err error) { + items := make([]SshPublicKeyResource, 0) + + page, err := c.ListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByResourceGroup prepares the ListByResourceGroup request. +func (c SshPublicKeysClient) preparerForListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.Compute/sshPublicKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByResourceGroupWithNextLink prepares the ListByResourceGroup request with the given nextLink token. +func (c SshPublicKeysClient) preparerForListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByResourceGroup handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (c SshPublicKeysClient) responderForListByResourceGroup(resp *http.Response) (result ListByResourceGroupOperationResponse, err error) { + type page struct { + Values []SshPublicKeyResource `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_listbysubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_listbysubscription_autorest.go new file mode 100644 index 000000000000..f43255ca14cd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_listbysubscription_autorest.go @@ -0,0 +1,187 @@ +package sshpublickeys + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListBySubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *[]SshPublicKeyResource + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListBySubscriptionOperationResponse, error) +} + +type ListBySubscriptionCompleteResult struct { + Items []SshPublicKeyResource +} + +func (r ListBySubscriptionOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListBySubscriptionOperationResponse) LoadMore(ctx context.Context) (resp ListBySubscriptionOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListBySubscription ... +func (c SshPublicKeysClient) ListBySubscription(ctx context.Context, id commonids.SubscriptionId) (resp ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscription(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListBySubscription", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListBySubscription(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListBySubscription", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListBySubscriptionComplete retrieves all of the results into a single object +func (c SshPublicKeysClient) ListBySubscriptionComplete(ctx context.Context, id commonids.SubscriptionId) (ListBySubscriptionCompleteResult, error) { + return c.ListBySubscriptionCompleteMatchingPredicate(ctx, id, SshPublicKeyResourceOperationPredicate{}) +} + +// ListBySubscriptionCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SshPublicKeysClient) ListBySubscriptionCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate SshPublicKeyResourceOperationPredicate) (resp ListBySubscriptionCompleteResult, err error) { + items := make([]SshPublicKeyResource, 0) + + page, err := c.ListBySubscription(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListBySubscriptionCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListBySubscription prepares the ListBySubscription request. +func (c SshPublicKeysClient) preparerForListBySubscription(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.Compute/sshPublicKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListBySubscriptionWithNextLink prepares the ListBySubscription request with the given nextLink token. +func (c SshPublicKeysClient) preparerForListBySubscriptionWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListBySubscription handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (c SshPublicKeysClient) responderForListBySubscription(resp *http.Response) (result ListBySubscriptionOperationResponse, err error) { + type page struct { + Values []SshPublicKeyResource `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscriptionWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListBySubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListBySubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "ListBySubscription", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_update_autorest.go new file mode 100644 index 000000000000..b17c0d315f41 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/method_update_autorest.go @@ -0,0 +1,68 @@ +package sshpublickeys + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + HttpResponse *http.Response + Model *SshPublicKeyResource +} + +// Update ... +func (c SshPublicKeysClient) Update(ctx context.Context, id SshPublicKeyId, input SshPublicKeyUpdateResource) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Update", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "sshpublickeys.SshPublicKeysClient", "Update", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForUpdate prepares the Update request. +func (c SshPublicKeysClient) preparerForUpdate(ctx context.Context, id SshPublicKeyId, input SshPublicKeyUpdateResource) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForUpdate handles the response to the Update request. The method always +// closes the http.Response Body. +func (c SshPublicKeysClient) responderForUpdate(resp *http.Response) (result UpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeygeneratekeypairresult.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeygeneratekeypairresult.go new file mode 100644 index 000000000000..cf57d99b2680 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeygeneratekeypairresult.go @@ -0,0 +1,10 @@ +package sshpublickeys + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SshPublicKeyGenerateKeyPairResult struct { + Id string `json:"id"` + PrivateKey string `json:"privateKey"` + PublicKey string `json:"publicKey"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyresource.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyresource.go new file mode 100644 index 000000000000..bbabaefed196 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyresource.go @@ -0,0 +1,13 @@ +package sshpublickeys + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SshPublicKeyResource struct { + Id *string `json:"id,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties *SshPublicKeyResourceProperties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyresourceproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyresourceproperties.go new file mode 100644 index 000000000000..b1d00a16a128 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyresourceproperties.go @@ -0,0 +1,8 @@ +package sshpublickeys + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SshPublicKeyResourceProperties struct { + PublicKey *string `json:"publicKey,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyupdateresource.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyupdateresource.go new file mode 100644 index 000000000000..e5ab89367c58 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/model_sshpublickeyupdateresource.go @@ -0,0 +1,9 @@ +package sshpublickeys + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SshPublicKeyUpdateResource struct { + Properties *SshPublicKeyResourceProperties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/predicates.go new file mode 100644 index 000000000000..f369fdbf1292 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/predicates.go @@ -0,0 +1,29 @@ +package sshpublickeys + +type SshPublicKeyResourceOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p SshPublicKeyResourceOperationPredicate) Matches(input SshPublicKeyResource) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/version.go new file mode 100644 index 000000000000..dfef6a053cbb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys/version.go @@ -0,0 +1,12 @@ +package sshpublickeys + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-11-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/sshpublickeys/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/README.md new file mode 100644 index 000000000000..08d11810c6f2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/README.md @@ -0,0 +1,263 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance` Documentation + +The `containerinstance` SDK allows for interaction with the Azure Resource Manager Service `containerinstance` (API Version `2021-03-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance" +``` + + +### Client Initialization + +```go +client := containerinstance.NewContainerInstanceClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `ContainerInstanceClient.ContainerGroupsCreateOrUpdate` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue") + +payload := containerinstance.ContainerGroup{ + // ... +} + + +if err := client.ContainerGroupsCreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainerGroupsDelete` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue") + +if err := client.ContainerGroupsDeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainerGroupsGet` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue") + +read, err := client.ContainerGroupsGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainerGroupsList` + +```go +ctx := context.TODO() +id := containerinstance.NewSubscriptionID() + +// alternatively `client.ContainerGroupsList(ctx, id)` can be used to do batched pagination +items, err := client.ContainerGroupsListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainerGroupsListByResourceGroup` + +```go +ctx := context.TODO() +id := containerinstance.NewResourceGroupID() + +// alternatively `client.ContainerGroupsListByResourceGroup(ctx, id)` can be used to do batched pagination +items, err := client.ContainerGroupsListByResourceGroupComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainerGroupsRestart` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue") + +if err := client.ContainerGroupsRestartThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainerGroupsStart` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue") + +if err := client.ContainerGroupsStartThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainerGroupsStop` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue") + +read, err := client.ContainerGroupsStop(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainerGroupsUpdate` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue") + +payload := containerinstance.Resource{ + // ... +} + + +read, err := client.ContainerGroupsUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainersAttach` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue", "containerValue") + +read, err := client.ContainersAttach(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainersExecuteCommand` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue", "containerValue") + +payload := containerinstance.ContainerExecRequest{ + // ... +} + + +read, err := client.ContainersExecuteCommand(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ContainerInstanceClient.ContainersListLogs` + +```go +ctx := context.TODO() +id := containerinstance.NewContainerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "containerGroupValue", "containerValue") + +read, err := client.ContainersListLogs(ctx, id, containerinstance.DefaultContainersListLogsOperationOptions()) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ContainerInstanceClient.LocationListCachedImages` + +```go +ctx := context.TODO() +id := containerinstance.NewLocationID("12345678-1234-9876-4563-123456789012", "locationValue") + +// alternatively `client.LocationListCachedImages(ctx, id)` can be used to do batched pagination +items, err := client.LocationListCachedImagesComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `ContainerInstanceClient.LocationListCapabilities` + +```go +ctx := context.TODO() +id := containerinstance.NewLocationID("12345678-1234-9876-4563-123456789012", "locationValue") + +// alternatively `client.LocationListCapabilities(ctx, id)` can be used to do batched pagination +items, err := client.LocationListCapabilitiesComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `ContainerInstanceClient.LocationListUsage` + +```go +ctx := context.TODO() +id := containerinstance.NewLocationID("12345678-1234-9876-4563-123456789012", "locationValue") + +read, err := client.LocationListUsage(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/client.go new file mode 100644 index 000000000000..7c611fe53d7c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/client.go @@ -0,0 +1,18 @@ +package containerinstance + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerInstanceClient struct { + Client autorest.Client + baseUri string +} + +func NewContainerInstanceClientWithBaseURI(endpoint string) ContainerInstanceClient { + return ContainerInstanceClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/constants.go new file mode 100644 index 000000000000..4209a2b00df1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/constants.go @@ -0,0 +1,264 @@ +package containerinstance + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupIpAddressType string + +const ( + ContainerGroupIpAddressTypePrivate ContainerGroupIpAddressType = "Private" + ContainerGroupIpAddressTypePublic ContainerGroupIpAddressType = "Public" +) + +func PossibleValuesForContainerGroupIpAddressType() []string { + return []string{ + string(ContainerGroupIpAddressTypePrivate), + string(ContainerGroupIpAddressTypePublic), + } +} + +func parseContainerGroupIpAddressType(input string) (*ContainerGroupIpAddressType, error) { + vals := map[string]ContainerGroupIpAddressType{ + "private": ContainerGroupIpAddressTypePrivate, + "public": ContainerGroupIpAddressTypePublic, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ContainerGroupIpAddressType(input) + return &out, nil +} + +type ContainerGroupNetworkProtocol string + +const ( + ContainerGroupNetworkProtocolTCP ContainerGroupNetworkProtocol = "TCP" + ContainerGroupNetworkProtocolUDP ContainerGroupNetworkProtocol = "UDP" +) + +func PossibleValuesForContainerGroupNetworkProtocol() []string { + return []string{ + string(ContainerGroupNetworkProtocolTCP), + string(ContainerGroupNetworkProtocolUDP), + } +} + +func parseContainerGroupNetworkProtocol(input string) (*ContainerGroupNetworkProtocol, error) { + vals := map[string]ContainerGroupNetworkProtocol{ + "tcp": ContainerGroupNetworkProtocolTCP, + "udp": ContainerGroupNetworkProtocolUDP, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ContainerGroupNetworkProtocol(input) + return &out, nil +} + +type ContainerGroupRestartPolicy string + +const ( + ContainerGroupRestartPolicyAlways ContainerGroupRestartPolicy = "Always" + ContainerGroupRestartPolicyNever ContainerGroupRestartPolicy = "Never" + ContainerGroupRestartPolicyOnFailure ContainerGroupRestartPolicy = "OnFailure" +) + +func PossibleValuesForContainerGroupRestartPolicy() []string { + return []string{ + string(ContainerGroupRestartPolicyAlways), + string(ContainerGroupRestartPolicyNever), + string(ContainerGroupRestartPolicyOnFailure), + } +} + +func parseContainerGroupRestartPolicy(input string) (*ContainerGroupRestartPolicy, error) { + vals := map[string]ContainerGroupRestartPolicy{ + "always": ContainerGroupRestartPolicyAlways, + "never": ContainerGroupRestartPolicyNever, + "onfailure": ContainerGroupRestartPolicyOnFailure, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ContainerGroupRestartPolicy(input) + return &out, nil +} + +type ContainerGroupSku string + +const ( + ContainerGroupSkuDedicated ContainerGroupSku = "Dedicated" + ContainerGroupSkuStandard ContainerGroupSku = "Standard" +) + +func PossibleValuesForContainerGroupSku() []string { + return []string{ + string(ContainerGroupSkuDedicated), + string(ContainerGroupSkuStandard), + } +} + +func parseContainerGroupSku(input string) (*ContainerGroupSku, error) { + vals := map[string]ContainerGroupSku{ + "dedicated": ContainerGroupSkuDedicated, + "standard": ContainerGroupSkuStandard, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ContainerGroupSku(input) + return &out, nil +} + +type ContainerNetworkProtocol string + +const ( + ContainerNetworkProtocolTCP ContainerNetworkProtocol = "TCP" + ContainerNetworkProtocolUDP ContainerNetworkProtocol = "UDP" +) + +func PossibleValuesForContainerNetworkProtocol() []string { + return []string{ + string(ContainerNetworkProtocolTCP), + string(ContainerNetworkProtocolUDP), + } +} + +func parseContainerNetworkProtocol(input string) (*ContainerNetworkProtocol, error) { + vals := map[string]ContainerNetworkProtocol{ + "tcp": ContainerNetworkProtocolTCP, + "udp": ContainerNetworkProtocolUDP, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ContainerNetworkProtocol(input) + return &out, nil +} + +type GpuSku string + +const ( + GpuSkuKEightZero GpuSku = "K80" + GpuSkuPOneHundred GpuSku = "P100" + GpuSkuVOneHundred GpuSku = "V100" +) + +func PossibleValuesForGpuSku() []string { + return []string{ + string(GpuSkuKEightZero), + string(GpuSkuPOneHundred), + string(GpuSkuVOneHundred), + } +} + +func parseGpuSku(input string) (*GpuSku, error) { + vals := map[string]GpuSku{ + "k80": GpuSkuKEightZero, + "p100": GpuSkuPOneHundred, + "v100": GpuSkuVOneHundred, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := GpuSku(input) + return &out, nil +} + +type LogAnalyticsLogType string + +const ( + LogAnalyticsLogTypeContainerInsights LogAnalyticsLogType = "ContainerInsights" + LogAnalyticsLogTypeContainerInstanceLogs LogAnalyticsLogType = "ContainerInstanceLogs" +) + +func PossibleValuesForLogAnalyticsLogType() []string { + return []string{ + string(LogAnalyticsLogTypeContainerInsights), + string(LogAnalyticsLogTypeContainerInstanceLogs), + } +} + +func parseLogAnalyticsLogType(input string) (*LogAnalyticsLogType, error) { + vals := map[string]LogAnalyticsLogType{ + "containerinsights": LogAnalyticsLogTypeContainerInsights, + "containerinstancelogs": LogAnalyticsLogTypeContainerInstanceLogs, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := LogAnalyticsLogType(input) + return &out, nil +} + +type OperatingSystemTypes string + +const ( + OperatingSystemTypesLinux OperatingSystemTypes = "Linux" + OperatingSystemTypesWindows OperatingSystemTypes = "Windows" +) + +func PossibleValuesForOperatingSystemTypes() []string { + return []string{ + string(OperatingSystemTypesLinux), + string(OperatingSystemTypesWindows), + } +} + +func parseOperatingSystemTypes(input string) (*OperatingSystemTypes, error) { + vals := map[string]OperatingSystemTypes{ + "linux": OperatingSystemTypesLinux, + "windows": OperatingSystemTypesWindows, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := OperatingSystemTypes(input) + return &out, nil +} + +type Scheme string + +const ( + SchemeHttp Scheme = "http" + SchemeHttps Scheme = "https" +) + +func PossibleValuesForScheme() []string { + return []string{ + string(SchemeHttp), + string(SchemeHttps), + } +} + +func parseScheme(input string) (*Scheme, error) { + vals := map[string]Scheme{ + "http": SchemeHttp, + "https": SchemeHttps, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := Scheme(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_container.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_container.go new file mode 100644 index 000000000000..614af5e4336f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_container.go @@ -0,0 +1,137 @@ +package containerinstance + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ContainerId{} + +// ContainerId is a struct representing the Resource ID for a Container +type ContainerId struct { + SubscriptionId string + ResourceGroupName string + ContainerGroupName string + ContainerName string +} + +// NewContainerID returns a new ContainerId struct +func NewContainerID(subscriptionId string, resourceGroupName string, containerGroupName string, containerName string) ContainerId { + return ContainerId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ContainerGroupName: containerGroupName, + ContainerName: containerName, + } +} + +// ParseContainerID parses 'input' into a ContainerId +func ParseContainerID(input string) (*ContainerId, error) { + parser := resourceids.NewParserFromResourceIdType(ContainerId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ContainerId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ContainerGroupName, ok = parsed.Parsed["containerGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'containerGroupName' was not found in the resource id %q", input) + } + + if id.ContainerName, ok = parsed.Parsed["containerName"]; !ok { + return nil, fmt.Errorf("the segment 'containerName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseContainerIDInsensitively parses 'input' case-insensitively into a ContainerId +// note: this method should only be used for API response data and not user input +func ParseContainerIDInsensitively(input string) (*ContainerId, error) { + parser := resourceids.NewParserFromResourceIdType(ContainerId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ContainerId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ContainerGroupName, ok = parsed.Parsed["containerGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'containerGroupName' was not found in the resource id %q", input) + } + + if id.ContainerName, ok = parsed.Parsed["containerName"]; !ok { + return nil, fmt.Errorf("the segment 'containerName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateContainerID checks that 'input' can be parsed as a Container ID +func ValidateContainerID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseContainerID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Container ID +func (id ContainerId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ContainerInstance/containerGroups/%s/containers/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ContainerGroupName, id.ContainerName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Container ID +func (id ContainerId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftContainerInstance", "Microsoft.ContainerInstance", "Microsoft.ContainerInstance"), + resourceids.StaticSegment("staticContainerGroups", "containerGroups", "containerGroups"), + resourceids.UserSpecifiedSegment("containerGroupName", "containerGroupValue"), + resourceids.StaticSegment("staticContainers", "containers", "containers"), + resourceids.UserSpecifiedSegment("containerName", "containerValue"), + } +} + +// String returns a human-readable description of this Container ID +func (id ContainerId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Container Group Name: %q", id.ContainerGroupName), + fmt.Sprintf("Container Name: %q", id.ContainerName), + } + return fmt.Sprintf("Container (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_containergroup.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_containergroup.go new file mode 100644 index 000000000000..75ce7b7c4e41 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_containergroup.go @@ -0,0 +1,124 @@ +package containerinstance + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ContainerGroupId{} + +// ContainerGroupId is a struct representing the Resource ID for a Container Group +type ContainerGroupId struct { + SubscriptionId string + ResourceGroupName string + ContainerGroupName string +} + +// NewContainerGroupID returns a new ContainerGroupId struct +func NewContainerGroupID(subscriptionId string, resourceGroupName string, containerGroupName string) ContainerGroupId { + return ContainerGroupId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ContainerGroupName: containerGroupName, + } +} + +// ParseContainerGroupID parses 'input' into a ContainerGroupId +func ParseContainerGroupID(input string) (*ContainerGroupId, error) { + parser := resourceids.NewParserFromResourceIdType(ContainerGroupId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ContainerGroupId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ContainerGroupName, ok = parsed.Parsed["containerGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'containerGroupName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseContainerGroupIDInsensitively parses 'input' case-insensitively into a ContainerGroupId +// note: this method should only be used for API response data and not user input +func ParseContainerGroupIDInsensitively(input string) (*ContainerGroupId, error) { + parser := resourceids.NewParserFromResourceIdType(ContainerGroupId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ContainerGroupId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ContainerGroupName, ok = parsed.Parsed["containerGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'containerGroupName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateContainerGroupID checks that 'input' can be parsed as a Container Group ID +func ValidateContainerGroupID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseContainerGroupID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Container Group ID +func (id ContainerGroupId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ContainerInstance/containerGroups/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ContainerGroupName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Container Group ID +func (id ContainerGroupId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftContainerInstance", "Microsoft.ContainerInstance", "Microsoft.ContainerInstance"), + resourceids.StaticSegment("staticContainerGroups", "containerGroups", "containerGroups"), + resourceids.UserSpecifiedSegment("containerGroupName", "containerGroupValue"), + } +} + +// String returns a human-readable description of this Container Group ID +func (id ContainerGroupId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Container Group Name: %q", id.ContainerGroupName), + } + return fmt.Sprintf("Container Group (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_location.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_location.go new file mode 100644 index 000000000000..a1f453fb23fb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/id_location.go @@ -0,0 +1,111 @@ +package containerinstance + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = LocationId{} + +// LocationId is a struct representing the Resource ID for a Location +type LocationId struct { + SubscriptionId string + Location string +} + +// NewLocationID returns a new LocationId struct +func NewLocationID(subscriptionId string, location string) LocationId { + return LocationId{ + SubscriptionId: subscriptionId, + Location: location, + } +} + +// ParseLocationID parses 'input' into a LocationId +func ParseLocationID(input string) (*LocationId, error) { + parser := resourceids.NewParserFromResourceIdType(LocationId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := LocationId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.Location, ok = parsed.Parsed["location"]; !ok { + return nil, fmt.Errorf("the segment 'location' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseLocationIDInsensitively parses 'input' case-insensitively into a LocationId +// note: this method should only be used for API response data and not user input +func ParseLocationIDInsensitively(input string) (*LocationId, error) { + parser := resourceids.NewParserFromResourceIdType(LocationId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := LocationId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.Location, ok = parsed.Parsed["location"]; !ok { + return nil, fmt.Errorf("the segment 'location' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateLocationID checks that 'input' can be parsed as a Location ID +func ValidateLocationID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseLocationID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Location ID +func (id LocationId) ID() string { + fmtString := "/subscriptions/%s/providers/Microsoft.ContainerInstance/locations/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.Location) +} + +// Segments returns a slice of Resource ID Segments which comprise this Location ID +func (id LocationId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftContainerInstance", "Microsoft.ContainerInstance", "Microsoft.ContainerInstance"), + resourceids.StaticSegment("staticLocations", "locations", "locations"), + resourceids.UserSpecifiedSegment("location", "locationValue"), + } +} + +// String returns a human-readable description of this Location ID +func (id LocationId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Location: %q", id.Location), + } + return fmt.Sprintf("Location (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupscreateorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupscreateorupdate_autorest.go new file mode 100644 index 000000000000..801ccd09e962 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupscreateorupdate_autorest.go @@ -0,0 +1,79 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupsCreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// ContainerGroupsCreateOrUpdate ... +func (c ContainerInstanceClient) ContainerGroupsCreateOrUpdate(ctx context.Context, id ContainerGroupId, input ContainerGroup) (result ContainerGroupsCreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForContainerGroupsCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsCreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForContainerGroupsCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsCreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// ContainerGroupsCreateOrUpdateThenPoll performs ContainerGroupsCreateOrUpdate then polls until it's completed +func (c ContainerInstanceClient) ContainerGroupsCreateOrUpdateThenPoll(ctx context.Context, id ContainerGroupId, input ContainerGroup) error { + result, err := c.ContainerGroupsCreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing ContainerGroupsCreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after ContainerGroupsCreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForContainerGroupsCreateOrUpdate prepares the ContainerGroupsCreateOrUpdate request. +func (c ContainerInstanceClient) preparerForContainerGroupsCreateOrUpdate(ctx context.Context, id ContainerGroupId, input ContainerGroup) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForContainerGroupsCreateOrUpdate sends the ContainerGroupsCreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c ContainerInstanceClient) senderForContainerGroupsCreateOrUpdate(ctx context.Context, req *http.Request) (future ContainerGroupsCreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsdelete_autorest.go new file mode 100644 index 000000000000..7468b631f234 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsdelete_autorest.go @@ -0,0 +1,78 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupsDeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// ContainerGroupsDelete ... +func (c ContainerInstanceClient) ContainerGroupsDelete(ctx context.Context, id ContainerGroupId) (result ContainerGroupsDeleteOperationResponse, err error) { + req, err := c.preparerForContainerGroupsDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsDelete", nil, "Failure preparing request") + return + } + + result, err = c.senderForContainerGroupsDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsDelete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// ContainerGroupsDeleteThenPoll performs ContainerGroupsDelete then polls until it's completed +func (c ContainerInstanceClient) ContainerGroupsDeleteThenPoll(ctx context.Context, id ContainerGroupId) error { + result, err := c.ContainerGroupsDelete(ctx, id) + if err != nil { + return fmt.Errorf("performing ContainerGroupsDelete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after ContainerGroupsDelete: %+v", err) + } + + return nil +} + +// preparerForContainerGroupsDelete prepares the ContainerGroupsDelete request. +func (c ContainerInstanceClient) preparerForContainerGroupsDelete(ctx context.Context, id ContainerGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForContainerGroupsDelete sends the ContainerGroupsDelete request. The method will close the +// http.Response Body if it receives an error. +func (c ContainerInstanceClient) senderForContainerGroupsDelete(ctx context.Context, req *http.Request) (future ContainerGroupsDeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsget_autorest.go new file mode 100644 index 000000000000..1a0d38f45fd2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsget_autorest.go @@ -0,0 +1,67 @@ +package containerinstance + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupsGetOperationResponse struct { + HttpResponse *http.Response + Model *ContainerGroup +} + +// ContainerGroupsGet ... +func (c ContainerInstanceClient) ContainerGroupsGet(ctx context.Context, id ContainerGroupId) (result ContainerGroupsGetOperationResponse, err error) { + req, err := c.preparerForContainerGroupsGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForContainerGroupsGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForContainerGroupsGet prepares the ContainerGroupsGet request. +func (c ContainerInstanceClient) preparerForContainerGroupsGet(ctx context.Context, id ContainerGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForContainerGroupsGet handles the response to the ContainerGroupsGet request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForContainerGroupsGet(resp *http.Response) (result ContainerGroupsGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupslist_autorest.go new file mode 100644 index 000000000000..b20598aa4ca4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupslist_autorest.go @@ -0,0 +1,187 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupsListOperationResponse struct { + HttpResponse *http.Response + Model *[]ContainerGroup + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ContainerGroupsListOperationResponse, error) +} + +type ContainerGroupsListCompleteResult struct { + Items []ContainerGroup +} + +func (r ContainerGroupsListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ContainerGroupsListOperationResponse) LoadMore(ctx context.Context) (resp ContainerGroupsListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ContainerGroupsList ... +func (c ContainerInstanceClient) ContainerGroupsList(ctx context.Context, id commonids.SubscriptionId) (resp ContainerGroupsListOperationResponse, err error) { + req, err := c.preparerForContainerGroupsList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForContainerGroupsList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ContainerGroupsListComplete retrieves all of the results into a single object +func (c ContainerInstanceClient) ContainerGroupsListComplete(ctx context.Context, id commonids.SubscriptionId) (ContainerGroupsListCompleteResult, error) { + return c.ContainerGroupsListCompleteMatchingPredicate(ctx, id, ContainerGroupOperationPredicate{}) +} + +// ContainerGroupsListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c ContainerInstanceClient) ContainerGroupsListCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate ContainerGroupOperationPredicate) (resp ContainerGroupsListCompleteResult, err error) { + items := make([]ContainerGroup, 0) + + page, err := c.ContainerGroupsList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ContainerGroupsListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForContainerGroupsList prepares the ContainerGroupsList request. +func (c ContainerInstanceClient) preparerForContainerGroupsList(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.ContainerInstance/containerGroups", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForContainerGroupsListWithNextLink prepares the ContainerGroupsList request with the given nextLink token. +func (c ContainerInstanceClient) preparerForContainerGroupsListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForContainerGroupsList handles the response to the ContainerGroupsList request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForContainerGroupsList(resp *http.Response) (result ContainerGroupsListOperationResponse, err error) { + type page struct { + Values []ContainerGroup `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ContainerGroupsListOperationResponse, err error) { + req, err := c.preparerForContainerGroupsListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForContainerGroupsList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupslistbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupslistbyresourcegroup_autorest.go new file mode 100644 index 000000000000..105d7ee4bb44 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupslistbyresourcegroup_autorest.go @@ -0,0 +1,187 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupsListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]ContainerGroup + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ContainerGroupsListByResourceGroupOperationResponse, error) +} + +type ContainerGroupsListByResourceGroupCompleteResult struct { + Items []ContainerGroup +} + +func (r ContainerGroupsListByResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ContainerGroupsListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ContainerGroupsListByResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ContainerGroupsListByResourceGroup ... +func (c ContainerInstanceClient) ContainerGroupsListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ContainerGroupsListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForContainerGroupsListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForContainerGroupsListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ContainerGroupsListByResourceGroupComplete retrieves all of the results into a single object +func (c ContainerInstanceClient) ContainerGroupsListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ContainerGroupsListByResourceGroupCompleteResult, error) { + return c.ContainerGroupsListByResourceGroupCompleteMatchingPredicate(ctx, id, ContainerGroupOperationPredicate{}) +} + +// ContainerGroupsListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c ContainerInstanceClient) ContainerGroupsListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate ContainerGroupOperationPredicate) (resp ContainerGroupsListByResourceGroupCompleteResult, err error) { + items := make([]ContainerGroup, 0) + + page, err := c.ContainerGroupsListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ContainerGroupsListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForContainerGroupsListByResourceGroup prepares the ContainerGroupsListByResourceGroup request. +func (c ContainerInstanceClient) preparerForContainerGroupsListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.ContainerInstance/containerGroups", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForContainerGroupsListByResourceGroupWithNextLink prepares the ContainerGroupsListByResourceGroup request with the given nextLink token. +func (c ContainerInstanceClient) preparerForContainerGroupsListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForContainerGroupsListByResourceGroup handles the response to the ContainerGroupsListByResourceGroup request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForContainerGroupsListByResourceGroup(resp *http.Response) (result ContainerGroupsListByResourceGroupOperationResponse, err error) { + type page struct { + Values []ContainerGroup `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ContainerGroupsListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForContainerGroupsListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForContainerGroupsListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsrestart_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsrestart_autorest.go new file mode 100644 index 000000000000..b4792ea3d197 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsrestart_autorest.go @@ -0,0 +1,78 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupsRestartOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// ContainerGroupsRestart ... +func (c ContainerInstanceClient) ContainerGroupsRestart(ctx context.Context, id ContainerGroupId) (result ContainerGroupsRestartOperationResponse, err error) { + req, err := c.preparerForContainerGroupsRestart(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsRestart", nil, "Failure preparing request") + return + } + + result, err = c.senderForContainerGroupsRestart(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsRestart", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// ContainerGroupsRestartThenPoll performs ContainerGroupsRestart then polls until it's completed +func (c ContainerInstanceClient) ContainerGroupsRestartThenPoll(ctx context.Context, id ContainerGroupId) error { + result, err := c.ContainerGroupsRestart(ctx, id) + if err != nil { + return fmt.Errorf("performing ContainerGroupsRestart: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after ContainerGroupsRestart: %+v", err) + } + + return nil +} + +// preparerForContainerGroupsRestart prepares the ContainerGroupsRestart request. +func (c ContainerInstanceClient) preparerForContainerGroupsRestart(ctx context.Context, id ContainerGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/restart", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForContainerGroupsRestart sends the ContainerGroupsRestart request. The method will close the +// http.Response Body if it receives an error. +func (c ContainerInstanceClient) senderForContainerGroupsRestart(ctx context.Context, req *http.Request) (future ContainerGroupsRestartOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsstart_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsstart_autorest.go new file mode 100644 index 000000000000..eb0e27e83be3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsstart_autorest.go @@ -0,0 +1,78 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupsStartOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// ContainerGroupsStart ... +func (c ContainerInstanceClient) ContainerGroupsStart(ctx context.Context, id ContainerGroupId) (result ContainerGroupsStartOperationResponse, err error) { + req, err := c.preparerForContainerGroupsStart(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsStart", nil, "Failure preparing request") + return + } + + result, err = c.senderForContainerGroupsStart(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsStart", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// ContainerGroupsStartThenPoll performs ContainerGroupsStart then polls until it's completed +func (c ContainerInstanceClient) ContainerGroupsStartThenPoll(ctx context.Context, id ContainerGroupId) error { + result, err := c.ContainerGroupsStart(ctx, id) + if err != nil { + return fmt.Errorf("performing ContainerGroupsStart: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after ContainerGroupsStart: %+v", err) + } + + return nil +} + +// preparerForContainerGroupsStart prepares the ContainerGroupsStart request. +func (c ContainerInstanceClient) preparerForContainerGroupsStart(ctx context.Context, id ContainerGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/start", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForContainerGroupsStart sends the ContainerGroupsStart request. The method will close the +// http.Response Body if it receives an error. +func (c ContainerInstanceClient) senderForContainerGroupsStart(ctx context.Context, req *http.Request) (future ContainerGroupsStartOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsstop_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsstop_autorest.go new file mode 100644 index 000000000000..0feaf54c046f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsstop_autorest.go @@ -0,0 +1,66 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupsStopOperationResponse struct { + HttpResponse *http.Response +} + +// ContainerGroupsStop ... +func (c ContainerInstanceClient) ContainerGroupsStop(ctx context.Context, id ContainerGroupId) (result ContainerGroupsStopOperationResponse, err error) { + req, err := c.preparerForContainerGroupsStop(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsStop", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsStop", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForContainerGroupsStop(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsStop", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForContainerGroupsStop prepares the ContainerGroupsStop request. +func (c ContainerInstanceClient) preparerForContainerGroupsStop(ctx context.Context, id ContainerGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/stop", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForContainerGroupsStop handles the response to the ContainerGroupsStop request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForContainerGroupsStop(resp *http.Response) (result ContainerGroupsStopOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsupdate_autorest.go new file mode 100644 index 000000000000..add0927f328c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containergroupsupdate_autorest.go @@ -0,0 +1,68 @@ +package containerinstance + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupsUpdateOperationResponse struct { + HttpResponse *http.Response + Model *ContainerGroup +} + +// ContainerGroupsUpdate ... +func (c ContainerInstanceClient) ContainerGroupsUpdate(ctx context.Context, id ContainerGroupId, input Resource) (result ContainerGroupsUpdateOperationResponse, err error) { + req, err := c.preparerForContainerGroupsUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForContainerGroupsUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainerGroupsUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForContainerGroupsUpdate prepares the ContainerGroupsUpdate request. +func (c ContainerInstanceClient) preparerForContainerGroupsUpdate(ctx context.Context, id ContainerGroupId, input Resource) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForContainerGroupsUpdate handles the response to the ContainerGroupsUpdate request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForContainerGroupsUpdate(resp *http.Response) (result ContainerGroupsUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containersattach_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containersattach_autorest.go new file mode 100644 index 000000000000..53f6a1f5b230 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containersattach_autorest.go @@ -0,0 +1,68 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainersAttachOperationResponse struct { + HttpResponse *http.Response + Model *ContainerAttachResponse +} + +// ContainersAttach ... +func (c ContainerInstanceClient) ContainersAttach(ctx context.Context, id ContainerId) (result ContainersAttachOperationResponse, err error) { + req, err := c.preparerForContainersAttach(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainersAttach", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainersAttach", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForContainersAttach(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainersAttach", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForContainersAttach prepares the ContainersAttach request. +func (c ContainerInstanceClient) preparerForContainersAttach(ctx context.Context, id ContainerId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/attach", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForContainersAttach handles the response to the ContainersAttach request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForContainersAttach(resp *http.Response) (result ContainersAttachOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containersexecutecommand_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containersexecutecommand_autorest.go new file mode 100644 index 000000000000..d0a2325d912b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containersexecutecommand_autorest.go @@ -0,0 +1,69 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainersExecuteCommandOperationResponse struct { + HttpResponse *http.Response + Model *ContainerExecResponse +} + +// ContainersExecuteCommand ... +func (c ContainerInstanceClient) ContainersExecuteCommand(ctx context.Context, id ContainerId, input ContainerExecRequest) (result ContainersExecuteCommandOperationResponse, err error) { + req, err := c.preparerForContainersExecuteCommand(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainersExecuteCommand", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainersExecuteCommand", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForContainersExecuteCommand(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainersExecuteCommand", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForContainersExecuteCommand prepares the ContainersExecuteCommand request. +func (c ContainerInstanceClient) preparerForContainersExecuteCommand(ctx context.Context, id ContainerId, input ContainerExecRequest) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/exec", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForContainersExecuteCommand handles the response to the ContainersExecuteCommand request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForContainersExecuteCommand(resp *http.Response) (result ContainersExecuteCommandOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containerslistlogs_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containerslistlogs_autorest.go new file mode 100644 index 000000000000..6b6c261b1e61 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_containerslistlogs_autorest.go @@ -0,0 +1,102 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainersListLogsOperationResponse struct { + HttpResponse *http.Response + Model *Logs +} + +type ContainersListLogsOperationOptions struct { + Tail *int64 + Timestamps *bool +} + +func DefaultContainersListLogsOperationOptions() ContainersListLogsOperationOptions { + return ContainersListLogsOperationOptions{} +} + +func (o ContainersListLogsOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o ContainersListLogsOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Tail != nil { + out["tail"] = *o.Tail + } + + if o.Timestamps != nil { + out["timestamps"] = *o.Timestamps + } + + return out +} + +// ContainersListLogs ... +func (c ContainerInstanceClient) ContainersListLogs(ctx context.Context, id ContainerId, options ContainersListLogsOperationOptions) (result ContainersListLogsOperationResponse, err error) { + req, err := c.preparerForContainersListLogs(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainersListLogs", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainersListLogs", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForContainersListLogs(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "ContainersListLogs", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForContainersListLogs prepares the ContainersListLogs request. +func (c ContainerInstanceClient) preparerForContainersListLogs(ctx context.Context, id ContainerId, options ContainersListLogsOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/logs", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForContainersListLogs handles the response to the ContainersListLogs request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForContainersListLogs(resp *http.Response) (result ContainersListLogsOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistcachedimages_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistcachedimages_autorest.go new file mode 100644 index 000000000000..4f63c44fa76d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistcachedimages_autorest.go @@ -0,0 +1,186 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type LocationListCachedImagesOperationResponse struct { + HttpResponse *http.Response + Model *[]CachedImages + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (LocationListCachedImagesOperationResponse, error) +} + +type LocationListCachedImagesCompleteResult struct { + Items []CachedImages +} + +func (r LocationListCachedImagesOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r LocationListCachedImagesOperationResponse) LoadMore(ctx context.Context) (resp LocationListCachedImagesOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// LocationListCachedImages ... +func (c ContainerInstanceClient) LocationListCachedImages(ctx context.Context, id LocationId) (resp LocationListCachedImagesOperationResponse, err error) { + req, err := c.preparerForLocationListCachedImages(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCachedImages", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCachedImages", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForLocationListCachedImages(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCachedImages", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// LocationListCachedImagesComplete retrieves all of the results into a single object +func (c ContainerInstanceClient) LocationListCachedImagesComplete(ctx context.Context, id LocationId) (LocationListCachedImagesCompleteResult, error) { + return c.LocationListCachedImagesCompleteMatchingPredicate(ctx, id, CachedImagesOperationPredicate{}) +} + +// LocationListCachedImagesCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c ContainerInstanceClient) LocationListCachedImagesCompleteMatchingPredicate(ctx context.Context, id LocationId, predicate CachedImagesOperationPredicate) (resp LocationListCachedImagesCompleteResult, err error) { + items := make([]CachedImages, 0) + + page, err := c.LocationListCachedImages(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := LocationListCachedImagesCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForLocationListCachedImages prepares the LocationListCachedImages request. +func (c ContainerInstanceClient) preparerForLocationListCachedImages(ctx context.Context, id LocationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/cachedImages", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForLocationListCachedImagesWithNextLink prepares the LocationListCachedImages request with the given nextLink token. +func (c ContainerInstanceClient) preparerForLocationListCachedImagesWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForLocationListCachedImages handles the response to the LocationListCachedImages request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForLocationListCachedImages(resp *http.Response) (result LocationListCachedImagesOperationResponse, err error) { + type page struct { + Values []CachedImages `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result LocationListCachedImagesOperationResponse, err error) { + req, err := c.preparerForLocationListCachedImagesWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCachedImages", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCachedImages", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForLocationListCachedImages(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCachedImages", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistcapabilities_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistcapabilities_autorest.go new file mode 100644 index 000000000000..89047d6d87d8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistcapabilities_autorest.go @@ -0,0 +1,186 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type LocationListCapabilitiesOperationResponse struct { + HttpResponse *http.Response + Model *[]Capabilities + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (LocationListCapabilitiesOperationResponse, error) +} + +type LocationListCapabilitiesCompleteResult struct { + Items []Capabilities +} + +func (r LocationListCapabilitiesOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r LocationListCapabilitiesOperationResponse) LoadMore(ctx context.Context) (resp LocationListCapabilitiesOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// LocationListCapabilities ... +func (c ContainerInstanceClient) LocationListCapabilities(ctx context.Context, id LocationId) (resp LocationListCapabilitiesOperationResponse, err error) { + req, err := c.preparerForLocationListCapabilities(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCapabilities", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCapabilities", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForLocationListCapabilities(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCapabilities", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// LocationListCapabilitiesComplete retrieves all of the results into a single object +func (c ContainerInstanceClient) LocationListCapabilitiesComplete(ctx context.Context, id LocationId) (LocationListCapabilitiesCompleteResult, error) { + return c.LocationListCapabilitiesCompleteMatchingPredicate(ctx, id, CapabilitiesOperationPredicate{}) +} + +// LocationListCapabilitiesCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c ContainerInstanceClient) LocationListCapabilitiesCompleteMatchingPredicate(ctx context.Context, id LocationId, predicate CapabilitiesOperationPredicate) (resp LocationListCapabilitiesCompleteResult, err error) { + items := make([]Capabilities, 0) + + page, err := c.LocationListCapabilities(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := LocationListCapabilitiesCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForLocationListCapabilities prepares the LocationListCapabilities request. +func (c ContainerInstanceClient) preparerForLocationListCapabilities(ctx context.Context, id LocationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/capabilities", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForLocationListCapabilitiesWithNextLink prepares the LocationListCapabilities request with the given nextLink token. +func (c ContainerInstanceClient) preparerForLocationListCapabilitiesWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForLocationListCapabilities handles the response to the LocationListCapabilities request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForLocationListCapabilities(resp *http.Response) (result LocationListCapabilitiesOperationResponse, err error) { + type page struct { + Values []Capabilities `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result LocationListCapabilitiesOperationResponse, err error) { + req, err := c.preparerForLocationListCapabilitiesWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCapabilities", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCapabilities", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForLocationListCapabilities(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListCapabilities", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistusage_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistusage_autorest.go new file mode 100644 index 000000000000..f3bf85b1c83a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/method_locationlistusage_autorest.go @@ -0,0 +1,68 @@ +package containerinstance + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type LocationListUsageOperationResponse struct { + HttpResponse *http.Response + Model *UsageListResult +} + +// LocationListUsage ... +func (c ContainerInstanceClient) LocationListUsage(ctx context.Context, id LocationId) (result LocationListUsageOperationResponse, err error) { + req, err := c.preparerForLocationListUsage(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListUsage", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListUsage", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForLocationListUsage(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "containerinstance.ContainerInstanceClient", "LocationListUsage", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForLocationListUsage prepares the LocationListUsage request. +func (c ContainerInstanceClient) preparerForLocationListUsage(ctx context.Context, id LocationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/usages", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForLocationListUsage handles the response to the LocationListUsage request. The method always +// closes the http.Response Body. +func (c ContainerInstanceClient) responderForLocationListUsage(resp *http.Response) (result LocationListUsageOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_azurefilevolume.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_azurefilevolume.go new file mode 100644 index 000000000000..f884ba7abf4c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_azurefilevolume.go @@ -0,0 +1,11 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AzureFileVolume struct { + ReadOnly *bool `json:"readOnly,omitempty"` + ShareName string `json:"shareName"` + StorageAccountKey *string `json:"storageAccountKey,omitempty"` + StorageAccountName string `json:"storageAccountName"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_cachedimages.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_cachedimages.go new file mode 100644 index 000000000000..35f76b327042 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_cachedimages.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CachedImages struct { + Image string `json:"image"` + OsType string `json:"osType"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_capabilities.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_capabilities.go new file mode 100644 index 000000000000..d515082a46d4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_capabilities.go @@ -0,0 +1,13 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Capabilities struct { + Capabilities *CapabilitiesCapabilities `json:"capabilities,omitempty"` + Gpu *string `json:"gpu,omitempty"` + IpAddressType *string `json:"ipAddressType,omitempty"` + Location *string `json:"location,omitempty"` + OsType *string `json:"osType,omitempty"` + ResourceType *string `json:"resourceType,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_capabilitiescapabilities.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_capabilitiescapabilities.go new file mode 100644 index 000000000000..257ec5ced3ed --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_capabilitiescapabilities.go @@ -0,0 +1,10 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CapabilitiesCapabilities struct { + MaxCpu *float64 `json:"maxCpu,omitempty"` + MaxGpuCount *float64 `json:"maxGpuCount,omitempty"` + MaxMemoryInGB *float64 `json:"maxMemoryInGB,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_container.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_container.go new file mode 100644 index 000000000000..cd048b57c1eb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_container.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Container struct { + Name string `json:"name"` + Properties ContainerProperties `json:"properties"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerattachresponse.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerattachresponse.go new file mode 100644 index 000000000000..5944a02f3d46 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerattachresponse.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerAttachResponse struct { + Password *string `json:"password,omitempty"` + WebSocketUri *string `json:"webSocketUri,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexec.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexec.go new file mode 100644 index 000000000000..dfa94b71f192 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexec.go @@ -0,0 +1,8 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerExec struct { + Command *[]string `json:"command,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecrequest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecrequest.go new file mode 100644 index 000000000000..078e69d0fb88 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecrequest.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerExecRequest struct { + Command *string `json:"command,omitempty"` + TerminalSize *ContainerExecRequestTerminalSize `json:"terminalSize,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecrequestterminalsize.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecrequestterminalsize.go new file mode 100644 index 000000000000..40110632964e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecrequestterminalsize.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerExecRequestTerminalSize struct { + Cols *int64 `json:"cols,omitempty"` + Rows *int64 `json:"rows,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecresponse.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecresponse.go new file mode 100644 index 000000000000..61c49fda4164 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerexecresponse.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerExecResponse struct { + Password *string `json:"password,omitempty"` + WebSocketUri *string `json:"webSocketUri,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroup.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroup.go new file mode 100644 index 000000000000..87017579b0cf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroup.go @@ -0,0 +1,18 @@ +package containerinstance + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroup struct { + Id *string `json:"id,omitempty"` + Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Properties ContainerGroupProperties `json:"properties"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupdiagnostics.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupdiagnostics.go new file mode 100644 index 000000000000..b26d399f4586 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupdiagnostics.go @@ -0,0 +1,8 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupDiagnostics struct { + LogAnalytics *LogAnalytics `json:"logAnalytics,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupnetworkprofile.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupnetworkprofile.go new file mode 100644 index 000000000000..dbfe19e65586 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupnetworkprofile.go @@ -0,0 +1,8 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupNetworkProfile struct { + Id string `json:"id"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupproperties.go new file mode 100644 index 000000000000..5191baef7629 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergroupproperties.go @@ -0,0 +1,21 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupProperties struct { + Containers []Container `json:"containers"` + Diagnostics *ContainerGroupDiagnostics `json:"diagnostics,omitempty"` + DnsConfig *DnsConfiguration `json:"dnsConfig,omitempty"` + EncryptionProperties *EncryptionProperties `json:"encryptionProperties,omitempty"` + ImageRegistryCredentials *[]ImageRegistryCredential `json:"imageRegistryCredentials,omitempty"` + InitContainers *[]InitContainerDefinition `json:"initContainers,omitempty"` + InstanceView *ContainerGroupPropertiesInstanceView `json:"instanceView,omitempty"` + IpAddress *IpAddress `json:"ipAddress,omitempty"` + NetworkProfile *ContainerGroupNetworkProfile `json:"networkProfile,omitempty"` + OsType OperatingSystemTypes `json:"osType"` + ProvisioningState *string `json:"provisioningState,omitempty"` + RestartPolicy *ContainerGroupRestartPolicy `json:"restartPolicy,omitempty"` + Sku *ContainerGroupSku `json:"sku,omitempty"` + Volumes *[]Volume `json:"volumes,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergrouppropertiesinstanceview.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergrouppropertiesinstanceview.go new file mode 100644 index 000000000000..6652cfdfeee8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containergrouppropertiesinstanceview.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerGroupPropertiesInstanceView struct { + Events *[]Event `json:"events,omitempty"` + State *string `json:"state,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerhttpget.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerhttpget.go new file mode 100644 index 000000000000..3ce858f1afe5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerhttpget.go @@ -0,0 +1,11 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerHttpGet struct { + HttpHeaders *[]HttpHeader `json:"httpHeaders,omitempty"` + Path *string `json:"path,omitempty"` + Port int64 `json:"port"` + Scheme *Scheme `json:"scheme,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerport.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerport.go new file mode 100644 index 000000000000..26e3c3d6180d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerport.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerPort struct { + Port int64 `json:"port"` + Protocol *ContainerNetworkProtocol `json:"protocol,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerprobe.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerprobe.go new file mode 100644 index 000000000000..4bdf40dfe5cf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerprobe.go @@ -0,0 +1,14 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerProbe struct { + Exec *ContainerExec `json:"exec,omitempty"` + FailureThreshold *int64 `json:"failureThreshold,omitempty"` + HttpGet *ContainerHttpGet `json:"httpGet,omitempty"` + InitialDelaySeconds *int64 `json:"initialDelaySeconds,omitempty"` + PeriodSeconds *int64 `json:"periodSeconds,omitempty"` + SuccessThreshold *int64 `json:"successThreshold,omitempty"` + TimeoutSeconds *int64 `json:"timeoutSeconds,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerproperties.go new file mode 100644 index 000000000000..19f54823c9d0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerproperties.go @@ -0,0 +1,16 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerProperties struct { + Command *[]string `json:"command,omitempty"` + EnvironmentVariables *[]EnvironmentVariable `json:"environmentVariables,omitempty"` + Image string `json:"image"` + InstanceView *ContainerPropertiesInstanceView `json:"instanceView,omitempty"` + LivenessProbe *ContainerProbe `json:"livenessProbe,omitempty"` + Ports *[]ContainerPort `json:"ports,omitempty"` + ReadinessProbe *ContainerProbe `json:"readinessProbe,omitempty"` + Resources ResourceRequirements `json:"resources"` + VolumeMounts *[]VolumeMount `json:"volumeMounts,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerpropertiesinstanceview.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerpropertiesinstanceview.go new file mode 100644 index 000000000000..347af45a182b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerpropertiesinstanceview.go @@ -0,0 +1,11 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerPropertiesInstanceView struct { + CurrentState *ContainerState `json:"currentState,omitempty"` + Events *[]Event `json:"events,omitempty"` + PreviousState *ContainerState `json:"previousState,omitempty"` + RestartCount *int64 `json:"restartCount,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerstate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerstate.go new file mode 100644 index 000000000000..b75c2eee165a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_containerstate.go @@ -0,0 +1,42 @@ +package containerinstance + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ContainerState struct { + DetailStatus *string `json:"detailStatus,omitempty"` + ExitCode *int64 `json:"exitCode,omitempty"` + FinishTime *string `json:"finishTime,omitempty"` + StartTime *string `json:"startTime,omitempty"` + State *string `json:"state,omitempty"` +} + +func (o *ContainerState) GetFinishTimeAsTime() (*time.Time, error) { + if o.FinishTime == nil { + return nil, nil + } + return dates.ParseAsFormat(o.FinishTime, "2006-01-02T15:04:05Z07:00") +} + +func (o *ContainerState) SetFinishTimeAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.FinishTime = &formatted +} + +func (o *ContainerState) GetStartTimeAsTime() (*time.Time, error) { + if o.StartTime == nil { + return nil, nil + } + return dates.ParseAsFormat(o.StartTime, "2006-01-02T15:04:05Z07:00") +} + +func (o *ContainerState) SetStartTimeAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.StartTime = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_dnsconfiguration.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_dnsconfiguration.go new file mode 100644 index 000000000000..08581fd75d3b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_dnsconfiguration.go @@ -0,0 +1,10 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DnsConfiguration struct { + NameServers []string `json:"nameServers"` + Options *string `json:"options,omitempty"` + SearchDomains *string `json:"searchDomains,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_encryptionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_encryptionproperties.go new file mode 100644 index 000000000000..d0aeecbc61e1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_encryptionproperties.go @@ -0,0 +1,10 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EncryptionProperties struct { + KeyName string `json:"keyName"` + KeyVersion string `json:"keyVersion"` + VaultBaseUrl string `json:"vaultBaseUrl"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_environmentvariable.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_environmentvariable.go new file mode 100644 index 000000000000..2184f90aa065 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_environmentvariable.go @@ -0,0 +1,10 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EnvironmentVariable struct { + Name string `json:"name"` + SecureValue *string `json:"secureValue,omitempty"` + Value *string `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_event.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_event.go new file mode 100644 index 000000000000..a66aa6de0146 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_event.go @@ -0,0 +1,43 @@ +package containerinstance + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Event struct { + Count *int64 `json:"count,omitempty"` + FirstTimestamp *string `json:"firstTimestamp,omitempty"` + LastTimestamp *string `json:"lastTimestamp,omitempty"` + Message *string `json:"message,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` +} + +func (o *Event) GetFirstTimestampAsTime() (*time.Time, error) { + if o.FirstTimestamp == nil { + return nil, nil + } + return dates.ParseAsFormat(o.FirstTimestamp, "2006-01-02T15:04:05Z07:00") +} + +func (o *Event) SetFirstTimestampAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.FirstTimestamp = &formatted +} + +func (o *Event) GetLastTimestampAsTime() (*time.Time, error) { + if o.LastTimestamp == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastTimestamp, "2006-01-02T15:04:05Z07:00") +} + +func (o *Event) SetLastTimestampAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastTimestamp = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_gitrepovolume.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_gitrepovolume.go new file mode 100644 index 000000000000..fe91482b0974 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_gitrepovolume.go @@ -0,0 +1,10 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GitRepoVolume struct { + Directory *string `json:"directory,omitempty"` + Repository string `json:"repository"` + Revision *string `json:"revision,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_gpuresource.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_gpuresource.go new file mode 100644 index 000000000000..eb389f05ae8e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_gpuresource.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GpuResource struct { + Count int64 `json:"count"` + Sku GpuSku `json:"sku"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_httpheader.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_httpheader.go new file mode 100644 index 000000000000..b4825abbeea0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_httpheader.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type HttpHeader struct { + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_imageregistrycredential.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_imageregistrycredential.go new file mode 100644 index 000000000000..3bc3e568c9f3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_imageregistrycredential.go @@ -0,0 +1,10 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ImageRegistryCredential struct { + Password *string `json:"password,omitempty"` + Server string `json:"server"` + Username string `json:"username"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerdefinition.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerdefinition.go new file mode 100644 index 000000000000..01211fb4a023 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerdefinition.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type InitContainerDefinition struct { + Name string `json:"name"` + Properties InitContainerPropertiesDefinition `json:"properties"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerpropertiesdefinition.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerpropertiesdefinition.go new file mode 100644 index 000000000000..301fd4ebd306 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerpropertiesdefinition.go @@ -0,0 +1,12 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type InitContainerPropertiesDefinition struct { + Command *[]string `json:"command,omitempty"` + EnvironmentVariables *[]EnvironmentVariable `json:"environmentVariables,omitempty"` + Image *string `json:"image,omitempty"` + InstanceView *InitContainerPropertiesDefinitionInstanceView `json:"instanceView,omitempty"` + VolumeMounts *[]VolumeMount `json:"volumeMounts,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerpropertiesdefinitioninstanceview.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerpropertiesdefinitioninstanceview.go new file mode 100644 index 000000000000..fd71b6bc7a1b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_initcontainerpropertiesdefinitioninstanceview.go @@ -0,0 +1,11 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type InitContainerPropertiesDefinitionInstanceView struct { + CurrentState *ContainerState `json:"currentState,omitempty"` + Events *[]Event `json:"events,omitempty"` + PreviousState *ContainerState `json:"previousState,omitempty"` + RestartCount *int64 `json:"restartCount,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_ipaddress.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_ipaddress.go new file mode 100644 index 000000000000..b4b56f1ef622 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_ipaddress.go @@ -0,0 +1,12 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type IpAddress struct { + DnsNameLabel *string `json:"dnsNameLabel,omitempty"` + Fqdn *string `json:"fqdn,omitempty"` + Ip *string `json:"ip,omitempty"` + Ports []Port `json:"ports"` + Type ContainerGroupIpAddressType `json:"type"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_loganalytics.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_loganalytics.go new file mode 100644 index 000000000000..df8644c0e3fd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_loganalytics.go @@ -0,0 +1,12 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type LogAnalytics struct { + LogType *LogAnalyticsLogType `json:"logType,omitempty"` + Metadata *map[string]string `json:"metadata,omitempty"` + WorkspaceId string `json:"workspaceId"` + WorkspaceKey string `json:"workspaceKey"` + WorkspaceResourceId *map[string]string `json:"workspaceResourceId,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_logs.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_logs.go new file mode 100644 index 000000000000..7e4dbc049387 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_logs.go @@ -0,0 +1,8 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Logs struct { + Content *string `json:"content,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_port.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_port.go new file mode 100644 index 000000000000..e3a87272de3b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_port.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Port struct { + Port int64 `json:"port"` + Protocol *ContainerGroupNetworkProtocol `json:"protocol,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resource.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resource.go new file mode 100644 index 000000000000..d9db6f7f3e6e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resource.go @@ -0,0 +1,12 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Resource struct { + Id *string `json:"id,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcelimits.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcelimits.go new file mode 100644 index 000000000000..8a2f7fc441d2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcelimits.go @@ -0,0 +1,10 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ResourceLimits struct { + Cpu *float64 `json:"cpu,omitempty"` + Gpu *GpuResource `json:"gpu,omitempty"` + MemoryInGB *float64 `json:"memoryInGB,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcerequests.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcerequests.go new file mode 100644 index 000000000000..e17a7bf905ef --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcerequests.go @@ -0,0 +1,10 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ResourceRequests struct { + Cpu float64 `json:"cpu"` + Gpu *GpuResource `json:"gpu,omitempty"` + MemoryInGB float64 `json:"memoryInGB"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcerequirements.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcerequirements.go new file mode 100644 index 000000000000..cdc6bfd4aaf7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_resourcerequirements.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ResourceRequirements struct { + Limits *ResourceLimits `json:"limits,omitempty"` + Requests ResourceRequests `json:"requests"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usage.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usage.go new file mode 100644 index 000000000000..2c30a75dee3c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usage.go @@ -0,0 +1,11 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Usage struct { + CurrentValue *int64 `json:"currentValue,omitempty"` + Limit *int64 `json:"limit,omitempty"` + Name *UsageName `json:"name,omitempty"` + Unit *string `json:"unit,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usagelistresult.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usagelistresult.go new file mode 100644 index 000000000000..a473f08b4e78 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usagelistresult.go @@ -0,0 +1,8 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UsageListResult struct { + Value *[]Usage `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usagename.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usagename.go new file mode 100644 index 000000000000..eba1c36c68b2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_usagename.go @@ -0,0 +1,9 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UsageName struct { + LocalizedValue *string `json:"localizedValue,omitempty"` + Value *string `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_volume.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_volume.go new file mode 100644 index 000000000000..ea997d3e01f0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_volume.go @@ -0,0 +1,12 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Volume struct { + AzureFile *AzureFileVolume `json:"azureFile,omitempty"` + EmptyDir *interface{} `json:"emptyDir,omitempty"` + GitRepo *GitRepoVolume `json:"gitRepo,omitempty"` + Name string `json:"name"` + Secret *map[string]string `json:"secret,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_volumemount.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_volumemount.go new file mode 100644 index 000000000000..71d7148c1bf8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/model_volumemount.go @@ -0,0 +1,10 @@ +package containerinstance + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumeMount struct { + MountPath string `json:"mountPath"` + Name string `json:"name"` + ReadOnly *bool `json:"readOnly,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/predicates.go new file mode 100644 index 000000000000..02f895d68f52 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/predicates.go @@ -0,0 +1,80 @@ +package containerinstance + +type CachedImagesOperationPredicate struct { + Image *string + OsType *string +} + +func (p CachedImagesOperationPredicate) Matches(input CachedImages) bool { + + if p.Image != nil && *p.Image != input.Image { + return false + } + + if p.OsType != nil && *p.OsType != input.OsType { + return false + } + + return true +} + +type CapabilitiesOperationPredicate struct { + Gpu *string + IpAddressType *string + Location *string + OsType *string + ResourceType *string +} + +func (p CapabilitiesOperationPredicate) Matches(input Capabilities) bool { + + if p.Gpu != nil && (input.Gpu == nil && *p.Gpu != *input.Gpu) { + return false + } + + if p.IpAddressType != nil && (input.IpAddressType == nil && *p.IpAddressType != *input.IpAddressType) { + return false + } + + if p.Location != nil && (input.Location == nil && *p.Location != *input.Location) { + return false + } + + if p.OsType != nil && (input.OsType == nil && *p.OsType != *input.OsType) { + return false + } + + if p.ResourceType != nil && (input.ResourceType == nil && *p.ResourceType != *input.ResourceType) { + return false + } + + return true +} + +type ContainerGroupOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p ContainerGroupOperationPredicate) Matches(input ContainerGroup) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && (input.Location == nil && *p.Location != *input.Location) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/version.go new file mode 100644 index 000000000000..1f296067049e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance/version.go @@ -0,0 +1,12 @@ +package containerinstance + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-03-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/containerinstance/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/README.md new file mode 100644 index 000000000000..9800a56c38b1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/README.md @@ -0,0 +1,116 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces` Documentation + +The `workspaces` SDK allows for interaction with the Azure Resource Manager Service `databricks` (API Version `2021-04-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces" +``` + + +### Client Initialization + +```go +client := workspaces.NewWorkspacesClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `WorkspacesClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := workspaces.NewWorkspaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "workspaceValue") + +payload := workspaces.Workspace{ + // ... +} + + +if err := client.CreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `WorkspacesClient.Delete` + +```go +ctx := context.TODO() +id := workspaces.NewWorkspaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "workspaceValue") + +if err := client.DeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `WorkspacesClient.Get` + +```go +ctx := context.TODO() +id := workspaces.NewWorkspaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "workspaceValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `WorkspacesClient.ListByResourceGroup` + +```go +ctx := context.TODO() +id := workspaces.NewResourceGroupID() + +// alternatively `client.ListByResourceGroup(ctx, id)` can be used to do batched pagination +items, err := client.ListByResourceGroupComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `WorkspacesClient.ListBySubscription` + +```go +ctx := context.TODO() +id := workspaces.NewSubscriptionID() + +// alternatively `client.ListBySubscription(ctx, id)` can be used to do batched pagination +items, err := client.ListBySubscriptionComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `WorkspacesClient.Update` + +```go +ctx := context.TODO() +id := workspaces.NewWorkspaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "workspaceValue") + +payload := workspaces.WorkspaceUpdate{ + // ... +} + + +if err := client.UpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/client.go new file mode 100644 index 000000000000..02d022fa85e3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/client.go @@ -0,0 +1,18 @@ +package workspaces + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspacesClient struct { + Client autorest.Client + baseUri string +} + +func NewWorkspacesClientWithBaseURI(endpoint string) WorkspacesClient { + return WorkspacesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/constants.go new file mode 100644 index 000000000000..130ad6fbf3d5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/constants.go @@ -0,0 +1,275 @@ +package workspaces + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomParameterType string + +const ( + CustomParameterTypeBool CustomParameterType = "Bool" + CustomParameterTypeObject CustomParameterType = "Object" + CustomParameterTypeString CustomParameterType = "String" +) + +func PossibleValuesForCustomParameterType() []string { + return []string{ + string(CustomParameterTypeBool), + string(CustomParameterTypeObject), + string(CustomParameterTypeString), + } +} + +func parseCustomParameterType(input string) (*CustomParameterType, error) { + vals := map[string]CustomParameterType{ + "bool": CustomParameterTypeBool, + "object": CustomParameterTypeObject, + "string": CustomParameterTypeString, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := CustomParameterType(input) + return &out, nil +} + +type EncryptionKeySource string + +const ( + EncryptionKeySourceMicrosoftPointKeyvault EncryptionKeySource = "Microsoft.Keyvault" +) + +func PossibleValuesForEncryptionKeySource() []string { + return []string{ + string(EncryptionKeySourceMicrosoftPointKeyvault), + } +} + +func parseEncryptionKeySource(input string) (*EncryptionKeySource, error) { + vals := map[string]EncryptionKeySource{ + "microsoft.keyvault": EncryptionKeySourceMicrosoftPointKeyvault, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EncryptionKeySource(input) + return &out, nil +} + +type KeySource string + +const ( + KeySourceDefault KeySource = "Default" + KeySourceMicrosoftPointKeyvault KeySource = "Microsoft.Keyvault" +) + +func PossibleValuesForKeySource() []string { + return []string{ + string(KeySourceDefault), + string(KeySourceMicrosoftPointKeyvault), + } +} + +func parseKeySource(input string) (*KeySource, error) { + vals := map[string]KeySource{ + "default": KeySourceDefault, + "microsoft.keyvault": KeySourceMicrosoftPointKeyvault, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeySource(input) + return &out, nil +} + +type PrivateEndpointConnectionProvisioningState string + +const ( + PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" + PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" + PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" + PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" + PrivateEndpointConnectionProvisioningStateUpdating PrivateEndpointConnectionProvisioningState = "Updating" +) + +func PossibleValuesForPrivateEndpointConnectionProvisioningState() []string { + return []string{ + string(PrivateEndpointConnectionProvisioningStateCreating), + string(PrivateEndpointConnectionProvisioningStateDeleting), + string(PrivateEndpointConnectionProvisioningStateFailed), + string(PrivateEndpointConnectionProvisioningStateSucceeded), + string(PrivateEndpointConnectionProvisioningStateUpdating), + } +} + +func parsePrivateEndpointConnectionProvisioningState(input string) (*PrivateEndpointConnectionProvisioningState, error) { + vals := map[string]PrivateEndpointConnectionProvisioningState{ + "creating": PrivateEndpointConnectionProvisioningStateCreating, + "deleting": PrivateEndpointConnectionProvisioningStateDeleting, + "failed": PrivateEndpointConnectionProvisioningStateFailed, + "succeeded": PrivateEndpointConnectionProvisioningStateSucceeded, + "updating": PrivateEndpointConnectionProvisioningStateUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := PrivateEndpointConnectionProvisioningState(input) + return &out, nil +} + +type PrivateLinkServiceConnectionStatus string + +const ( + PrivateLinkServiceConnectionStatusApproved PrivateLinkServiceConnectionStatus = "Approved" + PrivateLinkServiceConnectionStatusDisconnected PrivateLinkServiceConnectionStatus = "Disconnected" + PrivateLinkServiceConnectionStatusPending PrivateLinkServiceConnectionStatus = "Pending" + PrivateLinkServiceConnectionStatusRejected PrivateLinkServiceConnectionStatus = "Rejected" +) + +func PossibleValuesForPrivateLinkServiceConnectionStatus() []string { + return []string{ + string(PrivateLinkServiceConnectionStatusApproved), + string(PrivateLinkServiceConnectionStatusDisconnected), + string(PrivateLinkServiceConnectionStatusPending), + string(PrivateLinkServiceConnectionStatusRejected), + } +} + +func parsePrivateLinkServiceConnectionStatus(input string) (*PrivateLinkServiceConnectionStatus, error) { + vals := map[string]PrivateLinkServiceConnectionStatus{ + "approved": PrivateLinkServiceConnectionStatusApproved, + "disconnected": PrivateLinkServiceConnectionStatusDisconnected, + "pending": PrivateLinkServiceConnectionStatusPending, + "rejected": PrivateLinkServiceConnectionStatusRejected, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := PrivateLinkServiceConnectionStatus(input) + return &out, nil +} + +type ProvisioningState string + +const ( + ProvisioningStateAccepted ProvisioningState = "Accepted" + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateCreated ProvisioningState = "Created" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateDeleted ProvisioningState = "Deleted" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateReady ProvisioningState = "Ready" + ProvisioningStateRunning ProvisioningState = "Running" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +func PossibleValuesForProvisioningState() []string { + return []string{ + string(ProvisioningStateAccepted), + string(ProvisioningStateCanceled), + string(ProvisioningStateCreated), + string(ProvisioningStateCreating), + string(ProvisioningStateDeleted), + string(ProvisioningStateDeleting), + string(ProvisioningStateFailed), + string(ProvisioningStateReady), + string(ProvisioningStateRunning), + string(ProvisioningStateSucceeded), + string(ProvisioningStateUpdating), + } +} + +func parseProvisioningState(input string) (*ProvisioningState, error) { + vals := map[string]ProvisioningState{ + "accepted": ProvisioningStateAccepted, + "canceled": ProvisioningStateCanceled, + "created": ProvisioningStateCreated, + "creating": ProvisioningStateCreating, + "deleted": ProvisioningStateDeleted, + "deleting": ProvisioningStateDeleting, + "failed": ProvisioningStateFailed, + "ready": ProvisioningStateReady, + "running": ProvisioningStateRunning, + "succeeded": ProvisioningStateSucceeded, + "updating": ProvisioningStateUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ProvisioningState(input) + return &out, nil +} + +type PublicNetworkAccess string + +const ( + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +func PossibleValuesForPublicNetworkAccess() []string { + return []string{ + string(PublicNetworkAccessDisabled), + string(PublicNetworkAccessEnabled), + } +} + +func parsePublicNetworkAccess(input string) (*PublicNetworkAccess, error) { + vals := map[string]PublicNetworkAccess{ + "disabled": PublicNetworkAccessDisabled, + "enabled": PublicNetworkAccessEnabled, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := PublicNetworkAccess(input) + return &out, nil +} + +type RequiredNsgRules string + +const ( + RequiredNsgRulesAllRules RequiredNsgRules = "AllRules" + RequiredNsgRulesNoAzureDatabricksRules RequiredNsgRules = "NoAzureDatabricksRules" + RequiredNsgRulesNoAzureServiceRules RequiredNsgRules = "NoAzureServiceRules" +) + +func PossibleValuesForRequiredNsgRules() []string { + return []string{ + string(RequiredNsgRulesAllRules), + string(RequiredNsgRulesNoAzureDatabricksRules), + string(RequiredNsgRulesNoAzureServiceRules), + } +} + +func parseRequiredNsgRules(input string) (*RequiredNsgRules, error) { + vals := map[string]RequiredNsgRules{ + "allrules": RequiredNsgRulesAllRules, + "noazuredatabricksrules": RequiredNsgRulesNoAzureDatabricksRules, + "noazureservicerules": RequiredNsgRulesNoAzureServiceRules, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := RequiredNsgRules(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/id_workspace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/id_workspace.go new file mode 100644 index 000000000000..7225328c81aa --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/id_workspace.go @@ -0,0 +1,124 @@ +package workspaces + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = WorkspaceId{} + +// WorkspaceId is a struct representing the Resource ID for a Workspace +type WorkspaceId struct { + SubscriptionId string + ResourceGroupName string + WorkspaceName string +} + +// NewWorkspaceID returns a new WorkspaceId struct +func NewWorkspaceID(subscriptionId string, resourceGroupName string, workspaceName string) WorkspaceId { + return WorkspaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + WorkspaceName: workspaceName, + } +} + +// ParseWorkspaceID parses 'input' into a WorkspaceId +func ParseWorkspaceID(input string) (*WorkspaceId, error) { + parser := resourceids.NewParserFromResourceIdType(WorkspaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := WorkspaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.WorkspaceName, ok = parsed.Parsed["workspaceName"]; !ok { + return nil, fmt.Errorf("the segment 'workspaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseWorkspaceIDInsensitively parses 'input' case-insensitively into a WorkspaceId +// note: this method should only be used for API response data and not user input +func ParseWorkspaceIDInsensitively(input string) (*WorkspaceId, error) { + parser := resourceids.NewParserFromResourceIdType(WorkspaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := WorkspaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.WorkspaceName, ok = parsed.Parsed["workspaceName"]; !ok { + return nil, fmt.Errorf("the segment 'workspaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateWorkspaceID checks that 'input' can be parsed as a Workspace ID +func ValidateWorkspaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseWorkspaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Workspace ID +func (id WorkspaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Databricks/workspaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.WorkspaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Workspace ID +func (id WorkspaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftDatabricks", "Microsoft.Databricks", "Microsoft.Databricks"), + resourceids.StaticSegment("staticWorkspaces", "workspaces", "workspaces"), + resourceids.UserSpecifiedSegment("workspaceName", "workspaceValue"), + } +} + +// String returns a human-readable description of this Workspace ID +func (id WorkspaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Workspace Name: %q", id.WorkspaceName), + } + return fmt.Sprintf("Workspace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_createorupdate_autorest.go new file mode 100644 index 000000000000..7e742b0f05f9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_createorupdate_autorest.go @@ -0,0 +1,79 @@ +package workspaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CreateOrUpdate ... +func (c WorkspacesClient) CreateOrUpdate(ctx context.Context, id WorkspaceId, input Workspace) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CreateOrUpdateThenPoll performs CreateOrUpdate then polls until it's completed +func (c WorkspacesClient) CreateOrUpdateThenPoll(ctx context.Context, id WorkspaceId, input Workspace) error { + result, err := c.CreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing CreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c WorkspacesClient) preparerForCreateOrUpdate(ctx context.Context, id WorkspaceId, input Workspace) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCreateOrUpdate sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c WorkspacesClient) senderForCreateOrUpdate(ctx context.Context, req *http.Request) (future CreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_delete_autorest.go new file mode 100644 index 000000000000..3475fce1278b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_delete_autorest.go @@ -0,0 +1,78 @@ +package workspaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Delete ... +func (c WorkspacesClient) Delete(ctx context.Context, id WorkspaceId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = c.senderForDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// DeleteThenPoll performs Delete then polls until it's completed +func (c WorkspacesClient) DeleteThenPoll(ctx context.Context, id WorkspaceId) error { + result, err := c.Delete(ctx, id) + if err != nil { + return fmt.Errorf("performing Delete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Delete: %+v", err) + } + + return nil +} + +// preparerForDelete prepares the Delete request. +func (c WorkspacesClient) preparerForDelete(ctx context.Context, id WorkspaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForDelete sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (c WorkspacesClient) senderForDelete(ctx context.Context, req *http.Request) (future DeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_get_autorest.go new file mode 100644 index 000000000000..61796323becc --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_get_autorest.go @@ -0,0 +1,67 @@ +package workspaces + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *Workspace +} + +// Get ... +func (c WorkspacesClient) Get(ctx context.Context, id WorkspaceId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c WorkspacesClient) preparerForGet(ctx context.Context, id WorkspaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c WorkspacesClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_listbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_listbyresourcegroup_autorest.go new file mode 100644 index 000000000000..733e929d2475 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_listbyresourcegroup_autorest.go @@ -0,0 +1,187 @@ +package workspaces + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]Workspace + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByResourceGroupOperationResponse, error) +} + +type ListByResourceGroupCompleteResult struct { + Items []Workspace +} + +func (r ListByResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ListByResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListByResourceGroup ... +func (c WorkspacesClient) ListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByResourceGroupComplete retrieves all of the results into a single object +func (c WorkspacesClient) ListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ListByResourceGroupCompleteResult, error) { + return c.ListByResourceGroupCompleteMatchingPredicate(ctx, id, WorkspaceOperationPredicate{}) +} + +// ListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c WorkspacesClient) ListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate WorkspaceOperationPredicate) (resp ListByResourceGroupCompleteResult, err error) { + items := make([]Workspace, 0) + + page, err := c.ListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByResourceGroup prepares the ListByResourceGroup request. +func (c WorkspacesClient) preparerForListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.Databricks/workspaces", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByResourceGroupWithNextLink prepares the ListByResourceGroup request with the given nextLink token. +func (c WorkspacesClient) preparerForListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByResourceGroup handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (c WorkspacesClient) responderForListByResourceGroup(resp *http.Response) (result ListByResourceGroupOperationResponse, err error) { + type page struct { + Values []Workspace `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_listbysubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_listbysubscription_autorest.go new file mode 100644 index 000000000000..335454f1e1fb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_listbysubscription_autorest.go @@ -0,0 +1,187 @@ +package workspaces + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListBySubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *[]Workspace + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListBySubscriptionOperationResponse, error) +} + +type ListBySubscriptionCompleteResult struct { + Items []Workspace +} + +func (r ListBySubscriptionOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListBySubscriptionOperationResponse) LoadMore(ctx context.Context) (resp ListBySubscriptionOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListBySubscription ... +func (c WorkspacesClient) ListBySubscription(ctx context.Context, id commonids.SubscriptionId) (resp ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscription(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListBySubscription", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListBySubscription(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListBySubscription", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListBySubscriptionComplete retrieves all of the results into a single object +func (c WorkspacesClient) ListBySubscriptionComplete(ctx context.Context, id commonids.SubscriptionId) (ListBySubscriptionCompleteResult, error) { + return c.ListBySubscriptionCompleteMatchingPredicate(ctx, id, WorkspaceOperationPredicate{}) +} + +// ListBySubscriptionCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c WorkspacesClient) ListBySubscriptionCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate WorkspaceOperationPredicate) (resp ListBySubscriptionCompleteResult, err error) { + items := make([]Workspace, 0) + + page, err := c.ListBySubscription(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListBySubscriptionCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListBySubscription prepares the ListBySubscription request. +func (c WorkspacesClient) preparerForListBySubscription(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.Databricks/workspaces", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListBySubscriptionWithNextLink prepares the ListBySubscription request with the given nextLink token. +func (c WorkspacesClient) preparerForListBySubscriptionWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListBySubscription handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (c WorkspacesClient) responderForListBySubscription(resp *http.Response) (result ListBySubscriptionOperationResponse, err error) { + type page struct { + Values []Workspace `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscriptionWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListBySubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListBySubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "ListBySubscription", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_update_autorest.go new file mode 100644 index 000000000000..1bff4b670d16 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/method_update_autorest.go @@ -0,0 +1,79 @@ +package workspaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Update ... +func (c WorkspacesClient) Update(ctx context.Context, id WorkspaceId, input WorkspaceUpdate) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "Update", nil, "Failure preparing request") + return + } + + result, err = c.senderForUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "workspaces.WorkspacesClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// UpdateThenPoll performs Update then polls until it's completed +func (c WorkspacesClient) UpdateThenPoll(ctx context.Context, id WorkspaceId, input WorkspaceUpdate) error { + result, err := c.Update(ctx, id, input) + if err != nil { + return fmt.Errorf("performing Update: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Update: %+v", err) + } + + return nil +} + +// preparerForUpdate prepares the Update request. +func (c WorkspacesClient) preparerForUpdate(ctx context.Context, id WorkspaceId, input WorkspaceUpdate) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForUpdate sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (c WorkspacesClient) senderForUpdate(ctx context.Context, req *http.Request) (future UpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_createdby.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_createdby.go new file mode 100644 index 000000000000..fa06a35a393b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_createdby.go @@ -0,0 +1,10 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreatedBy struct { + ApplicationId *string `json:"applicationId,omitempty"` + Oid *string `json:"oid,omitempty"` + Puid *string `json:"puid,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryption.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryption.go new file mode 100644 index 000000000000..3d37fddd7e5f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryption.go @@ -0,0 +1,11 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Encryption struct { + KeyName *string `json:"KeyName,omitempty"` + KeySource *KeySource `json:"keySource,omitempty"` + Keyvaulturi *string `json:"keyvaulturi,omitempty"` + Keyversion *string `json:"keyversion,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionentitiesdefinition.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionentitiesdefinition.go new file mode 100644 index 000000000000..37c7a8fdbfb6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionentitiesdefinition.go @@ -0,0 +1,8 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EncryptionEntitiesDefinition struct { + ManagedServices *EncryptionV2 `json:"managedServices,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionv2.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionv2.go new file mode 100644 index 000000000000..1569f86ef50e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionv2.go @@ -0,0 +1,9 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EncryptionV2 struct { + KeySource EncryptionKeySource `json:"keySource"` + KeyVaultProperties *EncryptionV2KeyVaultProperties `json:"keyVaultProperties,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionv2keyvaultproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionv2keyvaultproperties.go new file mode 100644 index 000000000000..86adbd8c6a54 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_encryptionv2keyvaultproperties.go @@ -0,0 +1,10 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EncryptionV2KeyVaultProperties struct { + KeyName string `json:"keyName"` + KeyVaultUri string `json:"keyVaultUri"` + KeyVersion string `json:"keyVersion"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_managedidentityconfiguration.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_managedidentityconfiguration.go new file mode 100644 index 000000000000..aeea7f937c85 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_managedidentityconfiguration.go @@ -0,0 +1,10 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ManagedIdentityConfiguration struct { + PrincipalId *string `json:"principalId,omitempty"` + TenantId *string `json:"tenantId,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpoint.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpoint.go new file mode 100644 index 000000000000..9f81ff8b836c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpoint.go @@ -0,0 +1,8 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpoint struct { + Id *string `json:"id,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpointconnection.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpointconnection.go new file mode 100644 index 000000000000..aee2db4a4b3c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpointconnection.go @@ -0,0 +1,11 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnection struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties PrivateEndpointConnectionProperties `json:"properties"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpointconnectionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpointconnectionproperties.go new file mode 100644 index 000000000000..34f25f6a480a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privateendpointconnectionproperties.go @@ -0,0 +1,10 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionProperties struct { + PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` + PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState"` + ProvisioningState *PrivateEndpointConnectionProvisioningState `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privatelinkserviceconnectionstate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privatelinkserviceconnectionstate.go new file mode 100644 index 000000000000..bdea419278ee --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_privatelinkserviceconnectionstate.go @@ -0,0 +1,10 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateLinkServiceConnectionState struct { + ActionRequired *string `json:"actionRequired,omitempty"` + Description *string `json:"description,omitempty"` + Status PrivateLinkServiceConnectionStatus `json:"status"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_sku.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_sku.go new file mode 100644 index 000000000000..e5316e27b309 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_sku.go @@ -0,0 +1,9 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Sku struct { + Name string `json:"name"` + Tier *string `json:"tier,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspace.go new file mode 100644 index 000000000000..2a205ac19021 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspace.go @@ -0,0 +1,19 @@ +package workspaces + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Workspace struct { + Id *string `json:"id,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties WorkspaceProperties `json:"properties"` + Sku *Sku `json:"sku,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustombooleanparameter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustombooleanparameter.go new file mode 100644 index 000000000000..a2e256bd2f0d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustombooleanparameter.go @@ -0,0 +1,9 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspaceCustomBooleanParameter struct { + Type *CustomParameterType `json:"type,omitempty"` + Value bool `json:"value"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomobjectparameter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomobjectparameter.go new file mode 100644 index 000000000000..85cfe0983914 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomobjectparameter.go @@ -0,0 +1,9 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspaceCustomObjectParameter struct { + Type *CustomParameterType `json:"type,omitempty"` + Value interface{} `json:"value"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomparameters.go new file mode 100644 index 000000000000..99913cfbef11 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomparameters.go @@ -0,0 +1,23 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspaceCustomParameters struct { + AmlWorkspaceId *WorkspaceCustomStringParameter `json:"amlWorkspaceId,omitempty"` + CustomPrivateSubnetName *WorkspaceCustomStringParameter `json:"customPrivateSubnetName,omitempty"` + CustomPublicSubnetName *WorkspaceCustomStringParameter `json:"customPublicSubnetName,omitempty"` + CustomVirtualNetworkId *WorkspaceCustomStringParameter `json:"customVirtualNetworkId,omitempty"` + EnableNoPublicIp *WorkspaceCustomBooleanParameter `json:"enableNoPublicIp,omitempty"` + Encryption *WorkspaceEncryptionParameter `json:"encryption,omitempty"` + LoadBalancerBackendPoolName *WorkspaceCustomStringParameter `json:"loadBalancerBackendPoolName,omitempty"` + LoadBalancerId *WorkspaceCustomStringParameter `json:"loadBalancerId,omitempty"` + NatGatewayName *WorkspaceCustomStringParameter `json:"natGatewayName,omitempty"` + PrepareEncryption *WorkspaceCustomBooleanParameter `json:"prepareEncryption,omitempty"` + PublicIpName *WorkspaceCustomStringParameter `json:"publicIpName,omitempty"` + RequireInfrastructureEncryption *WorkspaceCustomBooleanParameter `json:"requireInfrastructureEncryption,omitempty"` + ResourceTags *WorkspaceCustomObjectParameter `json:"resourceTags,omitempty"` + StorageAccountName *WorkspaceCustomStringParameter `json:"storageAccountName,omitempty"` + StorageAccountSkuName *WorkspaceCustomStringParameter `json:"storageAccountSkuName,omitempty"` + VnetAddressPrefix *WorkspaceCustomStringParameter `json:"vnetAddressPrefix,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomstringparameter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomstringparameter.go new file mode 100644 index 000000000000..c983ffae968f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacecustomstringparameter.go @@ -0,0 +1,9 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspaceCustomStringParameter struct { + Type *CustomParameterType `json:"type,omitempty"` + Value string `json:"value"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceencryptionparameter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceencryptionparameter.go new file mode 100644 index 000000000000..551ca748c04c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceencryptionparameter.go @@ -0,0 +1,9 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspaceEncryptionParameter struct { + Type *CustomParameterType `json:"type,omitempty"` + Value *Encryption `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceproperties.go new file mode 100644 index 000000000000..1a968a53acb3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceproperties.go @@ -0,0 +1,40 @@ +package workspaces + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspaceProperties struct { + Authorizations *[]WorkspaceProviderAuthorization `json:"authorizations,omitempty"` + CreatedBy *CreatedBy `json:"createdBy,omitempty"` + CreatedDateTime *string `json:"createdDateTime,omitempty"` + Encryption *WorkspacePropertiesEncryption `json:"encryption,omitempty"` + ManagedResourceGroupId string `json:"managedResourceGroupId"` + Parameters *WorkspaceCustomParameters `json:"parameters,omitempty"` + PrivateEndpointConnections *[]PrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` + PublicNetworkAccess *PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + RequiredNsgRules *RequiredNsgRules `json:"requiredNsgRules,omitempty"` + StorageAccountIdentity *ManagedIdentityConfiguration `json:"storageAccountIdentity,omitempty"` + UiDefinitionUri *string `json:"uiDefinitionUri,omitempty"` + UpdatedBy *CreatedBy `json:"updatedBy,omitempty"` + WorkspaceId *string `json:"workspaceId,omitempty"` + WorkspaceUrl *string `json:"workspaceUrl,omitempty"` +} + +func (o *WorkspaceProperties) GetCreatedDateTimeAsTime() (*time.Time, error) { + if o.CreatedDateTime == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedDateTime, "2006-01-02T15:04:05Z07:00") +} + +func (o *WorkspaceProperties) SetCreatedDateTimeAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedDateTime = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacepropertiesencryption.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacepropertiesencryption.go new file mode 100644 index 000000000000..ddb3625ee748 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspacepropertiesencryption.go @@ -0,0 +1,8 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspacePropertiesEncryption struct { + Entities EncryptionEntitiesDefinition `json:"entities"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceproviderauthorization.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceproviderauthorization.go new file mode 100644 index 000000000000..98d6f732126c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceproviderauthorization.go @@ -0,0 +1,9 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspaceProviderAuthorization struct { + PrincipalId string `json:"principalId"` + RoleDefinitionId string `json:"roleDefinitionId"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceupdate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceupdate.go new file mode 100644 index 000000000000..079a43eda11b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/model_workspaceupdate.go @@ -0,0 +1,8 @@ +package workspaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WorkspaceUpdate struct { + Tags *map[string]string `json:"tags,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/predicates.go new file mode 100644 index 000000000000..aed808b5b33d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/predicates.go @@ -0,0 +1,29 @@ +package workspaces + +type WorkspaceOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p WorkspaceOperationPredicate) Matches(input Workspace) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/version.go new file mode 100644 index 000000000000..c253dde0243d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces/version.go @@ -0,0 +1,12 @@ +package workspaces + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-04-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/workspaces/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/README.md new file mode 100644 index 000000000000..1234b4af2a6d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/README.md @@ -0,0 +1,95 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs` Documentation + +The `authorizationruleseventhubs` SDK allows for interaction with the Azure Resource Manager Service `eventhub` (API Version `2017-04-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs" +``` + + +### Client Initialization + +```go +client := authorizationruleseventhubs.NewAuthorizationRulesEventHubsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `AuthorizationRulesEventHubsClient.EventHubsCreateOrUpdateAuthorizationRule` + +```go +ctx := context.TODO() +id := authorizationruleseventhubs.NewEventhubAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue", "authorizationRuleValue") + +payload := authorizationruleseventhubs.AuthorizationRule{ + // ... +} + + +read, err := client.EventHubsCreateOrUpdateAuthorizationRule(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AuthorizationRulesEventHubsClient.EventHubsListAuthorizationRules` + +```go +ctx := context.TODO() +id := authorizationruleseventhubs.NewEventhubID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue") + +// alternatively `client.EventHubsListAuthorizationRules(ctx, id)` can be used to do batched pagination +items, err := client.EventHubsListAuthorizationRulesComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `AuthorizationRulesEventHubsClient.EventHubsListKeys` + +```go +ctx := context.TODO() +id := authorizationruleseventhubs.NewEventhubAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue", "authorizationRuleValue") + +read, err := client.EventHubsListKeys(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AuthorizationRulesEventHubsClient.EventHubsRegenerateKeys` + +```go +ctx := context.TODO() +id := authorizationruleseventhubs.NewEventhubAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue", "authorizationRuleValue") + +payload := authorizationruleseventhubs.RegenerateAccessKeyParameters{ + // ... +} + + +read, err := client.EventHubsRegenerateKeys(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/client.go new file mode 100644 index 000000000000..904950f0cca6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/client.go @@ -0,0 +1,18 @@ +package authorizationruleseventhubs + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AuthorizationRulesEventHubsClient struct { + Client autorest.Client + baseUri string +} + +func NewAuthorizationRulesEventHubsClientWithBaseURI(endpoint string) AuthorizationRulesEventHubsClient { + return AuthorizationRulesEventHubsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/constants.go new file mode 100644 index 000000000000..8ad03472120c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/constants.go @@ -0,0 +1,65 @@ +package authorizationruleseventhubs + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessRights string + +const ( + AccessRightsListen AccessRights = "Listen" + AccessRightsManage AccessRights = "Manage" + AccessRightsSend AccessRights = "Send" +) + +func PossibleValuesForAccessRights() []string { + return []string{ + string(AccessRightsListen), + string(AccessRightsManage), + string(AccessRightsSend), + } +} + +func parseAccessRights(input string) (*AccessRights, error) { + vals := map[string]AccessRights{ + "listen": AccessRightsListen, + "manage": AccessRightsManage, + "send": AccessRightsSend, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AccessRights(input) + return &out, nil +} + +type KeyType string + +const ( + KeyTypePrimaryKey KeyType = "PrimaryKey" + KeyTypeSecondaryKey KeyType = "SecondaryKey" +) + +func PossibleValuesForKeyType() []string { + return []string{ + string(KeyTypePrimaryKey), + string(KeyTypeSecondaryKey), + } +} + +func parseKeyType(input string) (*KeyType, error) { + vals := map[string]KeyType{ + "primarykey": KeyTypePrimaryKey, + "secondarykey": KeyTypeSecondaryKey, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeyType(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/id_eventhub.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/id_eventhub.go new file mode 100644 index 000000000000..acff04d06b07 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/id_eventhub.go @@ -0,0 +1,137 @@ +package authorizationruleseventhubs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = EventhubId{} + +// EventhubId is a struct representing the Resource ID for a Eventhub +type EventhubId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + EventHubName string +} + +// NewEventhubID returns a new EventhubId struct +func NewEventhubID(subscriptionId string, resourceGroupName string, namespaceName string, eventHubName string) EventhubId { + return EventhubId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + EventHubName: eventHubName, + } +} + +// ParseEventhubID parses 'input' into a EventhubId +func ParseEventhubID(input string) (*EventhubId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseEventhubIDInsensitively parses 'input' case-insensitively into a EventhubId +// note: this method should only be used for API response data and not user input +func ParseEventhubIDInsensitively(input string) (*EventhubId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateEventhubID checks that 'input' can be parsed as a Eventhub ID +func ValidateEventhubID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseEventhubID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Eventhub ID +func (id EventhubId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/eventhubs/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.EventHubName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Eventhub ID +func (id EventhubId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticEventhubs", "eventhubs", "eventhubs"), + resourceids.UserSpecifiedSegment("eventHubName", "eventHubValue"), + } +} + +// String returns a human-readable description of this Eventhub ID +func (id EventhubId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Event Hub Name: %q", id.EventHubName), + } + return fmt.Sprintf("Eventhub (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/id_eventhubauthorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/id_eventhubauthorizationrule.go new file mode 100644 index 000000000000..d43aaadceb3b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/id_eventhubauthorizationrule.go @@ -0,0 +1,150 @@ +package authorizationruleseventhubs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = EventhubAuthorizationRuleId{} + +// EventhubAuthorizationRuleId is a struct representing the Resource ID for a Eventhub Authorization Rule +type EventhubAuthorizationRuleId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + EventHubName string + AuthorizationRuleName string +} + +// NewEventhubAuthorizationRuleID returns a new EventhubAuthorizationRuleId struct +func NewEventhubAuthorizationRuleID(subscriptionId string, resourceGroupName string, namespaceName string, eventHubName string, authorizationRuleName string) EventhubAuthorizationRuleId { + return EventhubAuthorizationRuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + EventHubName: eventHubName, + AuthorizationRuleName: authorizationRuleName, + } +} + +// ParseEventhubAuthorizationRuleID parses 'input' into a EventhubAuthorizationRuleId +func ParseEventhubAuthorizationRuleID(input string) (*EventhubAuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubAuthorizationRuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubAuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseEventhubAuthorizationRuleIDInsensitively parses 'input' case-insensitively into a EventhubAuthorizationRuleId +// note: this method should only be used for API response data and not user input +func ParseEventhubAuthorizationRuleIDInsensitively(input string) (*EventhubAuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubAuthorizationRuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubAuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateEventhubAuthorizationRuleID checks that 'input' can be parsed as a Eventhub Authorization Rule ID +func ValidateEventhubAuthorizationRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseEventhubAuthorizationRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Eventhub Authorization Rule ID +func (id EventhubAuthorizationRuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/eventhubs/%s/authorizationRules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.EventHubName, id.AuthorizationRuleName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Eventhub Authorization Rule ID +func (id EventhubAuthorizationRuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticEventhubs", "eventhubs", "eventhubs"), + resourceids.UserSpecifiedSegment("eventHubName", "eventHubValue"), + resourceids.StaticSegment("staticAuthorizationRules", "authorizationRules", "authorizationRules"), + resourceids.UserSpecifiedSegment("authorizationRuleName", "authorizationRuleValue"), + } +} + +// String returns a human-readable description of this Eventhub Authorization Rule ID +func (id EventhubAuthorizationRuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Event Hub Name: %q", id.EventHubName), + fmt.Sprintf("Authorization Rule Name: %q", id.AuthorizationRuleName), + } + return fmt.Sprintf("Eventhub Authorization Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubscreateorupdateauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubscreateorupdateauthorizationrule_autorest.go new file mode 100644 index 000000000000..a8bc751acbc4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubscreateorupdateauthorizationrule_autorest.go @@ -0,0 +1,68 @@ +package authorizationruleseventhubs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EventHubsCreateOrUpdateAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *AuthorizationRule +} + +// EventHubsCreateOrUpdateAuthorizationRule ... +func (c AuthorizationRulesEventHubsClient) EventHubsCreateOrUpdateAuthorizationRule(ctx context.Context, id EventhubAuthorizationRuleId, input AuthorizationRule) (result EventHubsCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForEventHubsCreateOrUpdateAuthorizationRule(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsCreateOrUpdateAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForEventHubsCreateOrUpdateAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForEventHubsCreateOrUpdateAuthorizationRule prepares the EventHubsCreateOrUpdateAuthorizationRule request. +func (c AuthorizationRulesEventHubsClient) preparerForEventHubsCreateOrUpdateAuthorizationRule(ctx context.Context, id EventhubAuthorizationRuleId, input AuthorizationRule) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForEventHubsCreateOrUpdateAuthorizationRule handles the response to the EventHubsCreateOrUpdateAuthorizationRule request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesEventHubsClient) responderForEventHubsCreateOrUpdateAuthorizationRule(resp *http.Response) (result EventHubsCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubslistauthorizationrules_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubslistauthorizationrules_autorest.go new file mode 100644 index 000000000000..bbac653a1b30 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubslistauthorizationrules_autorest.go @@ -0,0 +1,186 @@ +package authorizationruleseventhubs + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EventHubsListAuthorizationRulesOperationResponse struct { + HttpResponse *http.Response + Model *[]AuthorizationRule + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (EventHubsListAuthorizationRulesOperationResponse, error) +} + +type EventHubsListAuthorizationRulesCompleteResult struct { + Items []AuthorizationRule +} + +func (r EventHubsListAuthorizationRulesOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r EventHubsListAuthorizationRulesOperationResponse) LoadMore(ctx context.Context) (resp EventHubsListAuthorizationRulesOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// EventHubsListAuthorizationRules ... +func (c AuthorizationRulesEventHubsClient) EventHubsListAuthorizationRules(ctx context.Context, id EventhubId) (resp EventHubsListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForEventHubsListAuthorizationRules(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsListAuthorizationRules", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForEventHubsListAuthorizationRules(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsListAuthorizationRules", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// EventHubsListAuthorizationRulesComplete retrieves all of the results into a single object +func (c AuthorizationRulesEventHubsClient) EventHubsListAuthorizationRulesComplete(ctx context.Context, id EventhubId) (EventHubsListAuthorizationRulesCompleteResult, error) { + return c.EventHubsListAuthorizationRulesCompleteMatchingPredicate(ctx, id, AuthorizationRuleOperationPredicate{}) +} + +// EventHubsListAuthorizationRulesCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c AuthorizationRulesEventHubsClient) EventHubsListAuthorizationRulesCompleteMatchingPredicate(ctx context.Context, id EventhubId, predicate AuthorizationRuleOperationPredicate) (resp EventHubsListAuthorizationRulesCompleteResult, err error) { + items := make([]AuthorizationRule, 0) + + page, err := c.EventHubsListAuthorizationRules(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := EventHubsListAuthorizationRulesCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForEventHubsListAuthorizationRules prepares the EventHubsListAuthorizationRules request. +func (c AuthorizationRulesEventHubsClient) preparerForEventHubsListAuthorizationRules(ctx context.Context, id EventhubId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/authorizationRules", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForEventHubsListAuthorizationRulesWithNextLink prepares the EventHubsListAuthorizationRules request with the given nextLink token. +func (c AuthorizationRulesEventHubsClient) preparerForEventHubsListAuthorizationRulesWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForEventHubsListAuthorizationRules handles the response to the EventHubsListAuthorizationRules request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesEventHubsClient) responderForEventHubsListAuthorizationRules(resp *http.Response) (result EventHubsListAuthorizationRulesOperationResponse, err error) { + type page struct { + Values []AuthorizationRule `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result EventHubsListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForEventHubsListAuthorizationRulesWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsListAuthorizationRules", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsListAuthorizationRules", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForEventHubsListAuthorizationRules(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsListAuthorizationRules", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubslistkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubslistkeys_autorest.go new file mode 100644 index 000000000000..9ac1a8ccea12 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubslistkeys_autorest.go @@ -0,0 +1,68 @@ +package authorizationruleseventhubs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EventHubsListKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// EventHubsListKeys ... +func (c AuthorizationRulesEventHubsClient) EventHubsListKeys(ctx context.Context, id EventhubAuthorizationRuleId) (result EventHubsListKeysOperationResponse, err error) { + req, err := c.preparerForEventHubsListKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsListKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsListKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForEventHubsListKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsListKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForEventHubsListKeys prepares the EventHubsListKeys request. +func (c AuthorizationRulesEventHubsClient) preparerForEventHubsListKeys(ctx context.Context, id EventhubAuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForEventHubsListKeys handles the response to the EventHubsListKeys request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesEventHubsClient) responderForEventHubsListKeys(resp *http.Response) (result EventHubsListKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubsregeneratekeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubsregeneratekeys_autorest.go new file mode 100644 index 000000000000..fc21519e08cf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/method_eventhubsregeneratekeys_autorest.go @@ -0,0 +1,69 @@ +package authorizationruleseventhubs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EventHubsRegenerateKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// EventHubsRegenerateKeys ... +func (c AuthorizationRulesEventHubsClient) EventHubsRegenerateKeys(ctx context.Context, id EventhubAuthorizationRuleId, input RegenerateAccessKeyParameters) (result EventHubsRegenerateKeysOperationResponse, err error) { + req, err := c.preparerForEventHubsRegenerateKeys(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsRegenerateKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsRegenerateKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForEventHubsRegenerateKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationruleseventhubs.AuthorizationRulesEventHubsClient", "EventHubsRegenerateKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForEventHubsRegenerateKeys prepares the EventHubsRegenerateKeys request. +func (c AuthorizationRulesEventHubsClient) preparerForEventHubsRegenerateKeys(ctx context.Context, id EventhubAuthorizationRuleId, input RegenerateAccessKeyParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/regenerateKeys", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForEventHubsRegenerateKeys handles the response to the EventHubsRegenerateKeys request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesEventHubsClient) responderForEventHubsRegenerateKeys(resp *http.Response) (result EventHubsRegenerateKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_accesskeys.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_accesskeys.go new file mode 100644 index 000000000000..fc22fc746d31 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_accesskeys.go @@ -0,0 +1,14 @@ +package authorizationruleseventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessKeys struct { + AliasPrimaryConnectionString *string `json:"aliasPrimaryConnectionString,omitempty"` + AliasSecondaryConnectionString *string `json:"aliasSecondaryConnectionString,omitempty"` + KeyName *string `json:"keyName,omitempty"` + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + PrimaryKey *string `json:"primaryKey,omitempty"` + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + SecondaryKey *string `json:"secondaryKey,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_authorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_authorizationrule.go new file mode 100644 index 000000000000..107de77f991e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_authorizationrule.go @@ -0,0 +1,11 @@ +package authorizationruleseventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AuthorizationRule struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *AuthorizationRuleProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_authorizationruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_authorizationruleproperties.go new file mode 100644 index 000000000000..afbfae90d041 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_authorizationruleproperties.go @@ -0,0 +1,8 @@ +package authorizationruleseventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AuthorizationRuleProperties struct { + Rights []AccessRights `json:"rights"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_regenerateaccesskeyparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_regenerateaccesskeyparameters.go new file mode 100644 index 000000000000..0e6cffdfe71d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/model_regenerateaccesskeyparameters.go @@ -0,0 +1,9 @@ +package authorizationruleseventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateAccessKeyParameters struct { + Key *string `json:"key,omitempty"` + KeyType KeyType `json:"keyType"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/predicates.go new file mode 100644 index 000000000000..9d742fece6e4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/predicates.go @@ -0,0 +1,24 @@ +package authorizationruleseventhubs + +type AuthorizationRuleOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p AuthorizationRuleOperationPredicate) Matches(input AuthorizationRule) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/version.go new file mode 100644 index 000000000000..ea04279373cc --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs/version.go @@ -0,0 +1,12 @@ +package authorizationruleseventhubs + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2017-04-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/authorizationruleseventhubs/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/README.md new file mode 100644 index 000000000000..e5b039013b5b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/README.md @@ -0,0 +1,127 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces` Documentation + +The `authorizationrulesnamespaces` SDK allows for interaction with the Azure Resource Manager Service `eventhub` (API Version `2017-04-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces" +``` + + +### Client Initialization + +```go +client := authorizationrulesnamespaces.NewAuthorizationRulesNamespacesClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `AuthorizationRulesNamespacesClient.NamespacesCreateOrUpdateAuthorizationRule` + +```go +ctx := context.TODO() +id := authorizationrulesnamespaces.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +payload := authorizationrulesnamespaces.AuthorizationRule{ + // ... +} + + +read, err := client.NamespacesCreateOrUpdateAuthorizationRule(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AuthorizationRulesNamespacesClient.NamespacesDeleteAuthorizationRule` + +```go +ctx := context.TODO() +id := authorizationrulesnamespaces.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +read, err := client.NamespacesDeleteAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AuthorizationRulesNamespacesClient.NamespacesGetAuthorizationRule` + +```go +ctx := context.TODO() +id := authorizationrulesnamespaces.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +read, err := client.NamespacesGetAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AuthorizationRulesNamespacesClient.NamespacesListAuthorizationRules` + +```go +ctx := context.TODO() +id := authorizationrulesnamespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +// alternatively `client.NamespacesListAuthorizationRules(ctx, id)` can be used to do batched pagination +items, err := client.NamespacesListAuthorizationRulesComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `AuthorizationRulesNamespacesClient.NamespacesListKeys` + +```go +ctx := context.TODO() +id := authorizationrulesnamespaces.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +read, err := client.NamespacesListKeys(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `AuthorizationRulesNamespacesClient.NamespacesRegenerateKeys` + +```go +ctx := context.TODO() +id := authorizationrulesnamespaces.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +payload := authorizationrulesnamespaces.RegenerateAccessKeyParameters{ + // ... +} + + +read, err := client.NamespacesRegenerateKeys(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/client.go new file mode 100644 index 000000000000..17b3b9be9e26 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/client.go @@ -0,0 +1,18 @@ +package authorizationrulesnamespaces + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AuthorizationRulesNamespacesClient struct { + Client autorest.Client + baseUri string +} + +func NewAuthorizationRulesNamespacesClientWithBaseURI(endpoint string) AuthorizationRulesNamespacesClient { + return AuthorizationRulesNamespacesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/constants.go new file mode 100644 index 000000000000..a4bb8d8c6770 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/constants.go @@ -0,0 +1,65 @@ +package authorizationrulesnamespaces + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessRights string + +const ( + AccessRightsListen AccessRights = "Listen" + AccessRightsManage AccessRights = "Manage" + AccessRightsSend AccessRights = "Send" +) + +func PossibleValuesForAccessRights() []string { + return []string{ + string(AccessRightsListen), + string(AccessRightsManage), + string(AccessRightsSend), + } +} + +func parseAccessRights(input string) (*AccessRights, error) { + vals := map[string]AccessRights{ + "listen": AccessRightsListen, + "manage": AccessRightsManage, + "send": AccessRightsSend, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AccessRights(input) + return &out, nil +} + +type KeyType string + +const ( + KeyTypePrimaryKey KeyType = "PrimaryKey" + KeyTypeSecondaryKey KeyType = "SecondaryKey" +) + +func PossibleValuesForKeyType() []string { + return []string{ + string(KeyTypePrimaryKey), + string(KeyTypeSecondaryKey), + } +} + +func parseKeyType(input string) (*KeyType, error) { + vals := map[string]KeyType{ + "primarykey": KeyTypePrimaryKey, + "secondarykey": KeyTypeSecondaryKey, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeyType(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/id_authorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/id_authorizationrule.go new file mode 100644 index 000000000000..742f1b02ce7f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/id_authorizationrule.go @@ -0,0 +1,137 @@ +package authorizationrulesnamespaces + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = AuthorizationRuleId{} + +// AuthorizationRuleId is a struct representing the Resource ID for a Authorization Rule +type AuthorizationRuleId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + AuthorizationRuleName string +} + +// NewAuthorizationRuleID returns a new AuthorizationRuleId struct +func NewAuthorizationRuleID(subscriptionId string, resourceGroupName string, namespaceName string, authorizationRuleName string) AuthorizationRuleId { + return AuthorizationRuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + AuthorizationRuleName: authorizationRuleName, + } +} + +// ParseAuthorizationRuleID parses 'input' into a AuthorizationRuleId +func ParseAuthorizationRuleID(input string) (*AuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(AuthorizationRuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseAuthorizationRuleIDInsensitively parses 'input' case-insensitively into a AuthorizationRuleId +// note: this method should only be used for API response data and not user input +func ParseAuthorizationRuleIDInsensitively(input string) (*AuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(AuthorizationRuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateAuthorizationRuleID checks that 'input' can be parsed as a Authorization Rule ID +func ValidateAuthorizationRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseAuthorizationRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Authorization Rule ID +func (id AuthorizationRuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/authorizationRules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.AuthorizationRuleName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Authorization Rule ID +func (id AuthorizationRuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticAuthorizationRules", "authorizationRules", "authorizationRules"), + resourceids.UserSpecifiedSegment("authorizationRuleName", "authorizationRuleValue"), + } +} + +// String returns a human-readable description of this Authorization Rule ID +func (id AuthorizationRuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Authorization Rule Name: %q", id.AuthorizationRuleName), + } + return fmt.Sprintf("Authorization Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/id_namespace.go new file mode 100644 index 000000000000..808391d46db3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/id_namespace.go @@ -0,0 +1,124 @@ +package authorizationrulesnamespaces + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacescreateorupdateauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacescreateorupdateauthorizationrule_autorest.go new file mode 100644 index 000000000000..7ddb6be8b0ef --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacescreateorupdateauthorizationrule_autorest.go @@ -0,0 +1,68 @@ +package authorizationrulesnamespaces + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesCreateOrUpdateAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *AuthorizationRule +} + +// NamespacesCreateOrUpdateAuthorizationRule ... +func (c AuthorizationRulesNamespacesClient) NamespacesCreateOrUpdateAuthorizationRule(ctx context.Context, id AuthorizationRuleId, input AuthorizationRule) (result NamespacesCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForNamespacesCreateOrUpdateAuthorizationRule(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesCreateOrUpdateAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesCreateOrUpdateAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesCreateOrUpdateAuthorizationRule prepares the NamespacesCreateOrUpdateAuthorizationRule request. +func (c AuthorizationRulesNamespacesClient) preparerForNamespacesCreateOrUpdateAuthorizationRule(ctx context.Context, id AuthorizationRuleId, input AuthorizationRule) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesCreateOrUpdateAuthorizationRule handles the response to the NamespacesCreateOrUpdateAuthorizationRule request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesNamespacesClient) responderForNamespacesCreateOrUpdateAuthorizationRule(resp *http.Response) (result NamespacesCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesdeleteauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesdeleteauthorizationrule_autorest.go new file mode 100644 index 000000000000..ae0db0df190e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesdeleteauthorizationrule_autorest.go @@ -0,0 +1,65 @@ +package authorizationrulesnamespaces + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesDeleteAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response +} + +// NamespacesDeleteAuthorizationRule ... +func (c AuthorizationRulesNamespacesClient) NamespacesDeleteAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (result NamespacesDeleteAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForNamespacesDeleteAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesDeleteAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesDeleteAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesDeleteAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesDeleteAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesDeleteAuthorizationRule prepares the NamespacesDeleteAuthorizationRule request. +func (c AuthorizationRulesNamespacesClient) preparerForNamespacesDeleteAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesDeleteAuthorizationRule handles the response to the NamespacesDeleteAuthorizationRule request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesNamespacesClient) responderForNamespacesDeleteAuthorizationRule(resp *http.Response) (result NamespacesDeleteAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesgetauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesgetauthorizationrule_autorest.go new file mode 100644 index 000000000000..185094cea903 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesgetauthorizationrule_autorest.go @@ -0,0 +1,67 @@ +package authorizationrulesnamespaces + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesGetAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *AuthorizationRule +} + +// NamespacesGetAuthorizationRule ... +func (c AuthorizationRulesNamespacesClient) NamespacesGetAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (result NamespacesGetAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForNamespacesGetAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesGetAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesGetAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesGetAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesGetAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesGetAuthorizationRule prepares the NamespacesGetAuthorizationRule request. +func (c AuthorizationRulesNamespacesClient) preparerForNamespacesGetAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesGetAuthorizationRule handles the response to the NamespacesGetAuthorizationRule request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesNamespacesClient) responderForNamespacesGetAuthorizationRule(resp *http.Response) (result NamespacesGetAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespaceslistauthorizationrules_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespaceslistauthorizationrules_autorest.go new file mode 100644 index 000000000000..8b5a84d04791 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespaceslistauthorizationrules_autorest.go @@ -0,0 +1,186 @@ +package authorizationrulesnamespaces + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesListAuthorizationRulesOperationResponse struct { + HttpResponse *http.Response + Model *[]AuthorizationRule + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (NamespacesListAuthorizationRulesOperationResponse, error) +} + +type NamespacesListAuthorizationRulesCompleteResult struct { + Items []AuthorizationRule +} + +func (r NamespacesListAuthorizationRulesOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r NamespacesListAuthorizationRulesOperationResponse) LoadMore(ctx context.Context) (resp NamespacesListAuthorizationRulesOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// NamespacesListAuthorizationRules ... +func (c AuthorizationRulesNamespacesClient) NamespacesListAuthorizationRules(ctx context.Context, id NamespaceId) (resp NamespacesListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForNamespacesListAuthorizationRules(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesListAuthorizationRules", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForNamespacesListAuthorizationRules(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesListAuthorizationRules", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// NamespacesListAuthorizationRulesComplete retrieves all of the results into a single object +func (c AuthorizationRulesNamespacesClient) NamespacesListAuthorizationRulesComplete(ctx context.Context, id NamespaceId) (NamespacesListAuthorizationRulesCompleteResult, error) { + return c.NamespacesListAuthorizationRulesCompleteMatchingPredicate(ctx, id, AuthorizationRuleOperationPredicate{}) +} + +// NamespacesListAuthorizationRulesCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c AuthorizationRulesNamespacesClient) NamespacesListAuthorizationRulesCompleteMatchingPredicate(ctx context.Context, id NamespaceId, predicate AuthorizationRuleOperationPredicate) (resp NamespacesListAuthorizationRulesCompleteResult, err error) { + items := make([]AuthorizationRule, 0) + + page, err := c.NamespacesListAuthorizationRules(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := NamespacesListAuthorizationRulesCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForNamespacesListAuthorizationRules prepares the NamespacesListAuthorizationRules request. +func (c AuthorizationRulesNamespacesClient) preparerForNamespacesListAuthorizationRules(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/authorizationRules", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForNamespacesListAuthorizationRulesWithNextLink prepares the NamespacesListAuthorizationRules request with the given nextLink token. +func (c AuthorizationRulesNamespacesClient) preparerForNamespacesListAuthorizationRulesWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesListAuthorizationRules handles the response to the NamespacesListAuthorizationRules request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesNamespacesClient) responderForNamespacesListAuthorizationRules(resp *http.Response) (result NamespacesListAuthorizationRulesOperationResponse, err error) { + type page struct { + Values []AuthorizationRule `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result NamespacesListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForNamespacesListAuthorizationRulesWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesListAuthorizationRules", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesListAuthorizationRules", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesListAuthorizationRules(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesListAuthorizationRules", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespaceslistkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespaceslistkeys_autorest.go new file mode 100644 index 000000000000..569c86d6a926 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespaceslistkeys_autorest.go @@ -0,0 +1,68 @@ +package authorizationrulesnamespaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesListKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// NamespacesListKeys ... +func (c AuthorizationRulesNamespacesClient) NamespacesListKeys(ctx context.Context, id AuthorizationRuleId) (result NamespacesListKeysOperationResponse, err error) { + req, err := c.preparerForNamespacesListKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesListKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesListKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesListKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesListKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesListKeys prepares the NamespacesListKeys request. +func (c AuthorizationRulesNamespacesClient) preparerForNamespacesListKeys(ctx context.Context, id AuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesListKeys handles the response to the NamespacesListKeys request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesNamespacesClient) responderForNamespacesListKeys(resp *http.Response) (result NamespacesListKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesregeneratekeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesregeneratekeys_autorest.go new file mode 100644 index 000000000000..b4a557f8847e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/method_namespacesregeneratekeys_autorest.go @@ -0,0 +1,69 @@ +package authorizationrulesnamespaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesRegenerateKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// NamespacesRegenerateKeys ... +func (c AuthorizationRulesNamespacesClient) NamespacesRegenerateKeys(ctx context.Context, id AuthorizationRuleId, input RegenerateAccessKeyParameters) (result NamespacesRegenerateKeysOperationResponse, err error) { + req, err := c.preparerForNamespacesRegenerateKeys(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesRegenerateKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesRegenerateKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesRegenerateKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "authorizationrulesnamespaces.AuthorizationRulesNamespacesClient", "NamespacesRegenerateKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesRegenerateKeys prepares the NamespacesRegenerateKeys request. +func (c AuthorizationRulesNamespacesClient) preparerForNamespacesRegenerateKeys(ctx context.Context, id AuthorizationRuleId, input RegenerateAccessKeyParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/regenerateKeys", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesRegenerateKeys handles the response to the NamespacesRegenerateKeys request. The method always +// closes the http.Response Body. +func (c AuthorizationRulesNamespacesClient) responderForNamespacesRegenerateKeys(resp *http.Response) (result NamespacesRegenerateKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_accesskeys.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_accesskeys.go new file mode 100644 index 000000000000..fc7768192357 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_accesskeys.go @@ -0,0 +1,14 @@ +package authorizationrulesnamespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessKeys struct { + AliasPrimaryConnectionString *string `json:"aliasPrimaryConnectionString,omitempty"` + AliasSecondaryConnectionString *string `json:"aliasSecondaryConnectionString,omitempty"` + KeyName *string `json:"keyName,omitempty"` + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + PrimaryKey *string `json:"primaryKey,omitempty"` + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + SecondaryKey *string `json:"secondaryKey,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_authorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_authorizationrule.go new file mode 100644 index 000000000000..a2c8d1f4125d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_authorizationrule.go @@ -0,0 +1,11 @@ +package authorizationrulesnamespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AuthorizationRule struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *AuthorizationRuleProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_authorizationruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_authorizationruleproperties.go new file mode 100644 index 000000000000..100fb1ca6be9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_authorizationruleproperties.go @@ -0,0 +1,8 @@ +package authorizationrulesnamespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AuthorizationRuleProperties struct { + Rights []AccessRights `json:"rights"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_regenerateaccesskeyparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_regenerateaccesskeyparameters.go new file mode 100644 index 000000000000..121a8261f31a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/model_regenerateaccesskeyparameters.go @@ -0,0 +1,9 @@ +package authorizationrulesnamespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateAccessKeyParameters struct { + Key *string `json:"key,omitempty"` + KeyType KeyType `json:"keyType"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/predicates.go new file mode 100644 index 000000000000..89f14d6def63 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/predicates.go @@ -0,0 +1,24 @@ +package authorizationrulesnamespaces + +type AuthorizationRuleOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p AuthorizationRuleOperationPredicate) Matches(input AuthorizationRule) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/version.go new file mode 100644 index 000000000000..eac47c363df9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces/version.go @@ -0,0 +1,12 @@ +package authorizationrulesnamespaces + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2017-04-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/authorizationrulesnamespaces/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/README.md new file mode 100644 index 000000000000..44a54825862b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/README.md @@ -0,0 +1,41 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs` Documentation + +The `checknameavailabilitydisasterrecoveryconfigs` SDK allows for interaction with the Azure Resource Manager Service `eventhub` (API Version `2017-04-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs" +``` + + +### Client Initialization + +```go +client := checknameavailabilitydisasterrecoveryconfigs.NewCheckNameAvailabilityDisasterRecoveryConfigsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `CheckNameAvailabilityDisasterRecoveryConfigsClient.DisasterRecoveryConfigsCheckNameAvailability` + +```go +ctx := context.TODO() +id := checknameavailabilitydisasterrecoveryconfigs.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +payload := checknameavailabilitydisasterrecoveryconfigs.CheckNameAvailabilityParameter{ + // ... +} + + +read, err := client.DisasterRecoveryConfigsCheckNameAvailability(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/client.go new file mode 100644 index 000000000000..fcec870182af --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/client.go @@ -0,0 +1,18 @@ +package checknameavailabilitydisasterrecoveryconfigs + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailabilityDisasterRecoveryConfigsClient struct { + Client autorest.Client + baseUri string +} + +func NewCheckNameAvailabilityDisasterRecoveryConfigsClientWithBaseURI(endpoint string) CheckNameAvailabilityDisasterRecoveryConfigsClient { + return CheckNameAvailabilityDisasterRecoveryConfigsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/constants.go new file mode 100644 index 000000000000..e8bcdcb6ce6f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/constants.go @@ -0,0 +1,46 @@ +package checknameavailabilitydisasterrecoveryconfigs + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UnavailableReason string + +const ( + UnavailableReasonInvalidName UnavailableReason = "InvalidName" + UnavailableReasonNameInLockdown UnavailableReason = "NameInLockdown" + UnavailableReasonNameInUse UnavailableReason = "NameInUse" + UnavailableReasonNone UnavailableReason = "None" + UnavailableReasonSubscriptionIsDisabled UnavailableReason = "SubscriptionIsDisabled" + UnavailableReasonTooManyNamespaceInCurrentSubscription UnavailableReason = "TooManyNamespaceInCurrentSubscription" +) + +func PossibleValuesForUnavailableReason() []string { + return []string{ + string(UnavailableReasonInvalidName), + string(UnavailableReasonNameInLockdown), + string(UnavailableReasonNameInUse), + string(UnavailableReasonNone), + string(UnavailableReasonSubscriptionIsDisabled), + string(UnavailableReasonTooManyNamespaceInCurrentSubscription), + } +} + +func parseUnavailableReason(input string) (*UnavailableReason, error) { + vals := map[string]UnavailableReason{ + "invalidname": UnavailableReasonInvalidName, + "nameinlockdown": UnavailableReasonNameInLockdown, + "nameinuse": UnavailableReasonNameInUse, + "none": UnavailableReasonNone, + "subscriptionisdisabled": UnavailableReasonSubscriptionIsDisabled, + "toomanynamespaceincurrentsubscription": UnavailableReasonTooManyNamespaceInCurrentSubscription, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := UnavailableReason(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/id_namespace.go new file mode 100644 index 000000000000..e9252998130e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/id_namespace.go @@ -0,0 +1,124 @@ +package checknameavailabilitydisasterrecoveryconfigs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/model_checknameavailabilityparameter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/model_checknameavailabilityparameter.go new file mode 100644 index 000000000000..b1b7b4d1ada3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/model_checknameavailabilityparameter.go @@ -0,0 +1,8 @@ +package checknameavailabilitydisasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailabilityParameter struct { + Name string `json:"name"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/model_checknameavailabilityresult.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/model_checknameavailabilityresult.go new file mode 100644 index 000000000000..37fc7df5f14b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/model_checknameavailabilityresult.go @@ -0,0 +1,10 @@ +package checknameavailabilitydisasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailabilityResult struct { + Message *string `json:"message,omitempty"` + NameAvailable *bool `json:"nameAvailable,omitempty"` + Reason *UnavailableReason `json:"reason,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/version.go new file mode 100644 index 000000000000..c33a56bea2b6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/version.go @@ -0,0 +1,12 @@ +package checknameavailabilitydisasterrecoveryconfigs + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2017-04-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/checknameavailabilitydisasterrecoveryconfigs/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/README.md new file mode 100644 index 000000000000..cef07e89238a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/README.md @@ -0,0 +1,90 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups` Documentation + +The `consumergroups` SDK allows for interaction with the Azure Resource Manager Service `eventhub` (API Version `2017-04-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups" +``` + + +### Client Initialization + +```go +client := consumergroups.NewConsumerGroupsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `ConsumerGroupsClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := consumergroups.NewConsumerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue", "consumerGroupValue") + +payload := consumergroups.ConsumerGroup{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ConsumerGroupsClient.Delete` + +```go +ctx := context.TODO() +id := consumergroups.NewConsumerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue", "consumerGroupValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ConsumerGroupsClient.Get` + +```go +ctx := context.TODO() +id := consumergroups.NewConsumerGroupID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue", "consumerGroupValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ConsumerGroupsClient.ListByEventHub` + +```go +ctx := context.TODO() +id := consumergroups.NewEventhubID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue") + +// alternatively `client.ListByEventHub(ctx, id, consumergroups.DefaultListByEventHubOperationOptions())` can be used to do batched pagination +items, err := client.ListByEventHubComplete(ctx, id, consumergroups.DefaultListByEventHubOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/client.go new file mode 100644 index 000000000000..980852cd6a00 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/client.go @@ -0,0 +1,18 @@ +package consumergroups + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConsumerGroupsClient struct { + Client autorest.Client + baseUri string +} + +func NewConsumerGroupsClientWithBaseURI(endpoint string) ConsumerGroupsClient { + return ConsumerGroupsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/id_consumergroup.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/id_consumergroup.go new file mode 100644 index 000000000000..9b0ec2324403 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/id_consumergroup.go @@ -0,0 +1,150 @@ +package consumergroups + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ConsumerGroupId{} + +// ConsumerGroupId is a struct representing the Resource ID for a Consumer Group +type ConsumerGroupId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + EventHubName string + ConsumerGroupName string +} + +// NewConsumerGroupID returns a new ConsumerGroupId struct +func NewConsumerGroupID(subscriptionId string, resourceGroupName string, namespaceName string, eventHubName string, consumerGroupName string) ConsumerGroupId { + return ConsumerGroupId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + EventHubName: eventHubName, + ConsumerGroupName: consumerGroupName, + } +} + +// ParseConsumerGroupID parses 'input' into a ConsumerGroupId +func ParseConsumerGroupID(input string) (*ConsumerGroupId, error) { + parser := resourceids.NewParserFromResourceIdType(ConsumerGroupId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ConsumerGroupId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + if id.ConsumerGroupName, ok = parsed.Parsed["consumerGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'consumerGroupName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseConsumerGroupIDInsensitively parses 'input' case-insensitively into a ConsumerGroupId +// note: this method should only be used for API response data and not user input +func ParseConsumerGroupIDInsensitively(input string) (*ConsumerGroupId, error) { + parser := resourceids.NewParserFromResourceIdType(ConsumerGroupId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ConsumerGroupId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + if id.ConsumerGroupName, ok = parsed.Parsed["consumerGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'consumerGroupName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateConsumerGroupID checks that 'input' can be parsed as a Consumer Group ID +func ValidateConsumerGroupID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseConsumerGroupID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Consumer Group ID +func (id ConsumerGroupId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/eventhubs/%s/consumerGroups/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.EventHubName, id.ConsumerGroupName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Consumer Group ID +func (id ConsumerGroupId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticEventhubs", "eventhubs", "eventhubs"), + resourceids.UserSpecifiedSegment("eventHubName", "eventHubValue"), + resourceids.StaticSegment("staticConsumerGroups", "consumerGroups", "consumerGroups"), + resourceids.UserSpecifiedSegment("consumerGroupName", "consumerGroupValue"), + } +} + +// String returns a human-readable description of this Consumer Group ID +func (id ConsumerGroupId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Event Hub Name: %q", id.EventHubName), + fmt.Sprintf("Consumer Group Name: %q", id.ConsumerGroupName), + } + return fmt.Sprintf("Consumer Group (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/id_eventhub.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/id_eventhub.go new file mode 100644 index 000000000000..c0613963a6c5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/id_eventhub.go @@ -0,0 +1,137 @@ +package consumergroups + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = EventhubId{} + +// EventhubId is a struct representing the Resource ID for a Eventhub +type EventhubId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + EventHubName string +} + +// NewEventhubID returns a new EventhubId struct +func NewEventhubID(subscriptionId string, resourceGroupName string, namespaceName string, eventHubName string) EventhubId { + return EventhubId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + EventHubName: eventHubName, + } +} + +// ParseEventhubID parses 'input' into a EventhubId +func ParseEventhubID(input string) (*EventhubId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseEventhubIDInsensitively parses 'input' case-insensitively into a EventhubId +// note: this method should only be used for API response data and not user input +func ParseEventhubIDInsensitively(input string) (*EventhubId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateEventhubID checks that 'input' can be parsed as a Eventhub ID +func ValidateEventhubID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseEventhubID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Eventhub ID +func (id EventhubId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/eventhubs/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.EventHubName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Eventhub ID +func (id EventhubId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticEventhubs", "eventhubs", "eventhubs"), + resourceids.UserSpecifiedSegment("eventHubName", "eventHubValue"), + } +} + +// String returns a human-readable description of this Eventhub ID +func (id EventhubId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Event Hub Name: %q", id.EventHubName), + } + return fmt.Sprintf("Eventhub (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_createorupdate_autorest.go new file mode 100644 index 000000000000..56a93b8d8ef9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package consumergroups + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *ConsumerGroup +} + +// CreateOrUpdate ... +func (c ConsumerGroupsClient) CreateOrUpdate(ctx context.Context, id ConsumerGroupId, input ConsumerGroup) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c ConsumerGroupsClient) preparerForCreateOrUpdate(ctx context.Context, id ConsumerGroupId, input ConsumerGroup) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c ConsumerGroupsClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_delete_autorest.go new file mode 100644 index 000000000000..8bb302109088 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_delete_autorest.go @@ -0,0 +1,65 @@ +package consumergroups + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c ConsumerGroupsClient) Delete(ctx context.Context, id ConsumerGroupId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c ConsumerGroupsClient) preparerForDelete(ctx context.Context, id ConsumerGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c ConsumerGroupsClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_get_autorest.go new file mode 100644 index 000000000000..9188417af9f5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_get_autorest.go @@ -0,0 +1,67 @@ +package consumergroups + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *ConsumerGroup +} + +// Get ... +func (c ConsumerGroupsClient) Get(ctx context.Context, id ConsumerGroupId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c ConsumerGroupsClient) preparerForGet(ctx context.Context, id ConsumerGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c ConsumerGroupsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_listbyeventhub_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_listbyeventhub_autorest.go new file mode 100644 index 000000000000..a0a5ffdec1a2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/method_listbyeventhub_autorest.go @@ -0,0 +1,220 @@ +package consumergroups + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByEventHubOperationResponse struct { + HttpResponse *http.Response + Model *[]ConsumerGroup + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByEventHubOperationResponse, error) +} + +type ListByEventHubCompleteResult struct { + Items []ConsumerGroup +} + +func (r ListByEventHubOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByEventHubOperationResponse) LoadMore(ctx context.Context) (resp ListByEventHubOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type ListByEventHubOperationOptions struct { + Skip *int64 + Top *int64 +} + +func DefaultListByEventHubOperationOptions() ListByEventHubOperationOptions { + return ListByEventHubOperationOptions{} +} + +func (o ListByEventHubOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o ListByEventHubOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Skip != nil { + out["$skip"] = *o.Skip + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// ListByEventHub ... +func (c ConsumerGroupsClient) ListByEventHub(ctx context.Context, id EventhubId, options ListByEventHubOperationOptions) (resp ListByEventHubOperationResponse, err error) { + req, err := c.preparerForListByEventHub(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "ListByEventHub", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "ListByEventHub", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByEventHub(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "ListByEventHub", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByEventHubComplete retrieves all of the results into a single object +func (c ConsumerGroupsClient) ListByEventHubComplete(ctx context.Context, id EventhubId, options ListByEventHubOperationOptions) (ListByEventHubCompleteResult, error) { + return c.ListByEventHubCompleteMatchingPredicate(ctx, id, options, ConsumerGroupOperationPredicate{}) +} + +// ListByEventHubCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c ConsumerGroupsClient) ListByEventHubCompleteMatchingPredicate(ctx context.Context, id EventhubId, options ListByEventHubOperationOptions, predicate ConsumerGroupOperationPredicate) (resp ListByEventHubCompleteResult, err error) { + items := make([]ConsumerGroup, 0) + + page, err := c.ListByEventHub(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByEventHubCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByEventHub prepares the ListByEventHub request. +func (c ConsumerGroupsClient) preparerForListByEventHub(ctx context.Context, id EventhubId, options ListByEventHubOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/consumerGroups", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByEventHubWithNextLink prepares the ListByEventHub request with the given nextLink token. +func (c ConsumerGroupsClient) preparerForListByEventHubWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByEventHub handles the response to the ListByEventHub request. The method always +// closes the http.Response Body. +func (c ConsumerGroupsClient) responderForListByEventHub(resp *http.Response) (result ListByEventHubOperationResponse, err error) { + type page struct { + Values []ConsumerGroup `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByEventHubOperationResponse, err error) { + req, err := c.preparerForListByEventHubWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "ListByEventHub", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "ListByEventHub", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByEventHub(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "consumergroups.ConsumerGroupsClient", "ListByEventHub", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/model_consumergroup.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/model_consumergroup.go new file mode 100644 index 000000000000..c6aefc44f49a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/model_consumergroup.go @@ -0,0 +1,11 @@ +package consumergroups + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConsumerGroup struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *ConsumerGroupProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/model_consumergroupproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/model_consumergroupproperties.go new file mode 100644 index 000000000000..f34d76ca78db --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/model_consumergroupproperties.go @@ -0,0 +1,40 @@ +package consumergroups + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConsumerGroupProperties struct { + CreatedAt *string `json:"createdAt,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` + UserMetadata *string `json:"userMetadata,omitempty"` +} + +func (o *ConsumerGroupProperties) GetCreatedAtAsTime() (*time.Time, error) { + if o.CreatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *ConsumerGroupProperties) SetCreatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedAt = &formatted +} + +func (o *ConsumerGroupProperties) GetUpdatedAtAsTime() (*time.Time, error) { + if o.UpdatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.UpdatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *ConsumerGroupProperties) SetUpdatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.UpdatedAt = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/predicates.go new file mode 100644 index 000000000000..073bf2b48e7a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/predicates.go @@ -0,0 +1,24 @@ +package consumergroups + +type ConsumerGroupOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p ConsumerGroupOperationPredicate) Matches(input ConsumerGroup) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/version.go new file mode 100644 index 000000000000..065e9569d927 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups/version.go @@ -0,0 +1,12 @@ +package consumergroups + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2017-04-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/consumergroups/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/README.md new file mode 100644 index 000000000000..506719077e6a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/README.md @@ -0,0 +1,122 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs` Documentation + +The `disasterrecoveryconfigs` SDK allows for interaction with the Azure Resource Manager Service `eventhub` (API Version `2017-04-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs" +``` + + +### Client Initialization + +```go +client := disasterrecoveryconfigs.NewDisasterRecoveryConfigsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.BreakPairing` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +read, err := client.BreakPairing(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +payload := disasterrecoveryconfigs.ArmDisasterRecovery{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.Delete` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.FailOver` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +read, err := client.FailOver(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.Get` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.List` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +// alternatively `client.List(ctx, id)` can be used to do batched pagination +items, err := client.ListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/client.go new file mode 100644 index 000000000000..92bd0f75168c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/client.go @@ -0,0 +1,18 @@ +package disasterrecoveryconfigs + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DisasterRecoveryConfigsClient struct { + Client autorest.Client + baseUri string +} + +func NewDisasterRecoveryConfigsClientWithBaseURI(endpoint string) DisasterRecoveryConfigsClient { + return DisasterRecoveryConfigsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/constants.go new file mode 100644 index 000000000000..8c8c6ff74d2a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/constants.go @@ -0,0 +1,68 @@ +package disasterrecoveryconfigs + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ProvisioningStateDR string + +const ( + ProvisioningStateDRAccepted ProvisioningStateDR = "Accepted" + ProvisioningStateDRFailed ProvisioningStateDR = "Failed" + ProvisioningStateDRSucceeded ProvisioningStateDR = "Succeeded" +) + +func PossibleValuesForProvisioningStateDR() []string { + return []string{ + string(ProvisioningStateDRAccepted), + string(ProvisioningStateDRFailed), + string(ProvisioningStateDRSucceeded), + } +} + +func parseProvisioningStateDR(input string) (*ProvisioningStateDR, error) { + vals := map[string]ProvisioningStateDR{ + "accepted": ProvisioningStateDRAccepted, + "failed": ProvisioningStateDRFailed, + "succeeded": ProvisioningStateDRSucceeded, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ProvisioningStateDR(input) + return &out, nil +} + +type RoleDisasterRecovery string + +const ( + RoleDisasterRecoveryPrimary RoleDisasterRecovery = "Primary" + RoleDisasterRecoveryPrimaryNotReplicating RoleDisasterRecovery = "PrimaryNotReplicating" + RoleDisasterRecoverySecondary RoleDisasterRecovery = "Secondary" +) + +func PossibleValuesForRoleDisasterRecovery() []string { + return []string{ + string(RoleDisasterRecoveryPrimary), + string(RoleDisasterRecoveryPrimaryNotReplicating), + string(RoleDisasterRecoverySecondary), + } +} + +func parseRoleDisasterRecovery(input string) (*RoleDisasterRecovery, error) { + vals := map[string]RoleDisasterRecovery{ + "primary": RoleDisasterRecoveryPrimary, + "primarynotreplicating": RoleDisasterRecoveryPrimaryNotReplicating, + "secondary": RoleDisasterRecoverySecondary, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := RoleDisasterRecovery(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/id_disasterrecoveryconfig.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/id_disasterrecoveryconfig.go new file mode 100644 index 000000000000..ad109682b0ee --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/id_disasterrecoveryconfig.go @@ -0,0 +1,137 @@ +package disasterrecoveryconfigs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = DisasterRecoveryConfigId{} + +// DisasterRecoveryConfigId is a struct representing the Resource ID for a Disaster Recovery Config +type DisasterRecoveryConfigId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + Alias string +} + +// NewDisasterRecoveryConfigID returns a new DisasterRecoveryConfigId struct +func NewDisasterRecoveryConfigID(subscriptionId string, resourceGroupName string, namespaceName string, alias string) DisasterRecoveryConfigId { + return DisasterRecoveryConfigId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + Alias: alias, + } +} + +// ParseDisasterRecoveryConfigID parses 'input' into a DisasterRecoveryConfigId +func ParseDisasterRecoveryConfigID(input string) (*DisasterRecoveryConfigId, error) { + parser := resourceids.NewParserFromResourceIdType(DisasterRecoveryConfigId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := DisasterRecoveryConfigId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.Alias, ok = parsed.Parsed["alias"]; !ok { + return nil, fmt.Errorf("the segment 'alias' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseDisasterRecoveryConfigIDInsensitively parses 'input' case-insensitively into a DisasterRecoveryConfigId +// note: this method should only be used for API response data and not user input +func ParseDisasterRecoveryConfigIDInsensitively(input string) (*DisasterRecoveryConfigId, error) { + parser := resourceids.NewParserFromResourceIdType(DisasterRecoveryConfigId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := DisasterRecoveryConfigId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.Alias, ok = parsed.Parsed["alias"]; !ok { + return nil, fmt.Errorf("the segment 'alias' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateDisasterRecoveryConfigID checks that 'input' can be parsed as a Disaster Recovery Config ID +func ValidateDisasterRecoveryConfigID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseDisasterRecoveryConfigID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Disaster Recovery Config ID +func (id DisasterRecoveryConfigId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/disasterRecoveryConfigs/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.Alias) +} + +// Segments returns a slice of Resource ID Segments which comprise this Disaster Recovery Config ID +func (id DisasterRecoveryConfigId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticDisasterRecoveryConfigs", "disasterRecoveryConfigs", "disasterRecoveryConfigs"), + resourceids.UserSpecifiedSegment("alias", "aliasValue"), + } +} + +// String returns a human-readable description of this Disaster Recovery Config ID +func (id DisasterRecoveryConfigId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Alias: %q", id.Alias), + } + return fmt.Sprintf("Disaster Recovery Config (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/id_namespace.go new file mode 100644 index 000000000000..8d50ced2cc0e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/id_namespace.go @@ -0,0 +1,124 @@ +package disasterrecoveryconfigs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_breakpairing_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_breakpairing_autorest.go new file mode 100644 index 000000000000..144131ab3e57 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_breakpairing_autorest.go @@ -0,0 +1,66 @@ +package disasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type BreakPairingOperationResponse struct { + HttpResponse *http.Response +} + +// BreakPairing ... +func (c DisasterRecoveryConfigsClient) BreakPairing(ctx context.Context, id DisasterRecoveryConfigId) (result BreakPairingOperationResponse, err error) { + req, err := c.preparerForBreakPairing(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "BreakPairing", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "BreakPairing", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForBreakPairing(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "BreakPairing", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForBreakPairing prepares the BreakPairing request. +func (c DisasterRecoveryConfigsClient) preparerForBreakPairing(ctx context.Context, id DisasterRecoveryConfigId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/breakPairing", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForBreakPairing handles the response to the BreakPairing request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForBreakPairing(resp *http.Response) (result BreakPairingOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_createorupdate_autorest.go new file mode 100644 index 000000000000..f6ed48aef31d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package disasterrecoveryconfigs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *ArmDisasterRecovery +} + +// CreateOrUpdate ... +func (c DisasterRecoveryConfigsClient) CreateOrUpdate(ctx context.Context, id DisasterRecoveryConfigId, input ArmDisasterRecovery) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c DisasterRecoveryConfigsClient) preparerForCreateOrUpdate(ctx context.Context, id DisasterRecoveryConfigId, input ArmDisasterRecovery) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_delete_autorest.go new file mode 100644 index 000000000000..b98d8635ee1e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_delete_autorest.go @@ -0,0 +1,65 @@ +package disasterrecoveryconfigs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c DisasterRecoveryConfigsClient) Delete(ctx context.Context, id DisasterRecoveryConfigId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c DisasterRecoveryConfigsClient) preparerForDelete(ctx context.Context, id DisasterRecoveryConfigId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_failover_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_failover_autorest.go new file mode 100644 index 000000000000..1189d6935549 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_failover_autorest.go @@ -0,0 +1,66 @@ +package disasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FailOverOperationResponse struct { + HttpResponse *http.Response +} + +// FailOver ... +func (c DisasterRecoveryConfigsClient) FailOver(ctx context.Context, id DisasterRecoveryConfigId) (result FailOverOperationResponse, err error) { + req, err := c.preparerForFailOver(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "FailOver", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "FailOver", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForFailOver(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "FailOver", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForFailOver prepares the FailOver request. +func (c DisasterRecoveryConfigsClient) preparerForFailOver(ctx context.Context, id DisasterRecoveryConfigId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/failover", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForFailOver handles the response to the FailOver request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForFailOver(resp *http.Response) (result FailOverOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_get_autorest.go new file mode 100644 index 000000000000..da5493fb0272 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_get_autorest.go @@ -0,0 +1,67 @@ +package disasterrecoveryconfigs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *ArmDisasterRecovery +} + +// Get ... +func (c DisasterRecoveryConfigsClient) Get(ctx context.Context, id DisasterRecoveryConfigId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c DisasterRecoveryConfigsClient) preparerForGet(ctx context.Context, id DisasterRecoveryConfigId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_list_autorest.go new file mode 100644 index 000000000000..abd321a27394 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/method_list_autorest.go @@ -0,0 +1,186 @@ +package disasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *[]ArmDisasterRecovery + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) +} + +type ListCompleteResult struct { + Items []ArmDisasterRecovery +} + +func (r ListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// List ... +func (c DisasterRecoveryConfigsClient) List(ctx context.Context, id NamespaceId) (resp ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListComplete retrieves all of the results into a single object +func (c DisasterRecoveryConfigsClient) ListComplete(ctx context.Context, id NamespaceId) (ListCompleteResult, error) { + return c.ListCompleteMatchingPredicate(ctx, id, ArmDisasterRecoveryOperationPredicate{}) +} + +// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c DisasterRecoveryConfigsClient) ListCompleteMatchingPredicate(ctx context.Context, id NamespaceId, predicate ArmDisasterRecoveryOperationPredicate) (resp ListCompleteResult, err error) { + items := make([]ArmDisasterRecovery, 0) + + page, err := c.List(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForList prepares the List request. +func (c DisasterRecoveryConfigsClient) preparerForList(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/disasterRecoveryConfigs", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListWithNextLink prepares the List request with the given nextLink token. +func (c DisasterRecoveryConfigsClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + type page struct { + Values []ArmDisasterRecovery `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { + req, err := c.preparerForListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/model_armdisasterrecovery.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/model_armdisasterrecovery.go new file mode 100644 index 000000000000..88fb2f3edb4c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/model_armdisasterrecovery.go @@ -0,0 +1,11 @@ +package disasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ArmDisasterRecovery struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *ArmDisasterRecoveryProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/model_armdisasterrecoveryproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/model_armdisasterrecoveryproperties.go new file mode 100644 index 000000000000..233aac5a3e81 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/model_armdisasterrecoveryproperties.go @@ -0,0 +1,12 @@ +package disasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ArmDisasterRecoveryProperties struct { + AlternateName *string `json:"alternateName,omitempty"` + PartnerNamespace *string `json:"partnerNamespace,omitempty"` + PendingReplicationOperationsCount *int64 `json:"pendingReplicationOperationsCount,omitempty"` + ProvisioningState *ProvisioningStateDR `json:"provisioningState,omitempty"` + Role *RoleDisasterRecovery `json:"role,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/predicates.go new file mode 100644 index 000000000000..b1a661738fac --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/predicates.go @@ -0,0 +1,24 @@ +package disasterrecoveryconfigs + +type ArmDisasterRecoveryOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p ArmDisasterRecoveryOperationPredicate) Matches(input ArmDisasterRecovery) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/version.go new file mode 100644 index 000000000000..992e04e271c6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs/version.go @@ -0,0 +1,12 @@ +package disasterrecoveryconfigs + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2017-04-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/disasterrecoveryconfigs/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/README.md new file mode 100644 index 000000000000..3f3dfaa29be0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/README.md @@ -0,0 +1,122 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs` Documentation + +The `eventhubs` SDK allows for interaction with the Azure Resource Manager Service `eventhub` (API Version `2017-04-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs" +``` + + +### Client Initialization + +```go +client := eventhubs.NewEventHubsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `EventHubsClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := eventhubs.NewEventhubID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue") + +payload := eventhubs.Eventhub{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `EventHubsClient.Delete` + +```go +ctx := context.TODO() +id := eventhubs.NewEventhubID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `EventHubsClient.DeleteAuthorizationRule` + +```go +ctx := context.TODO() +id := eventhubs.NewEventhubAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue", "authorizationRuleValue") + +read, err := client.DeleteAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `EventHubsClient.Get` + +```go +ctx := context.TODO() +id := eventhubs.NewEventhubID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `EventHubsClient.GetAuthorizationRule` + +```go +ctx := context.TODO() +id := eventhubs.NewEventhubAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "eventHubValue", "authorizationRuleValue") + +read, err := client.GetAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `EventHubsClient.ListByNamespace` + +```go +ctx := context.TODO() +id := eventhubs.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +// alternatively `client.ListByNamespace(ctx, id, eventhubs.DefaultListByNamespaceOperationOptions())` can be used to do batched pagination +items, err := client.ListByNamespaceComplete(ctx, id, eventhubs.DefaultListByNamespaceOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/client.go new file mode 100644 index 000000000000..5eb53e47b4a2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/client.go @@ -0,0 +1,18 @@ +package eventhubs + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EventHubsClient struct { + Client autorest.Client + baseUri string +} + +func NewEventHubsClientWithBaseURI(endpoint string) EventHubsClient { + return EventHubsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/constants.go new file mode 100644 index 000000000000..89e20f646d89 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/constants.go @@ -0,0 +1,114 @@ +package eventhubs + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessRights string + +const ( + AccessRightsListen AccessRights = "Listen" + AccessRightsManage AccessRights = "Manage" + AccessRightsSend AccessRights = "Send" +) + +func PossibleValuesForAccessRights() []string { + return []string{ + string(AccessRightsListen), + string(AccessRightsManage), + string(AccessRightsSend), + } +} + +func parseAccessRights(input string) (*AccessRights, error) { + vals := map[string]AccessRights{ + "listen": AccessRightsListen, + "manage": AccessRightsManage, + "send": AccessRightsSend, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AccessRights(input) + return &out, nil +} + +type EncodingCaptureDescription string + +const ( + EncodingCaptureDescriptionAvro EncodingCaptureDescription = "Avro" + EncodingCaptureDescriptionAvroDeflate EncodingCaptureDescription = "AvroDeflate" +) + +func PossibleValuesForEncodingCaptureDescription() []string { + return []string{ + string(EncodingCaptureDescriptionAvro), + string(EncodingCaptureDescriptionAvroDeflate), + } +} + +func parseEncodingCaptureDescription(input string) (*EncodingCaptureDescription, error) { + vals := map[string]EncodingCaptureDescription{ + "avro": EncodingCaptureDescriptionAvro, + "avrodeflate": EncodingCaptureDescriptionAvroDeflate, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EncodingCaptureDescription(input) + return &out, nil +} + +type EntityStatus string + +const ( + EntityStatusActive EntityStatus = "Active" + EntityStatusCreating EntityStatus = "Creating" + EntityStatusDeleting EntityStatus = "Deleting" + EntityStatusDisabled EntityStatus = "Disabled" + EntityStatusReceiveDisabled EntityStatus = "ReceiveDisabled" + EntityStatusRenaming EntityStatus = "Renaming" + EntityStatusRestoring EntityStatus = "Restoring" + EntityStatusSendDisabled EntityStatus = "SendDisabled" + EntityStatusUnknown EntityStatus = "Unknown" +) + +func PossibleValuesForEntityStatus() []string { + return []string{ + string(EntityStatusActive), + string(EntityStatusCreating), + string(EntityStatusDeleting), + string(EntityStatusDisabled), + string(EntityStatusReceiveDisabled), + string(EntityStatusRenaming), + string(EntityStatusRestoring), + string(EntityStatusSendDisabled), + string(EntityStatusUnknown), + } +} + +func parseEntityStatus(input string) (*EntityStatus, error) { + vals := map[string]EntityStatus{ + "active": EntityStatusActive, + "creating": EntityStatusCreating, + "deleting": EntityStatusDeleting, + "disabled": EntityStatusDisabled, + "receivedisabled": EntityStatusReceiveDisabled, + "renaming": EntityStatusRenaming, + "restoring": EntityStatusRestoring, + "senddisabled": EntityStatusSendDisabled, + "unknown": EntityStatusUnknown, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EntityStatus(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_eventhub.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_eventhub.go new file mode 100644 index 000000000000..665ab9cc1234 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_eventhub.go @@ -0,0 +1,137 @@ +package eventhubs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = EventhubId{} + +// EventhubId is a struct representing the Resource ID for a Eventhub +type EventhubId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + EventHubName string +} + +// NewEventhubID returns a new EventhubId struct +func NewEventhubID(subscriptionId string, resourceGroupName string, namespaceName string, eventHubName string) EventhubId { + return EventhubId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + EventHubName: eventHubName, + } +} + +// ParseEventhubID parses 'input' into a EventhubId +func ParseEventhubID(input string) (*EventhubId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseEventhubIDInsensitively parses 'input' case-insensitively into a EventhubId +// note: this method should only be used for API response data and not user input +func ParseEventhubIDInsensitively(input string) (*EventhubId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateEventhubID checks that 'input' can be parsed as a Eventhub ID +func ValidateEventhubID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseEventhubID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Eventhub ID +func (id EventhubId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/eventhubs/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.EventHubName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Eventhub ID +func (id EventhubId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticEventhubs", "eventhubs", "eventhubs"), + resourceids.UserSpecifiedSegment("eventHubName", "eventHubValue"), + } +} + +// String returns a human-readable description of this Eventhub ID +func (id EventhubId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Event Hub Name: %q", id.EventHubName), + } + return fmt.Sprintf("Eventhub (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_eventhubauthorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_eventhubauthorizationrule.go new file mode 100644 index 000000000000..0aaa6901e14f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_eventhubauthorizationrule.go @@ -0,0 +1,150 @@ +package eventhubs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = EventhubAuthorizationRuleId{} + +// EventhubAuthorizationRuleId is a struct representing the Resource ID for a Eventhub Authorization Rule +type EventhubAuthorizationRuleId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + EventHubName string + AuthorizationRuleName string +} + +// NewEventhubAuthorizationRuleID returns a new EventhubAuthorizationRuleId struct +func NewEventhubAuthorizationRuleID(subscriptionId string, resourceGroupName string, namespaceName string, eventHubName string, authorizationRuleName string) EventhubAuthorizationRuleId { + return EventhubAuthorizationRuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + EventHubName: eventHubName, + AuthorizationRuleName: authorizationRuleName, + } +} + +// ParseEventhubAuthorizationRuleID parses 'input' into a EventhubAuthorizationRuleId +func ParseEventhubAuthorizationRuleID(input string) (*EventhubAuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubAuthorizationRuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubAuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseEventhubAuthorizationRuleIDInsensitively parses 'input' case-insensitively into a EventhubAuthorizationRuleId +// note: this method should only be used for API response data and not user input +func ParseEventhubAuthorizationRuleIDInsensitively(input string) (*EventhubAuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(EventhubAuthorizationRuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := EventhubAuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.EventHubName, ok = parsed.Parsed["eventHubName"]; !ok { + return nil, fmt.Errorf("the segment 'eventHubName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateEventhubAuthorizationRuleID checks that 'input' can be parsed as a Eventhub Authorization Rule ID +func ValidateEventhubAuthorizationRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseEventhubAuthorizationRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Eventhub Authorization Rule ID +func (id EventhubAuthorizationRuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/eventhubs/%s/authorizationRules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.EventHubName, id.AuthorizationRuleName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Eventhub Authorization Rule ID +func (id EventhubAuthorizationRuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticEventhubs", "eventhubs", "eventhubs"), + resourceids.UserSpecifiedSegment("eventHubName", "eventHubValue"), + resourceids.StaticSegment("staticAuthorizationRules", "authorizationRules", "authorizationRules"), + resourceids.UserSpecifiedSegment("authorizationRuleName", "authorizationRuleValue"), + } +} + +// String returns a human-readable description of this Eventhub Authorization Rule ID +func (id EventhubAuthorizationRuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Event Hub Name: %q", id.EventHubName), + fmt.Sprintf("Authorization Rule Name: %q", id.AuthorizationRuleName), + } + return fmt.Sprintf("Eventhub Authorization Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_namespace.go new file mode 100644 index 000000000000..d24e62c9d7c1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/id_namespace.go @@ -0,0 +1,124 @@ +package eventhubs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_createorupdate_autorest.go new file mode 100644 index 000000000000..c0871695fa6d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package eventhubs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *Eventhub +} + +// CreateOrUpdate ... +func (c EventHubsClient) CreateOrUpdate(ctx context.Context, id EventhubId, input Eventhub) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c EventHubsClient) preparerForCreateOrUpdate(ctx context.Context, id EventhubId, input Eventhub) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c EventHubsClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_delete_autorest.go new file mode 100644 index 000000000000..d78ba256cbfd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_delete_autorest.go @@ -0,0 +1,65 @@ +package eventhubs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c EventHubsClient) Delete(ctx context.Context, id EventhubId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c EventHubsClient) preparerForDelete(ctx context.Context, id EventhubId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c EventHubsClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_deleteauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_deleteauthorizationrule_autorest.go new file mode 100644 index 000000000000..0de9f9863ea5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_deleteauthorizationrule_autorest.go @@ -0,0 +1,65 @@ +package eventhubs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response +} + +// DeleteAuthorizationRule ... +func (c EventHubsClient) DeleteAuthorizationRule(ctx context.Context, id EventhubAuthorizationRuleId) (result DeleteAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForDeleteAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "DeleteAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "DeleteAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDeleteAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "DeleteAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDeleteAuthorizationRule prepares the DeleteAuthorizationRule request. +func (c EventHubsClient) preparerForDeleteAuthorizationRule(ctx context.Context, id EventhubAuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDeleteAuthorizationRule handles the response to the DeleteAuthorizationRule request. The method always +// closes the http.Response Body. +func (c EventHubsClient) responderForDeleteAuthorizationRule(resp *http.Response) (result DeleteAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_get_autorest.go new file mode 100644 index 000000000000..9d3b066d946e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_get_autorest.go @@ -0,0 +1,67 @@ +package eventhubs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *Eventhub +} + +// Get ... +func (c EventHubsClient) Get(ctx context.Context, id EventhubId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c EventHubsClient) preparerForGet(ctx context.Context, id EventhubId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c EventHubsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_getauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_getauthorizationrule_autorest.go new file mode 100644 index 000000000000..ce69338e5fab --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_getauthorizationrule_autorest.go @@ -0,0 +1,67 @@ +package eventhubs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *AuthorizationRule +} + +// GetAuthorizationRule ... +func (c EventHubsClient) GetAuthorizationRule(ctx context.Context, id EventhubAuthorizationRuleId) (result GetAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForGetAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "GetAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "GetAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGetAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "GetAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGetAuthorizationRule prepares the GetAuthorizationRule request. +func (c EventHubsClient) preparerForGetAuthorizationRule(ctx context.Context, id EventhubAuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGetAuthorizationRule handles the response to the GetAuthorizationRule request. The method always +// closes the http.Response Body. +func (c EventHubsClient) responderForGetAuthorizationRule(resp *http.Response) (result GetAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_listbynamespace_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_listbynamespace_autorest.go new file mode 100644 index 000000000000..34dbc420a6d1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/method_listbynamespace_autorest.go @@ -0,0 +1,220 @@ +package eventhubs + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByNamespaceOperationResponse struct { + HttpResponse *http.Response + Model *[]Eventhub + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByNamespaceOperationResponse, error) +} + +type ListByNamespaceCompleteResult struct { + Items []Eventhub +} + +func (r ListByNamespaceOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByNamespaceOperationResponse) LoadMore(ctx context.Context) (resp ListByNamespaceOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type ListByNamespaceOperationOptions struct { + Skip *int64 + Top *int64 +} + +func DefaultListByNamespaceOperationOptions() ListByNamespaceOperationOptions { + return ListByNamespaceOperationOptions{} +} + +func (o ListByNamespaceOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o ListByNamespaceOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Skip != nil { + out["$skip"] = *o.Skip + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// ListByNamespace ... +func (c EventHubsClient) ListByNamespace(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions) (resp ListByNamespaceOperationResponse, err error) { + req, err := c.preparerForListByNamespace(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "ListByNamespace", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "ListByNamespace", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByNamespace(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "ListByNamespace", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByNamespaceComplete retrieves all of the results into a single object +func (c EventHubsClient) ListByNamespaceComplete(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions) (ListByNamespaceCompleteResult, error) { + return c.ListByNamespaceCompleteMatchingPredicate(ctx, id, options, EventhubOperationPredicate{}) +} + +// ListByNamespaceCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c EventHubsClient) ListByNamespaceCompleteMatchingPredicate(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions, predicate EventhubOperationPredicate) (resp ListByNamespaceCompleteResult, err error) { + items := make([]Eventhub, 0) + + page, err := c.ListByNamespace(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByNamespaceCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByNamespace prepares the ListByNamespace request. +func (c EventHubsClient) preparerForListByNamespace(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/eventhubs", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByNamespaceWithNextLink prepares the ListByNamespace request with the given nextLink token. +func (c EventHubsClient) preparerForListByNamespaceWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByNamespace handles the response to the ListByNamespace request. The method always +// closes the http.Response Body. +func (c EventHubsClient) responderForListByNamespace(resp *http.Response) (result ListByNamespaceOperationResponse, err error) { + type page struct { + Values []Eventhub `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByNamespaceOperationResponse, err error) { + req, err := c.preparerForListByNamespaceWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "ListByNamespace", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "ListByNamespace", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByNamespace(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubs.EventHubsClient", "ListByNamespace", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_authorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_authorizationrule.go new file mode 100644 index 000000000000..5892b249c2f4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_authorizationrule.go @@ -0,0 +1,11 @@ +package eventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AuthorizationRule struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *AuthorizationRuleProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_authorizationruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_authorizationruleproperties.go new file mode 100644 index 000000000000..3b364835633e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_authorizationruleproperties.go @@ -0,0 +1,8 @@ +package eventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AuthorizationRuleProperties struct { + Rights []AccessRights `json:"rights"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_capturedescription.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_capturedescription.go new file mode 100644 index 000000000000..527b7c7974b1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_capturedescription.go @@ -0,0 +1,13 @@ +package eventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CaptureDescription struct { + Destination *Destination `json:"destination,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + Encoding *EncodingCaptureDescription `json:"encoding,omitempty"` + IntervalInSeconds *int64 `json:"intervalInSeconds,omitempty"` + SizeLimitInBytes *int64 `json:"sizeLimitInBytes,omitempty"` + SkipEmptyArchives *bool `json:"skipEmptyArchives,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_destination.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_destination.go new file mode 100644 index 000000000000..e14ec4e1ee38 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_destination.go @@ -0,0 +1,9 @@ +package eventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Destination struct { + Name *string `json:"name,omitempty"` + Properties *DestinationProperties `json:"properties,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_destinationproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_destinationproperties.go new file mode 100644 index 000000000000..6c36700b6571 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_destinationproperties.go @@ -0,0 +1,10 @@ +package eventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DestinationProperties struct { + ArchiveNameFormat *string `json:"archiveNameFormat,omitempty"` + BlobContainer *string `json:"blobContainer,omitempty"` + StorageAccountResourceId *string `json:"storageAccountResourceId,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_eventhub.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_eventhub.go new file mode 100644 index 000000000000..68cc849db7d8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_eventhub.go @@ -0,0 +1,11 @@ +package eventhubs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Eventhub struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *EventhubProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_eventhubproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_eventhubproperties.go new file mode 100644 index 000000000000..9afd92ec6dc5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/model_eventhubproperties.go @@ -0,0 +1,44 @@ +package eventhubs + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EventhubProperties struct { + CaptureDescription *CaptureDescription `json:"captureDescription,omitempty"` + CreatedAt *string `json:"createdAt,omitempty"` + MessageRetentionInDays *int64 `json:"messageRetentionInDays,omitempty"` + PartitionCount *int64 `json:"partitionCount,omitempty"` + PartitionIds *[]string `json:"partitionIds,omitempty"` + Status *EntityStatus `json:"status,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` +} + +func (o *EventhubProperties) GetCreatedAtAsTime() (*time.Time, error) { + if o.CreatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *EventhubProperties) SetCreatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedAt = &formatted +} + +func (o *EventhubProperties) GetUpdatedAtAsTime() (*time.Time, error) { + if o.UpdatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.UpdatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *EventhubProperties) SetUpdatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.UpdatedAt = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/predicates.go new file mode 100644 index 000000000000..ddbb67f99f80 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/predicates.go @@ -0,0 +1,24 @@ +package eventhubs + +type EventhubOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p EventhubOperationPredicate) Matches(input Eventhub) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/version.go new file mode 100644 index 000000000000..18bb1481b6de --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs/version.go @@ -0,0 +1,12 @@ +package eventhubs + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2017-04-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/eventhubs/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/README.md new file mode 100644 index 000000000000..25dc63c5d985 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/README.md @@ -0,0 +1,99 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters` Documentation + +The `eventhubsclusters` SDK allows for interaction with the Azure Resource Manager Service `eventhub` (API Version `2018-01-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters" +``` + + +### Client Initialization + +```go +client := eventhubsclusters.NewEventHubsClustersClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `EventHubsClustersClient.ClustersCreateOrUpdate` + +```go +ctx := context.TODO() +id := eventhubsclusters.NewClusterID("12345678-1234-9876-4563-123456789012", "example-resource-group", "clusterValue") + +payload := eventhubsclusters.Cluster{ + // ... +} + + +if err := client.ClustersCreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `EventHubsClustersClient.ClustersDelete` + +```go +ctx := context.TODO() +id := eventhubsclusters.NewClusterID("12345678-1234-9876-4563-123456789012", "example-resource-group", "clusterValue") + +if err := client.ClustersDeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `EventHubsClustersClient.ClustersGet` + +```go +ctx := context.TODO() +id := eventhubsclusters.NewClusterID("12345678-1234-9876-4563-123456789012", "example-resource-group", "clusterValue") + +read, err := client.ClustersGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `EventHubsClustersClient.ClustersListByResourceGroup` + +```go +ctx := context.TODO() +id := eventhubsclusters.NewResourceGroupID() + +// alternatively `client.ClustersListByResourceGroup(ctx, id)` can be used to do batched pagination +items, err := client.ClustersListByResourceGroupComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `EventHubsClustersClient.ClustersUpdate` + +```go +ctx := context.TODO() +id := eventhubsclusters.NewClusterID("12345678-1234-9876-4563-123456789012", "example-resource-group", "clusterValue") + +payload := eventhubsclusters.Cluster{ + // ... +} + + +if err := client.ClustersUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/client.go new file mode 100644 index 000000000000..e8b854570454 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/client.go @@ -0,0 +1,18 @@ +package eventhubsclusters + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EventHubsClustersClient struct { + Client autorest.Client + baseUri string +} + +func NewEventHubsClustersClientWithBaseURI(endpoint string) EventHubsClustersClient { + return EventHubsClustersClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/constants.go new file mode 100644 index 000000000000..081abe1b29a8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/constants.go @@ -0,0 +1,31 @@ +package eventhubsclusters + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ClusterSkuName string + +const ( + ClusterSkuNameDedicated ClusterSkuName = "Dedicated" +) + +func PossibleValuesForClusterSkuName() []string { + return []string{ + string(ClusterSkuNameDedicated), + } +} + +func parseClusterSkuName(input string) (*ClusterSkuName, error) { + vals := map[string]ClusterSkuName{ + "dedicated": ClusterSkuNameDedicated, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ClusterSkuName(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/id_cluster.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/id_cluster.go new file mode 100644 index 000000000000..d1950ad134a0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/id_cluster.go @@ -0,0 +1,124 @@ +package eventhubsclusters + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ClusterId{} + +// ClusterId is a struct representing the Resource ID for a Cluster +type ClusterId struct { + SubscriptionId string + ResourceGroupName string + ClusterName string +} + +// NewClusterID returns a new ClusterId struct +func NewClusterID(subscriptionId string, resourceGroupName string, clusterName string) ClusterId { + return ClusterId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ClusterName: clusterName, + } +} + +// ParseClusterID parses 'input' into a ClusterId +func ParseClusterID(input string) (*ClusterId, error) { + parser := resourceids.NewParserFromResourceIdType(ClusterId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ClusterId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ClusterName, ok = parsed.Parsed["clusterName"]; !ok { + return nil, fmt.Errorf("the segment 'clusterName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseClusterIDInsensitively parses 'input' case-insensitively into a ClusterId +// note: this method should only be used for API response data and not user input +func ParseClusterIDInsensitively(input string) (*ClusterId, error) { + parser := resourceids.NewParserFromResourceIdType(ClusterId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ClusterId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ClusterName, ok = parsed.Parsed["clusterName"]; !ok { + return nil, fmt.Errorf("the segment 'clusterName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateClusterID checks that 'input' can be parsed as a Cluster ID +func ValidateClusterID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseClusterID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Cluster ID +func (id ClusterId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/clusters/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ClusterName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Cluster ID +func (id ClusterId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticClusters", "clusters", "clusters"), + resourceids.UserSpecifiedSegment("clusterName", "clusterValue"), + } +} + +// String returns a human-readable description of this Cluster ID +func (id ClusterId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Cluster Name: %q", id.ClusterName), + } + return fmt.Sprintf("Cluster (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clusterscreateorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clusterscreateorupdate_autorest.go new file mode 100644 index 000000000000..bfd345967a61 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clusterscreateorupdate_autorest.go @@ -0,0 +1,79 @@ +package eventhubsclusters + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ClustersCreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// ClustersCreateOrUpdate ... +func (c EventHubsClustersClient) ClustersCreateOrUpdate(ctx context.Context, id ClusterId, input Cluster) (result ClustersCreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForClustersCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersCreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForClustersCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersCreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// ClustersCreateOrUpdateThenPoll performs ClustersCreateOrUpdate then polls until it's completed +func (c EventHubsClustersClient) ClustersCreateOrUpdateThenPoll(ctx context.Context, id ClusterId, input Cluster) error { + result, err := c.ClustersCreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing ClustersCreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after ClustersCreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForClustersCreateOrUpdate prepares the ClustersCreateOrUpdate request. +func (c EventHubsClustersClient) preparerForClustersCreateOrUpdate(ctx context.Context, id ClusterId, input Cluster) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForClustersCreateOrUpdate sends the ClustersCreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c EventHubsClustersClient) senderForClustersCreateOrUpdate(ctx context.Context, req *http.Request) (future ClustersCreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersdelete_autorest.go new file mode 100644 index 000000000000..c47586d4f811 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersdelete_autorest.go @@ -0,0 +1,78 @@ +package eventhubsclusters + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ClustersDeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// ClustersDelete ... +func (c EventHubsClustersClient) ClustersDelete(ctx context.Context, id ClusterId) (result ClustersDeleteOperationResponse, err error) { + req, err := c.preparerForClustersDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersDelete", nil, "Failure preparing request") + return + } + + result, err = c.senderForClustersDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersDelete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// ClustersDeleteThenPoll performs ClustersDelete then polls until it's completed +func (c EventHubsClustersClient) ClustersDeleteThenPoll(ctx context.Context, id ClusterId) error { + result, err := c.ClustersDelete(ctx, id) + if err != nil { + return fmt.Errorf("performing ClustersDelete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after ClustersDelete: %+v", err) + } + + return nil +} + +// preparerForClustersDelete prepares the ClustersDelete request. +func (c EventHubsClustersClient) preparerForClustersDelete(ctx context.Context, id ClusterId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForClustersDelete sends the ClustersDelete request. The method will close the +// http.Response Body if it receives an error. +func (c EventHubsClustersClient) senderForClustersDelete(ctx context.Context, req *http.Request) (future ClustersDeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersget_autorest.go new file mode 100644 index 000000000000..6580dc962d4e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersget_autorest.go @@ -0,0 +1,67 @@ +package eventhubsclusters + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ClustersGetOperationResponse struct { + HttpResponse *http.Response + Model *Cluster +} + +// ClustersGet ... +func (c EventHubsClustersClient) ClustersGet(ctx context.Context, id ClusterId) (result ClustersGetOperationResponse, err error) { + req, err := c.preparerForClustersGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForClustersGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForClustersGet prepares the ClustersGet request. +func (c EventHubsClustersClient) preparerForClustersGet(ctx context.Context, id ClusterId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForClustersGet handles the response to the ClustersGet request. The method always +// closes the http.Response Body. +func (c EventHubsClustersClient) responderForClustersGet(resp *http.Response) (result ClustersGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clusterslistbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clusterslistbyresourcegroup_autorest.go new file mode 100644 index 000000000000..da58b7ba37b0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clusterslistbyresourcegroup_autorest.go @@ -0,0 +1,187 @@ +package eventhubsclusters + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ClustersListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]Cluster + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ClustersListByResourceGroupOperationResponse, error) +} + +type ClustersListByResourceGroupCompleteResult struct { + Items []Cluster +} + +func (r ClustersListByResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ClustersListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ClustersListByResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ClustersListByResourceGroup ... +func (c EventHubsClustersClient) ClustersListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ClustersListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForClustersListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForClustersListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ClustersListByResourceGroupComplete retrieves all of the results into a single object +func (c EventHubsClustersClient) ClustersListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ClustersListByResourceGroupCompleteResult, error) { + return c.ClustersListByResourceGroupCompleteMatchingPredicate(ctx, id, ClusterOperationPredicate{}) +} + +// ClustersListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c EventHubsClustersClient) ClustersListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate ClusterOperationPredicate) (resp ClustersListByResourceGroupCompleteResult, err error) { + items := make([]Cluster, 0) + + page, err := c.ClustersListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ClustersListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForClustersListByResourceGroup prepares the ClustersListByResourceGroup request. +func (c EventHubsClustersClient) preparerForClustersListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.EventHub/clusters", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForClustersListByResourceGroupWithNextLink prepares the ClustersListByResourceGroup request with the given nextLink token. +func (c EventHubsClustersClient) preparerForClustersListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForClustersListByResourceGroup handles the response to the ClustersListByResourceGroup request. The method always +// closes the http.Response Body. +func (c EventHubsClustersClient) responderForClustersListByResourceGroup(resp *http.Response) (result ClustersListByResourceGroupOperationResponse, err error) { + type page struct { + Values []Cluster `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ClustersListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForClustersListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForClustersListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersupdate_autorest.go new file mode 100644 index 000000000000..b912a1d3d150 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/method_clustersupdate_autorest.go @@ -0,0 +1,79 @@ +package eventhubsclusters + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ClustersUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// ClustersUpdate ... +func (c EventHubsClustersClient) ClustersUpdate(ctx context.Context, id ClusterId, input Cluster) (result ClustersUpdateOperationResponse, err error) { + req, err := c.preparerForClustersUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForClustersUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventhubsclusters.EventHubsClustersClient", "ClustersUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// ClustersUpdateThenPoll performs ClustersUpdate then polls until it's completed +func (c EventHubsClustersClient) ClustersUpdateThenPoll(ctx context.Context, id ClusterId, input Cluster) error { + result, err := c.ClustersUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing ClustersUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after ClustersUpdate: %+v", err) + } + + return nil +} + +// preparerForClustersUpdate prepares the ClustersUpdate request. +func (c EventHubsClustersClient) preparerForClustersUpdate(ctx context.Context, id ClusterId, input Cluster) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForClustersUpdate sends the ClustersUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c EventHubsClustersClient) senderForClustersUpdate(ctx context.Context, req *http.Request) (future ClustersUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_cluster.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_cluster.go new file mode 100644 index 000000000000..20dd353e89df --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_cluster.go @@ -0,0 +1,14 @@ +package eventhubsclusters + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Cluster struct { + Id *string `json:"id,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Properties *ClusterProperties `json:"properties,omitempty"` + Sku *ClusterSku `json:"sku,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_clusterproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_clusterproperties.go new file mode 100644 index 000000000000..eb3deebdf90e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_clusterproperties.go @@ -0,0 +1,11 @@ +package eventhubsclusters + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ClusterProperties struct { + CreatedAt *string `json:"createdAt,omitempty"` + MetricId *string `json:"metricId,omitempty"` + Status *string `json:"status,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_clustersku.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_clustersku.go new file mode 100644 index 000000000000..aa0c7ea5e17b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/model_clustersku.go @@ -0,0 +1,9 @@ +package eventhubsclusters + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ClusterSku struct { + Capacity *int64 `json:"capacity,omitempty"` + Name ClusterSkuName `json:"name"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/predicates.go new file mode 100644 index 000000000000..7c63b56d238e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/predicates.go @@ -0,0 +1,29 @@ +package eventhubsclusters + +type ClusterOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p ClusterOperationPredicate) Matches(input Cluster) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && (input.Location == nil && *p.Location != *input.Location) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/version.go new file mode 100644 index 000000000000..daf742449a54 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters/version.go @@ -0,0 +1,12 @@ +package eventhubsclusters + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2018-01-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/eventhubsclusters/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/README.md new file mode 100644 index 000000000000..7928dadd74b1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/README.md @@ -0,0 +1,57 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets` Documentation + +The `networkrulesets` SDK allows for interaction with the Azure Resource Manager Service `eventhub` (API Version `2018-01-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets" +``` + + +### Client Initialization + +```go +client := networkrulesets.NewNetworkRuleSetsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `NetworkRuleSetsClient.NamespacesCreateOrUpdateNetworkRuleSet` + +```go +ctx := context.TODO() +id := networkrulesets.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +payload := networkrulesets.NetworkRuleSet{ + // ... +} + + +read, err := client.NamespacesCreateOrUpdateNetworkRuleSet(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NetworkRuleSetsClient.NamespacesGetNetworkRuleSet` + +```go +ctx := context.TODO() +id := networkrulesets.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +read, err := client.NamespacesGetNetworkRuleSet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/client.go new file mode 100644 index 000000000000..3182f271e9c1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/client.go @@ -0,0 +1,18 @@ +package networkrulesets + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NetworkRuleSetsClient struct { + Client autorest.Client + baseUri string +} + +func NewNetworkRuleSetsClientWithBaseURI(endpoint string) NetworkRuleSetsClient { + return NetworkRuleSetsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/constants.go new file mode 100644 index 000000000000..80c561aae4e5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/constants.go @@ -0,0 +1,59 @@ +package networkrulesets + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DefaultAction string + +const ( + DefaultActionAllow DefaultAction = "Allow" + DefaultActionDeny DefaultAction = "Deny" +) + +func PossibleValuesForDefaultAction() []string { + return []string{ + string(DefaultActionAllow), + string(DefaultActionDeny), + } +} + +func parseDefaultAction(input string) (*DefaultAction, error) { + vals := map[string]DefaultAction{ + "allow": DefaultActionAllow, + "deny": DefaultActionDeny, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := DefaultAction(input) + return &out, nil +} + +type NetworkRuleIPAction string + +const ( + NetworkRuleIPActionAllow NetworkRuleIPAction = "Allow" +) + +func PossibleValuesForNetworkRuleIPAction() []string { + return []string{ + string(NetworkRuleIPActionAllow), + } +} + +func parseNetworkRuleIPAction(input string) (*NetworkRuleIPAction, error) { + vals := map[string]NetworkRuleIPAction{ + "allow": NetworkRuleIPActionAllow, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := NetworkRuleIPAction(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/id_namespace.go new file mode 100644 index 000000000000..52801035472f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/id_namespace.go @@ -0,0 +1,124 @@ +package networkrulesets + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/method_namespacescreateorupdatenetworkruleset_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/method_namespacescreateorupdatenetworkruleset_autorest.go new file mode 100644 index 000000000000..91f087c1dd23 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/method_namespacescreateorupdatenetworkruleset_autorest.go @@ -0,0 +1,69 @@ +package networkrulesets + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesCreateOrUpdateNetworkRuleSetOperationResponse struct { + HttpResponse *http.Response + Model *NetworkRuleSet +} + +// NamespacesCreateOrUpdateNetworkRuleSet ... +func (c NetworkRuleSetsClient) NamespacesCreateOrUpdateNetworkRuleSet(ctx context.Context, id NamespaceId, input NetworkRuleSet) (result NamespacesCreateOrUpdateNetworkRuleSetOperationResponse, err error) { + req, err := c.preparerForNamespacesCreateOrUpdateNetworkRuleSet(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "networkrulesets.NetworkRuleSetsClient", "NamespacesCreateOrUpdateNetworkRuleSet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "networkrulesets.NetworkRuleSetsClient", "NamespacesCreateOrUpdateNetworkRuleSet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesCreateOrUpdateNetworkRuleSet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "networkrulesets.NetworkRuleSetsClient", "NamespacesCreateOrUpdateNetworkRuleSet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesCreateOrUpdateNetworkRuleSet prepares the NamespacesCreateOrUpdateNetworkRuleSet request. +func (c NetworkRuleSetsClient) preparerForNamespacesCreateOrUpdateNetworkRuleSet(ctx context.Context, id NamespaceId, input NetworkRuleSet) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/networkRuleSets/default", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesCreateOrUpdateNetworkRuleSet handles the response to the NamespacesCreateOrUpdateNetworkRuleSet request. The method always +// closes the http.Response Body. +func (c NetworkRuleSetsClient) responderForNamespacesCreateOrUpdateNetworkRuleSet(resp *http.Response) (result NamespacesCreateOrUpdateNetworkRuleSetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/method_namespacesgetnetworkruleset_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/method_namespacesgetnetworkruleset_autorest.go new file mode 100644 index 000000000000..10614c1302f0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/method_namespacesgetnetworkruleset_autorest.go @@ -0,0 +1,68 @@ +package networkrulesets + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesGetNetworkRuleSetOperationResponse struct { + HttpResponse *http.Response + Model *NetworkRuleSet +} + +// NamespacesGetNetworkRuleSet ... +func (c NetworkRuleSetsClient) NamespacesGetNetworkRuleSet(ctx context.Context, id NamespaceId) (result NamespacesGetNetworkRuleSetOperationResponse, err error) { + req, err := c.preparerForNamespacesGetNetworkRuleSet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "networkrulesets.NetworkRuleSetsClient", "NamespacesGetNetworkRuleSet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "networkrulesets.NetworkRuleSetsClient", "NamespacesGetNetworkRuleSet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesGetNetworkRuleSet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "networkrulesets.NetworkRuleSetsClient", "NamespacesGetNetworkRuleSet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesGetNetworkRuleSet prepares the NamespacesGetNetworkRuleSet request. +func (c NetworkRuleSetsClient) preparerForNamespacesGetNetworkRuleSet(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/networkRuleSets/default", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesGetNetworkRuleSet handles the response to the NamespacesGetNetworkRuleSet request. The method always +// closes the http.Response Body. +func (c NetworkRuleSetsClient) responderForNamespacesGetNetworkRuleSet(resp *http.Response) (result NamespacesGetNetworkRuleSetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_networkruleset.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_networkruleset.go new file mode 100644 index 000000000000..18e12748b530 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_networkruleset.go @@ -0,0 +1,11 @@ +package networkrulesets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NetworkRuleSet struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *NetworkRuleSetProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_networkrulesetproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_networkrulesetproperties.go new file mode 100644 index 000000000000..3c2e96afd554 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_networkrulesetproperties.go @@ -0,0 +1,11 @@ +package networkrulesets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NetworkRuleSetProperties struct { + DefaultAction *DefaultAction `json:"defaultAction,omitempty"` + IpRules *[]NWRuleSetIpRules `json:"ipRules,omitempty"` + TrustedServiceAccessEnabled *bool `json:"trustedServiceAccessEnabled,omitempty"` + VirtualNetworkRules *[]NWRuleSetVirtualNetworkRules `json:"virtualNetworkRules,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_nwrulesetiprules.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_nwrulesetiprules.go new file mode 100644 index 000000000000..28a0ee5d4d50 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_nwrulesetiprules.go @@ -0,0 +1,9 @@ +package networkrulesets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NWRuleSetIpRules struct { + Action *NetworkRuleIPAction `json:"action,omitempty"` + IpMask *string `json:"ipMask,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_nwrulesetvirtualnetworkrules.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_nwrulesetvirtualnetworkrules.go new file mode 100644 index 000000000000..5a8c3ff0f519 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_nwrulesetvirtualnetworkrules.go @@ -0,0 +1,9 @@ +package networkrulesets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NWRuleSetVirtualNetworkRules struct { + IgnoreMissingVnetServiceEndpoint *bool `json:"ignoreMissingVnetServiceEndpoint,omitempty"` + Subnet *Subnet `json:"subnet,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_subnet.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_subnet.go new file mode 100644 index 000000000000..9a2cdbb0a873 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/model_subnet.go @@ -0,0 +1,8 @@ +package networkrulesets + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Subnet struct { + Id *string `json:"id,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/version.go new file mode 100644 index 000000000000..cc5a6df45134 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets/version.go @@ -0,0 +1,12 @@ +package networkrulesets + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2018-01-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/networkrulesets/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/README.md new file mode 100644 index 000000000000..9ff443c80cad --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/README.md @@ -0,0 +1,120 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces` Documentation + +The `namespaces` SDK allows for interaction with the Azure Resource Manager Service `eventhub` (API Version `2021-01-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces" +``` + + +### Client Initialization + +```go +client := namespaces.NewNamespacesClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `NamespacesClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +payload := namespaces.EHNamespace{ + // ... +} + + +if err := client.CreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `NamespacesClient.Delete` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +if err := client.DeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `NamespacesClient.Get` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NamespacesClient.List` + +```go +ctx := context.TODO() +id := namespaces.NewSubscriptionID() + +// alternatively `client.List(ctx, id)` can be used to do batched pagination +items, err := client.ListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `NamespacesClient.ListByResourceGroup` + +```go +ctx := context.TODO() +id := namespaces.NewResourceGroupID() + +// alternatively `client.ListByResourceGroup(ctx, id)` can be used to do batched pagination +items, err := client.ListByResourceGroupComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `NamespacesClient.Update` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +payload := namespaces.EHNamespace{ + // ... +} + + +read, err := client.Update(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/client.go new file mode 100644 index 000000000000..bf25155c4194 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/client.go @@ -0,0 +1,18 @@ +package namespaces + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesClient struct { + Client autorest.Client + baseUri string +} + +func NewNamespacesClientWithBaseURI(endpoint string) NamespacesClient { + return NamespacesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/constants.go new file mode 100644 index 000000000000..6558e700ccbf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/constants.go @@ -0,0 +1,167 @@ +package namespaces + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EndPointProvisioningState string + +const ( + EndPointProvisioningStateCanceled EndPointProvisioningState = "Canceled" + EndPointProvisioningStateCreating EndPointProvisioningState = "Creating" + EndPointProvisioningStateDeleting EndPointProvisioningState = "Deleting" + EndPointProvisioningStateFailed EndPointProvisioningState = "Failed" + EndPointProvisioningStateSucceeded EndPointProvisioningState = "Succeeded" + EndPointProvisioningStateUpdating EndPointProvisioningState = "Updating" +) + +func PossibleValuesForEndPointProvisioningState() []string { + return []string{ + string(EndPointProvisioningStateCanceled), + string(EndPointProvisioningStateCreating), + string(EndPointProvisioningStateDeleting), + string(EndPointProvisioningStateFailed), + string(EndPointProvisioningStateSucceeded), + string(EndPointProvisioningStateUpdating), + } +} + +func parseEndPointProvisioningState(input string) (*EndPointProvisioningState, error) { + vals := map[string]EndPointProvisioningState{ + "canceled": EndPointProvisioningStateCanceled, + "creating": EndPointProvisioningStateCreating, + "deleting": EndPointProvisioningStateDeleting, + "failed": EndPointProvisioningStateFailed, + "succeeded": EndPointProvisioningStateSucceeded, + "updating": EndPointProvisioningStateUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EndPointProvisioningState(input) + return &out, nil +} + +type KeySource string + +const ( + KeySourceMicrosoftPointKeyVault KeySource = "Microsoft.KeyVault" +) + +func PossibleValuesForKeySource() []string { + return []string{ + string(KeySourceMicrosoftPointKeyVault), + } +} + +func parseKeySource(input string) (*KeySource, error) { + vals := map[string]KeySource{ + "microsoft.keyvault": KeySourceMicrosoftPointKeyVault, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeySource(input) + return &out, nil +} + +type PrivateLinkConnectionStatus string + +const ( + PrivateLinkConnectionStatusApproved PrivateLinkConnectionStatus = "Approved" + PrivateLinkConnectionStatusDisconnected PrivateLinkConnectionStatus = "Disconnected" + PrivateLinkConnectionStatusPending PrivateLinkConnectionStatus = "Pending" + PrivateLinkConnectionStatusRejected PrivateLinkConnectionStatus = "Rejected" +) + +func PossibleValuesForPrivateLinkConnectionStatus() []string { + return []string{ + string(PrivateLinkConnectionStatusApproved), + string(PrivateLinkConnectionStatusDisconnected), + string(PrivateLinkConnectionStatusPending), + string(PrivateLinkConnectionStatusRejected), + } +} + +func parsePrivateLinkConnectionStatus(input string) (*PrivateLinkConnectionStatus, error) { + vals := map[string]PrivateLinkConnectionStatus{ + "approved": PrivateLinkConnectionStatusApproved, + "disconnected": PrivateLinkConnectionStatusDisconnected, + "pending": PrivateLinkConnectionStatusPending, + "rejected": PrivateLinkConnectionStatusRejected, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := PrivateLinkConnectionStatus(input) + return &out, nil +} + +type SkuName string + +const ( + SkuNameBasic SkuName = "Basic" + SkuNamePremium SkuName = "Premium" + SkuNameStandard SkuName = "Standard" +) + +func PossibleValuesForSkuName() []string { + return []string{ + string(SkuNameBasic), + string(SkuNamePremium), + string(SkuNameStandard), + } +} + +func parseSkuName(input string) (*SkuName, error) { + vals := map[string]SkuName{ + "basic": SkuNameBasic, + "premium": SkuNamePremium, + "standard": SkuNameStandard, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := SkuName(input) + return &out, nil +} + +type SkuTier string + +const ( + SkuTierBasic SkuTier = "Basic" + SkuTierPremium SkuTier = "Premium" + SkuTierStandard SkuTier = "Standard" +) + +func PossibleValuesForSkuTier() []string { + return []string{ + string(SkuTierBasic), + string(SkuTierPremium), + string(SkuTierStandard), + } +} + +func parseSkuTier(input string) (*SkuTier, error) { + vals := map[string]SkuTier{ + "basic": SkuTierBasic, + "premium": SkuTierPremium, + "standard": SkuTierStandard, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := SkuTier(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/id_namespace.go new file mode 100644 index 000000000000..dba614cfaf0d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/id_namespace.go @@ -0,0 +1,124 @@ +package namespaces + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftEventHub", "Microsoft.EventHub", "Microsoft.EventHub"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_createorupdate_autorest.go new file mode 100644 index 000000000000..44e30b453dbf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_createorupdate_autorest.go @@ -0,0 +1,79 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CreateOrUpdate ... +func (c NamespacesClient) CreateOrUpdate(ctx context.Context, id NamespaceId, input EHNamespace) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CreateOrUpdateThenPoll performs CreateOrUpdate then polls until it's completed +func (c NamespacesClient) CreateOrUpdateThenPoll(ctx context.Context, id NamespaceId, input EHNamespace) error { + result, err := c.CreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing CreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c NamespacesClient) preparerForCreateOrUpdate(ctx context.Context, id NamespaceId, input EHNamespace) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCreateOrUpdate sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c NamespacesClient) senderForCreateOrUpdate(ctx context.Context, req *http.Request) (future CreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_delete_autorest.go new file mode 100644 index 000000000000..968dfe754f22 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_delete_autorest.go @@ -0,0 +1,78 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Delete ... +func (c NamespacesClient) Delete(ctx context.Context, id NamespaceId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = c.senderForDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// DeleteThenPoll performs Delete then polls until it's completed +func (c NamespacesClient) DeleteThenPoll(ctx context.Context, id NamespaceId) error { + result, err := c.Delete(ctx, id) + if err != nil { + return fmt.Errorf("performing Delete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Delete: %+v", err) + } + + return nil +} + +// preparerForDelete prepares the Delete request. +func (c NamespacesClient) preparerForDelete(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForDelete sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (c NamespacesClient) senderForDelete(ctx context.Context, req *http.Request) (future DeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_get_autorest.go new file mode 100644 index 000000000000..b1c33b953b22 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_get_autorest.go @@ -0,0 +1,67 @@ +package namespaces + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *EHNamespace +} + +// Get ... +func (c NamespacesClient) Get(ctx context.Context, id NamespaceId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c NamespacesClient) preparerForGet(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_list_autorest.go new file mode 100644 index 000000000000..ccd84c360fc6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_list_autorest.go @@ -0,0 +1,187 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *[]EHNamespace + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) +} + +type ListCompleteResult struct { + Items []EHNamespace +} + +func (r ListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// List ... +func (c NamespacesClient) List(ctx context.Context, id commonids.SubscriptionId) (resp ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListComplete retrieves all of the results into a single object +func (c NamespacesClient) ListComplete(ctx context.Context, id commonids.SubscriptionId) (ListCompleteResult, error) { + return c.ListCompleteMatchingPredicate(ctx, id, EHNamespaceOperationPredicate{}) +} + +// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c NamespacesClient) ListCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate EHNamespaceOperationPredicate) (resp ListCompleteResult, err error) { + items := make([]EHNamespace, 0) + + page, err := c.List(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForList prepares the List request. +func (c NamespacesClient) preparerForList(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.EventHub/namespaces", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListWithNextLink prepares the List request with the given nextLink token. +func (c NamespacesClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + type page struct { + Values []EHNamespace `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { + req, err := c.preparerForListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_listbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_listbyresourcegroup_autorest.go new file mode 100644 index 000000000000..99c00b6ad9d6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_listbyresourcegroup_autorest.go @@ -0,0 +1,187 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]EHNamespace + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByResourceGroupOperationResponse, error) +} + +type ListByResourceGroupCompleteResult struct { + Items []EHNamespace +} + +func (r ListByResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ListByResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListByResourceGroup ... +func (c NamespacesClient) ListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByResourceGroupComplete retrieves all of the results into a single object +func (c NamespacesClient) ListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ListByResourceGroupCompleteResult, error) { + return c.ListByResourceGroupCompleteMatchingPredicate(ctx, id, EHNamespaceOperationPredicate{}) +} + +// ListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c NamespacesClient) ListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate EHNamespaceOperationPredicate) (resp ListByResourceGroupCompleteResult, err error) { + items := make([]EHNamespace, 0) + + page, err := c.ListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByResourceGroup prepares the ListByResourceGroup request. +func (c NamespacesClient) preparerForListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.EventHub/namespaces", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByResourceGroupWithNextLink prepares the ListByResourceGroup request with the given nextLink token. +func (c NamespacesClient) preparerForListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByResourceGroup handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForListByResourceGroup(resp *http.Response) (result ListByResourceGroupOperationResponse, err error) { + type page struct { + Values []EHNamespace `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_update_autorest.go new file mode 100644 index 000000000000..c54d6ff8d8d0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/method_update_autorest.go @@ -0,0 +1,68 @@ +package namespaces + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + HttpResponse *http.Response + Model *EHNamespace +} + +// Update ... +func (c NamespacesClient) Update(ctx context.Context, id NamespaceId, input EHNamespace) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Update", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Update", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForUpdate prepares the Update request. +func (c NamespacesClient) preparerForUpdate(ctx context.Context, id NamespaceId, input EHNamespace) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForUpdate handles the response to the Update request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForUpdate(resp *http.Response) (result UpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_connectionstate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_connectionstate.go new file mode 100644 index 000000000000..022aa980debf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_connectionstate.go @@ -0,0 +1,9 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConnectionState struct { + Description *string `json:"description,omitempty"` + Status *PrivateLinkConnectionStatus `json:"status,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_ehnamespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_ehnamespace.go new file mode 100644 index 000000000000..17819eb7bf04 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_ehnamespace.go @@ -0,0 +1,21 @@ +package namespaces + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EHNamespace struct { + Id *string `json:"id,omitempty"` + Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Properties *EHNamespaceProperties `json:"properties,omitempty"` + Sku *Sku `json:"sku,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_ehnamespaceproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_ehnamespaceproperties.go new file mode 100644 index 000000000000..d24af1b62e7f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_ehnamespaceproperties.go @@ -0,0 +1,50 @@ +package namespaces + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EHNamespaceProperties struct { + ClusterArmId *string `json:"clusterArmId,omitempty"` + CreatedAt *string `json:"createdAt,omitempty"` + Encryption *Encryption `json:"encryption,omitempty"` + IsAutoInflateEnabled *bool `json:"isAutoInflateEnabled,omitempty"` + KafkaEnabled *bool `json:"kafkaEnabled,omitempty"` + MaximumThroughputUnits *int64 `json:"maximumThroughputUnits,omitempty"` + MetricId *string `json:"metricId,omitempty"` + PrivateEndpointConnections *[]PrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + ServiceBusEndpoint *string `json:"serviceBusEndpoint,omitempty"` + Status *string `json:"status,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` + ZoneRedundant *bool `json:"zoneRedundant,omitempty"` +} + +func (o *EHNamespaceProperties) GetCreatedAtAsTime() (*time.Time, error) { + if o.CreatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *EHNamespaceProperties) SetCreatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedAt = &formatted +} + +func (o *EHNamespaceProperties) GetUpdatedAtAsTime() (*time.Time, error) { + if o.UpdatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.UpdatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *EHNamespaceProperties) SetUpdatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.UpdatedAt = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_encryption.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_encryption.go new file mode 100644 index 000000000000..c33fdbc6fad2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_encryption.go @@ -0,0 +1,10 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Encryption struct { + KeySource *KeySource `json:"keySource,omitempty"` + KeyVaultProperties *[]KeyVaultProperties `json:"keyVaultProperties,omitempty"` + RequireInfrastructureEncryption *bool `json:"requireInfrastructureEncryption,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_keyvaultproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_keyvaultproperties.go new file mode 100644 index 000000000000..b0dfb9a4e063 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_keyvaultproperties.go @@ -0,0 +1,11 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type KeyVaultProperties struct { + Identity *UserAssignedIdentityProperties `json:"identity,omitempty"` + KeyName *string `json:"keyName,omitempty"` + KeyVaultUri *string `json:"keyVaultUri,omitempty"` + KeyVersion *string `json:"keyVersion,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpoint.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpoint.go new file mode 100644 index 000000000000..3dec0387e5f1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpoint.go @@ -0,0 +1,8 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpoint struct { + Id *string `json:"id,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpointconnection.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpointconnection.go new file mode 100644 index 000000000000..d60671cf999e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpointconnection.go @@ -0,0 +1,16 @@ +package namespaces + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnection struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *PrivateEndpointConnectionProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpointconnectionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpointconnectionproperties.go new file mode 100644 index 000000000000..e0aa15c59571 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_privateendpointconnectionproperties.go @@ -0,0 +1,10 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionProperties struct { + PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` + PrivateLinkServiceConnectionState *ConnectionState `json:"privateLinkServiceConnectionState,omitempty"` + ProvisioningState *EndPointProvisioningState `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_sku.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_sku.go new file mode 100644 index 000000000000..909b599f1389 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_sku.go @@ -0,0 +1,10 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Sku struct { + Capacity *int64 `json:"capacity,omitempty"` + Name SkuName `json:"name"` + Tier *SkuTier `json:"tier,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_userassignedidentityproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_userassignedidentityproperties.go new file mode 100644 index 000000000000..0685aa3ea141 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/model_userassignedidentityproperties.go @@ -0,0 +1,8 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UserAssignedIdentityProperties struct { + UserAssignedIdentity *string `json:"userAssignedIdentity,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/predicates.go new file mode 100644 index 000000000000..da2e3acefe1a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/predicates.go @@ -0,0 +1,29 @@ +package namespaces + +type EHNamespaceOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p EHNamespaceOperationPredicate) Matches(input EHNamespace) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && (input.Location == nil && *p.Location != *input.Location) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/version.go new file mode 100644 index 000000000000..181d6ba1025b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces/version.go @@ -0,0 +1,12 @@ +package namespaces + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-01-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/namespaces/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/README.md new file mode 100644 index 000000000000..1890f15a0c97 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/README.md @@ -0,0 +1,181 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers` Documentation + +The `fluidrelayservers` SDK allows for interaction with the Azure Resource Manager Service `fluidrelay` (API Version `2022-05-26`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers" +``` + + +### Client Initialization + +```go +client := fluidrelayservers.NewFluidRelayServersClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `FluidRelayServersClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := fluidrelayservers.NewFluidRelayServerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "fluidRelayServerValue") + +payload := fluidrelayservers.FluidRelayServer{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `FluidRelayServersClient.Delete` + +```go +ctx := context.TODO() +id := fluidrelayservers.NewFluidRelayServerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "fluidRelayServerValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `FluidRelayServersClient.Get` + +```go +ctx := context.TODO() +id := fluidrelayservers.NewFluidRelayServerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "fluidRelayServerValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `FluidRelayServersClient.GetKeys` + +```go +ctx := context.TODO() +id := fluidrelayservers.NewFluidRelayServerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "fluidRelayServerValue") + +read, err := client.GetKeys(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `FluidRelayServersClient.ListByResourceGroup` + +```go +ctx := context.TODO() +id := fluidrelayservers.NewResourceGroupID() + +// alternatively `client.ListByResourceGroup(ctx, id)` can be used to do batched pagination +items, err := client.ListByResourceGroupComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `FluidRelayServersClient.ListBySubscription` + +```go +ctx := context.TODO() +id := fluidrelayservers.NewSubscriptionID() + +// alternatively `client.ListBySubscription(ctx, id)` can be used to do batched pagination +items, err := client.ListBySubscriptionComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `FluidRelayServersClient.ListKeys` + +```go +ctx := context.TODO() +id := fluidrelayservers.NewFluidRelayServerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "fluidRelayServerValue") + +read, err := client.ListKeys(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `FluidRelayServersClient.RegenerateKey` + +```go +ctx := context.TODO() +id := fluidrelayservers.NewFluidRelayServerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "fluidRelayServerValue") + +payload := fluidrelayservers.RegenerateKeyRequest{ + // ... +} + + +read, err := client.RegenerateKey(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `FluidRelayServersClient.Update` + +```go +ctx := context.TODO() +id := fluidrelayservers.NewFluidRelayServerID("12345678-1234-9876-4563-123456789012", "example-resource-group", "fluidRelayServerValue") + +payload := fluidrelayservers.FluidRelayServerUpdate{ + // ... +} + + +read, err := client.Update(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/client.go new file mode 100644 index 000000000000..bd29abddd025 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/client.go @@ -0,0 +1,18 @@ +package fluidrelayservers + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FluidRelayServersClient struct { + Client autorest.Client + baseUri string +} + +func NewFluidRelayServersClientWithBaseURI(endpoint string) FluidRelayServersClient { + return FluidRelayServersClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/constants.go new file mode 100644 index 000000000000..1d0e44d42c6b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/constants.go @@ -0,0 +1,121 @@ +package fluidrelayservers + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CmkIdentityType string + +const ( + CmkIdentityTypeSystemAssigned CmkIdentityType = "SystemAssigned" + CmkIdentityTypeUserAssigned CmkIdentityType = "UserAssigned" +) + +func PossibleValuesForCmkIdentityType() []string { + return []string{ + string(CmkIdentityTypeSystemAssigned), + string(CmkIdentityTypeUserAssigned), + } +} + +func parseCmkIdentityType(input string) (*CmkIdentityType, error) { + vals := map[string]CmkIdentityType{ + "systemassigned": CmkIdentityTypeSystemAssigned, + "userassigned": CmkIdentityTypeUserAssigned, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := CmkIdentityType(input) + return &out, nil +} + +type KeyName string + +const ( + KeyNameKeyOne KeyName = "key1" + KeyNameKeyTwo KeyName = "key2" +) + +func PossibleValuesForKeyName() []string { + return []string{ + string(KeyNameKeyOne), + string(KeyNameKeyTwo), + } +} + +func parseKeyName(input string) (*KeyName, error) { + vals := map[string]KeyName{ + "key1": KeyNameKeyOne, + "key2": KeyNameKeyTwo, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeyName(input) + return &out, nil +} + +type ProvisioningState string + +const ( + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +func PossibleValuesForProvisioningState() []string { + return []string{ + string(ProvisioningStateCanceled), + string(ProvisioningStateFailed), + string(ProvisioningStateSucceeded), + } +} + +func parseProvisioningState(input string) (*ProvisioningState, error) { + vals := map[string]ProvisioningState{ + "canceled": ProvisioningStateCanceled, + "failed": ProvisioningStateFailed, + "succeeded": ProvisioningStateSucceeded, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ProvisioningState(input) + return &out, nil +} + +type StorageSKU string + +const ( + StorageSKUBasic StorageSKU = "basic" + StorageSKUStandard StorageSKU = "standard" +) + +func PossibleValuesForStorageSKU() []string { + return []string{ + string(StorageSKUBasic), + string(StorageSKUStandard), + } +} + +func parseStorageSKU(input string) (*StorageSKU, error) { + vals := map[string]StorageSKU{ + "basic": StorageSKUBasic, + "standard": StorageSKUStandard, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := StorageSKU(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/id_fluidrelayserver.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/id_fluidrelayserver.go new file mode 100644 index 000000000000..bc41376a2926 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/id_fluidrelayserver.go @@ -0,0 +1,124 @@ +package fluidrelayservers + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = FluidRelayServerId{} + +// FluidRelayServerId is a struct representing the Resource ID for a Fluid Relay Server +type FluidRelayServerId struct { + SubscriptionId string + ResourceGroup string + FluidRelayServerName string +} + +// NewFluidRelayServerID returns a new FluidRelayServerId struct +func NewFluidRelayServerID(subscriptionId string, resourceGroup string, fluidRelayServerName string) FluidRelayServerId { + return FluidRelayServerId{ + SubscriptionId: subscriptionId, + ResourceGroup: resourceGroup, + FluidRelayServerName: fluidRelayServerName, + } +} + +// ParseFluidRelayServerID parses 'input' into a FluidRelayServerId +func ParseFluidRelayServerID(input string) (*FluidRelayServerId, error) { + parser := resourceids.NewParserFromResourceIdType(FluidRelayServerId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := FluidRelayServerId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroup, ok = parsed.Parsed["resourceGroup"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroup' was not found in the resource id %q", input) + } + + if id.FluidRelayServerName, ok = parsed.Parsed["fluidRelayServerName"]; !ok { + return nil, fmt.Errorf("the segment 'fluidRelayServerName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseFluidRelayServerIDInsensitively parses 'input' case-insensitively into a FluidRelayServerId +// note: this method should only be used for API response data and not user input +func ParseFluidRelayServerIDInsensitively(input string) (*FluidRelayServerId, error) { + parser := resourceids.NewParserFromResourceIdType(FluidRelayServerId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := FluidRelayServerId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroup, ok = parsed.Parsed["resourceGroup"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroup' was not found in the resource id %q", input) + } + + if id.FluidRelayServerName, ok = parsed.Parsed["fluidRelayServerName"]; !ok { + return nil, fmt.Errorf("the segment 'fluidRelayServerName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateFluidRelayServerID checks that 'input' can be parsed as a Fluid Relay Server ID +func ValidateFluidRelayServerID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseFluidRelayServerID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Fluid Relay Server ID +func (id FluidRelayServerId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.FluidRelay/fluidRelayServers/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.FluidRelayServerName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Fluid Relay Server ID +func (id FluidRelayServerId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroup", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftFluidRelay", "Microsoft.FluidRelay", "Microsoft.FluidRelay"), + resourceids.StaticSegment("staticFluidRelayServers", "fluidRelayServers", "fluidRelayServers"), + resourceids.UserSpecifiedSegment("fluidRelayServerName", "fluidRelayServerValue"), + } +} + +// String returns a human-readable description of this Fluid Relay Server ID +func (id FluidRelayServerId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group: %q", id.ResourceGroup), + fmt.Sprintf("Fluid Relay Server Name: %q", id.FluidRelayServerName), + } + return fmt.Sprintf("Fluid Relay Server (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_createorupdate_autorest.go new file mode 100644 index 000000000000..3e71fc66c650 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package fluidrelayservers + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *FluidRelayServer +} + +// CreateOrUpdate ... +func (c FluidRelayServersClient) CreateOrUpdate(ctx context.Context, id FluidRelayServerId, input FluidRelayServer) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c FluidRelayServersClient) preparerForCreateOrUpdate(ctx context.Context, id FluidRelayServerId, input FluidRelayServer) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c FluidRelayServersClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_delete_autorest.go new file mode 100644 index 000000000000..bb7ba2ba3c82 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_delete_autorest.go @@ -0,0 +1,65 @@ +package fluidrelayservers + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c FluidRelayServersClient) Delete(ctx context.Context, id FluidRelayServerId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c FluidRelayServersClient) preparerForDelete(ctx context.Context, id FluidRelayServerId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c FluidRelayServersClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_get_autorest.go new file mode 100644 index 000000000000..c58a5785cd9a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_get_autorest.go @@ -0,0 +1,67 @@ +package fluidrelayservers + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *FluidRelayServer +} + +// Get ... +func (c FluidRelayServersClient) Get(ctx context.Context, id FluidRelayServerId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c FluidRelayServersClient) preparerForGet(ctx context.Context, id FluidRelayServerId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c FluidRelayServersClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_getkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_getkeys_autorest.go new file mode 100644 index 000000000000..5f3be4b813ed --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_getkeys_autorest.go @@ -0,0 +1,68 @@ +package fluidrelayservers + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetKeysOperationResponse struct { + HttpResponse *http.Response + Model *FluidRelayServerKeys +} + +// GetKeys ... +func (c FluidRelayServersClient) GetKeys(ctx context.Context, id FluidRelayServerId) (result GetKeysOperationResponse, err error) { + req, err := c.preparerForGetKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "GetKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "GetKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGetKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "GetKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGetKeys prepares the GetKeys request. +func (c FluidRelayServersClient) preparerForGetKeys(ctx context.Context, id FluidRelayServerId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/getKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGetKeys handles the response to the GetKeys request. The method always +// closes the http.Response Body. +func (c FluidRelayServersClient) responderForGetKeys(resp *http.Response) (result GetKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listbyresourcegroup_autorest.go new file mode 100644 index 000000000000..8579dfa5bca6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listbyresourcegroup_autorest.go @@ -0,0 +1,187 @@ +package fluidrelayservers + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]FluidRelayServer + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByResourceGroupOperationResponse, error) +} + +type ListByResourceGroupCompleteResult struct { + Items []FluidRelayServer +} + +func (r ListByResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ListByResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListByResourceGroup ... +func (c FluidRelayServersClient) ListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByResourceGroupComplete retrieves all of the results into a single object +func (c FluidRelayServersClient) ListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ListByResourceGroupCompleteResult, error) { + return c.ListByResourceGroupCompleteMatchingPredicate(ctx, id, FluidRelayServerOperationPredicate{}) +} + +// ListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c FluidRelayServersClient) ListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate FluidRelayServerOperationPredicate) (resp ListByResourceGroupCompleteResult, err error) { + items := make([]FluidRelayServer, 0) + + page, err := c.ListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByResourceGroup prepares the ListByResourceGroup request. +func (c FluidRelayServersClient) preparerForListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.FluidRelay/fluidRelayServers", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByResourceGroupWithNextLink prepares the ListByResourceGroup request with the given nextLink token. +func (c FluidRelayServersClient) preparerForListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByResourceGroup handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (c FluidRelayServersClient) responderForListByResourceGroup(resp *http.Response) (result ListByResourceGroupOperationResponse, err error) { + type page struct { + Values []FluidRelayServer `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listbysubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listbysubscription_autorest.go new file mode 100644 index 000000000000..1386b52cadc9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listbysubscription_autorest.go @@ -0,0 +1,187 @@ +package fluidrelayservers + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListBySubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *[]FluidRelayServer + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListBySubscriptionOperationResponse, error) +} + +type ListBySubscriptionCompleteResult struct { + Items []FluidRelayServer +} + +func (r ListBySubscriptionOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListBySubscriptionOperationResponse) LoadMore(ctx context.Context) (resp ListBySubscriptionOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListBySubscription ... +func (c FluidRelayServersClient) ListBySubscription(ctx context.Context, id commonids.SubscriptionId) (resp ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscription(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListBySubscription", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListBySubscription(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListBySubscription", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListBySubscriptionComplete retrieves all of the results into a single object +func (c FluidRelayServersClient) ListBySubscriptionComplete(ctx context.Context, id commonids.SubscriptionId) (ListBySubscriptionCompleteResult, error) { + return c.ListBySubscriptionCompleteMatchingPredicate(ctx, id, FluidRelayServerOperationPredicate{}) +} + +// ListBySubscriptionCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c FluidRelayServersClient) ListBySubscriptionCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate FluidRelayServerOperationPredicate) (resp ListBySubscriptionCompleteResult, err error) { + items := make([]FluidRelayServer, 0) + + page, err := c.ListBySubscription(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListBySubscriptionCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListBySubscription prepares the ListBySubscription request. +func (c FluidRelayServersClient) preparerForListBySubscription(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.FluidRelay/fluidRelayServers", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListBySubscriptionWithNextLink prepares the ListBySubscription request with the given nextLink token. +func (c FluidRelayServersClient) preparerForListBySubscriptionWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListBySubscription handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (c FluidRelayServersClient) responderForListBySubscription(resp *http.Response) (result ListBySubscriptionOperationResponse, err error) { + type page struct { + Values []FluidRelayServer `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscriptionWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListBySubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListBySubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListBySubscription", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listkeys_autorest.go new file mode 100644 index 000000000000..e50e87e63cb0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_listkeys_autorest.go @@ -0,0 +1,68 @@ +package fluidrelayservers + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListKeysOperationResponse struct { + HttpResponse *http.Response + Model *FluidRelayServerKeys +} + +// ListKeys ... +func (c FluidRelayServersClient) ListKeys(ctx context.Context, id FluidRelayServerId) (result ListKeysOperationResponse, err error) { + req, err := c.preparerForListKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "ListKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForListKeys prepares the ListKeys request. +func (c FluidRelayServersClient) preparerForListKeys(ctx context.Context, id FluidRelayServerId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListKeys handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (c FluidRelayServersClient) responderForListKeys(resp *http.Response) (result ListKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_regeneratekey_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_regeneratekey_autorest.go new file mode 100644 index 000000000000..aca471923ef9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_regeneratekey_autorest.go @@ -0,0 +1,69 @@ +package fluidrelayservers + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateKeyOperationResponse struct { + HttpResponse *http.Response + Model *FluidRelayServerKeys +} + +// RegenerateKey ... +func (c FluidRelayServersClient) RegenerateKey(ctx context.Context, id FluidRelayServerId, input RegenerateKeyRequest) (result RegenerateKeyOperationResponse, err error) { + req, err := c.preparerForRegenerateKey(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "RegenerateKey", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "RegenerateKey", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRegenerateKey(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "RegenerateKey", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRegenerateKey prepares the RegenerateKey request. +func (c FluidRelayServersClient) preparerForRegenerateKey(ctx context.Context, id FluidRelayServerId, input RegenerateKeyRequest) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/regenerateKey", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRegenerateKey handles the response to the RegenerateKey request. The method always +// closes the http.Response Body. +func (c FluidRelayServersClient) responderForRegenerateKey(resp *http.Response) (result RegenerateKeyOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_update_autorest.go new file mode 100644 index 000000000000..150d7a9ed77b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/method_update_autorest.go @@ -0,0 +1,68 @@ +package fluidrelayservers + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + HttpResponse *http.Response + Model *FluidRelayServer +} + +// Update ... +func (c FluidRelayServersClient) Update(ctx context.Context, id FluidRelayServerId, input FluidRelayServerUpdate) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "Update", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "fluidrelayservers.FluidRelayServersClient", "Update", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForUpdate prepares the Update request. +func (c FluidRelayServersClient) preparerForUpdate(ctx context.Context, id FluidRelayServerId, input FluidRelayServerUpdate) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForUpdate handles the response to the Update request. The method always +// closes the http.Response Body. +func (c FluidRelayServersClient) responderForUpdate(resp *http.Response) (result UpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_customermanagedkeyencryptionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_customermanagedkeyencryptionproperties.go new file mode 100644 index 000000000000..c901b57f9097 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_customermanagedkeyencryptionproperties.go @@ -0,0 +1,9 @@ +package fluidrelayservers + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomerManagedKeyEncryptionProperties struct { + KeyEncryptionKeyIdentity *CustomerManagedKeyEncryptionPropertiesKeyEncryptionKeyIdentity `json:"keyEncryptionKeyIdentity,omitempty"` + KeyEncryptionKeyUrl *string `json:"keyEncryptionKeyUrl,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_customermanagedkeyencryptionpropertieskeyencryptionkeyidentity.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_customermanagedkeyencryptionpropertieskeyencryptionkeyidentity.go new file mode 100644 index 000000000000..a14936a4cb8a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_customermanagedkeyencryptionpropertieskeyencryptionkeyidentity.go @@ -0,0 +1,9 @@ +package fluidrelayservers + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomerManagedKeyEncryptionPropertiesKeyEncryptionKeyIdentity struct { + IdentityType *CmkIdentityType `json:"identityType,omitempty"` + UserAssignedIdentityResourceId *string `json:"userAssignedIdentityResourceId,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_encryptionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_encryptionproperties.go new file mode 100644 index 000000000000..ebb20890ac63 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_encryptionproperties.go @@ -0,0 +1,8 @@ +package fluidrelayservers + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EncryptionProperties struct { + CustomerManagedKeyEncryption *CustomerManagedKeyEncryptionProperties `json:"customerManagedKeyEncryption,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayendpoints.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayendpoints.go new file mode 100644 index 000000000000..7d6f78c08fbd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayendpoints.go @@ -0,0 +1,10 @@ +package fluidrelayservers + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FluidRelayEndpoints struct { + OrdererEndpoints *[]string `json:"ordererEndpoints,omitempty"` + ServiceEndpoints *[]string `json:"serviceEndpoints,omitempty"` + StorageEndpoints *[]string `json:"storageEndpoints,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserver.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserver.go new file mode 100644 index 000000000000..2295c002065a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserver.go @@ -0,0 +1,20 @@ +package fluidrelayservers + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FluidRelayServer struct { + Id *string `json:"id,omitempty"` + Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties *FluidRelayServerProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverkeys.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverkeys.go new file mode 100644 index 000000000000..d70edabd7a0e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverkeys.go @@ -0,0 +1,9 @@ +package fluidrelayservers + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FluidRelayServerKeys struct { + Key1 *string `json:"key1,omitempty"` + Key2 *string `json:"key2,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverproperties.go new file mode 100644 index 000000000000..1c430eab5e3c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverproperties.go @@ -0,0 +1,12 @@ +package fluidrelayservers + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FluidRelayServerProperties struct { + Encryption *EncryptionProperties `json:"encryption,omitempty"` + FluidRelayEndpoints *FluidRelayEndpoints `json:"fluidRelayEndpoints,omitempty"` + FrsTenantId *string `json:"frsTenantId,omitempty"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` + Storagesku *StorageSKU `json:"storagesku,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverupdate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverupdate.go new file mode 100644 index 000000000000..51e0c55443ff --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverupdate.go @@ -0,0 +1,15 @@ +package fluidrelayservers + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FluidRelayServerUpdate struct { + Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` + Location *string `json:"location,omitempty"` + Properties *FluidRelayServerUpdateProperties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverupdateproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverupdateproperties.go new file mode 100644 index 000000000000..d150ca43a28c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_fluidrelayserverupdateproperties.go @@ -0,0 +1,8 @@ +package fluidrelayservers + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FluidRelayServerUpdateProperties struct { + Encryption *EncryptionProperties `json:"encryption,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_regeneratekeyrequest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_regeneratekeyrequest.go new file mode 100644 index 000000000000..1aad29b69943 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/model_regeneratekeyrequest.go @@ -0,0 +1,8 @@ +package fluidrelayservers + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateKeyRequest struct { + KeyName KeyName `json:"keyName"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/predicates.go new file mode 100644 index 000000000000..e618e42269b5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/predicates.go @@ -0,0 +1,29 @@ +package fluidrelayservers + +type FluidRelayServerOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p FluidRelayServerOperationPredicate) Matches(input FluidRelayServer) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/version.go new file mode 100644 index 000000000000..7664a0458cc0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers/version.go @@ -0,0 +1,12 @@ +package fluidrelayservers + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2022-05-26" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/fluidrelayservers/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/README.md new file mode 100644 index 000000000000..74a7fd3d66a7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/README.md @@ -0,0 +1,82 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments` Documentation + +The `registrationassignments` SDK allows for interaction with the Azure Resource Manager Service `managedservices` (API Version `2019-06-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments" +``` + + +### Client Initialization + +```go +client := registrationassignments.NewRegistrationAssignmentsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `RegistrationAssignmentsClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := registrationassignments.NewScopedRegistrationAssignmentID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "registrationAssignmentIdValue") + +payload := registrationassignments.RegistrationAssignment{ + // ... +} + + +if err := client.CreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `RegistrationAssignmentsClient.Delete` + +```go +ctx := context.TODO() +id := registrationassignments.NewScopedRegistrationAssignmentID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "registrationAssignmentIdValue") + +if err := client.DeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `RegistrationAssignmentsClient.Get` + +```go +ctx := context.TODO() +id := registrationassignments.NewScopedRegistrationAssignmentID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "registrationAssignmentIdValue") + +read, err := client.Get(ctx, id, registrationassignments.DefaultGetOperationOptions()) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `RegistrationAssignmentsClient.List` + +```go +ctx := context.TODO() +id := registrationassignments.NewScopeID() + +// alternatively `client.List(ctx, id, registrationassignments.DefaultListOperationOptions())` can be used to do batched pagination +items, err := client.ListComplete(ctx, id, registrationassignments.DefaultListOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/client.go new file mode 100644 index 000000000000..e565c9276511 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/client.go @@ -0,0 +1,18 @@ +package registrationassignments + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegistrationAssignmentsClient struct { + Client autorest.Client + baseUri string +} + +func NewRegistrationAssignmentsClientWithBaseURI(endpoint string) RegistrationAssignmentsClient { + return RegistrationAssignmentsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/constants.go new file mode 100644 index 000000000000..401dbb8e28ea --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/constants.go @@ -0,0 +1,64 @@ +package registrationassignments + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ProvisioningState string + +const ( + ProvisioningStateAccepted ProvisioningState = "Accepted" + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateCreated ProvisioningState = "Created" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateDeleted ProvisioningState = "Deleted" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateNotSpecified ProvisioningState = "NotSpecified" + ProvisioningStateReady ProvisioningState = "Ready" + ProvisioningStateRunning ProvisioningState = "Running" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +func PossibleValuesForProvisioningState() []string { + return []string{ + string(ProvisioningStateAccepted), + string(ProvisioningStateCanceled), + string(ProvisioningStateCreated), + string(ProvisioningStateCreating), + string(ProvisioningStateDeleted), + string(ProvisioningStateDeleting), + string(ProvisioningStateFailed), + string(ProvisioningStateNotSpecified), + string(ProvisioningStateReady), + string(ProvisioningStateRunning), + string(ProvisioningStateSucceeded), + string(ProvisioningStateUpdating), + } +} + +func parseProvisioningState(input string) (*ProvisioningState, error) { + vals := map[string]ProvisioningState{ + "accepted": ProvisioningStateAccepted, + "canceled": ProvisioningStateCanceled, + "created": ProvisioningStateCreated, + "creating": ProvisioningStateCreating, + "deleted": ProvisioningStateDeleted, + "deleting": ProvisioningStateDeleting, + "failed": ProvisioningStateFailed, + "notspecified": ProvisioningStateNotSpecified, + "ready": ProvisioningStateReady, + "running": ProvisioningStateRunning, + "succeeded": ProvisioningStateSucceeded, + "updating": ProvisioningStateUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ProvisioningState(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/id_scopedregistrationassignment.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/id_scopedregistrationassignment.go new file mode 100644 index 000000000000..d9e3fe30b3ad --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/id_scopedregistrationassignment.go @@ -0,0 +1,110 @@ +package registrationassignments + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ScopedRegistrationAssignmentId{} + +// ScopedRegistrationAssignmentId is a struct representing the Resource ID for a Scoped Registration Assignment +type ScopedRegistrationAssignmentId struct { + Scope string + RegistrationAssignmentId string +} + +// NewScopedRegistrationAssignmentID returns a new ScopedRegistrationAssignmentId struct +func NewScopedRegistrationAssignmentID(scope string, registrationAssignmentId string) ScopedRegistrationAssignmentId { + return ScopedRegistrationAssignmentId{ + Scope: scope, + RegistrationAssignmentId: registrationAssignmentId, + } +} + +// ParseScopedRegistrationAssignmentID parses 'input' into a ScopedRegistrationAssignmentId +func ParseScopedRegistrationAssignmentID(input string) (*ScopedRegistrationAssignmentId, error) { + parser := resourceids.NewParserFromResourceIdType(ScopedRegistrationAssignmentId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ScopedRegistrationAssignmentId{} + + if id.Scope, ok = parsed.Parsed["scope"]; !ok { + return nil, fmt.Errorf("the segment 'scope' was not found in the resource id %q", input) + } + + if id.RegistrationAssignmentId, ok = parsed.Parsed["registrationAssignmentId"]; !ok { + return nil, fmt.Errorf("the segment 'registrationAssignmentId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseScopedRegistrationAssignmentIDInsensitively parses 'input' case-insensitively into a ScopedRegistrationAssignmentId +// note: this method should only be used for API response data and not user input +func ParseScopedRegistrationAssignmentIDInsensitively(input string) (*ScopedRegistrationAssignmentId, error) { + parser := resourceids.NewParserFromResourceIdType(ScopedRegistrationAssignmentId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ScopedRegistrationAssignmentId{} + + if id.Scope, ok = parsed.Parsed["scope"]; !ok { + return nil, fmt.Errorf("the segment 'scope' was not found in the resource id %q", input) + } + + if id.RegistrationAssignmentId, ok = parsed.Parsed["registrationAssignmentId"]; !ok { + return nil, fmt.Errorf("the segment 'registrationAssignmentId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateScopedRegistrationAssignmentID checks that 'input' can be parsed as a Scoped Registration Assignment ID +func ValidateScopedRegistrationAssignmentID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseScopedRegistrationAssignmentID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Scoped Registration Assignment ID +func (id ScopedRegistrationAssignmentId) ID() string { + fmtString := "/%s/providers/Microsoft.ManagedServices/registrationAssignments/%s" + return fmt.Sprintf(fmtString, strings.TrimPrefix(id.Scope, "/"), id.RegistrationAssignmentId) +} + +// Segments returns a slice of Resource ID Segments which comprise this Scoped Registration Assignment ID +func (id ScopedRegistrationAssignmentId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.ScopeSegment("scope", "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftManagedServices", "Microsoft.ManagedServices", "Microsoft.ManagedServices"), + resourceids.StaticSegment("staticRegistrationAssignments", "registrationAssignments", "registrationAssignments"), + resourceids.UserSpecifiedSegment("registrationAssignmentId", "registrationAssignmentIdValue"), + } +} + +// String returns a human-readable description of this Scoped Registration Assignment ID +func (id ScopedRegistrationAssignmentId) String() string { + components := []string{ + fmt.Sprintf("Scope: %q", id.Scope), + fmt.Sprintf("Registration Assignment: %q", id.RegistrationAssignmentId), + } + return fmt.Sprintf("Scoped Registration Assignment (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_createorupdate_autorest.go new file mode 100644 index 000000000000..6887ce6d3217 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_createorupdate_autorest.go @@ -0,0 +1,79 @@ +package registrationassignments + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CreateOrUpdate ... +func (c RegistrationAssignmentsClient) CreateOrUpdate(ctx context.Context, id ScopedRegistrationAssignmentId, input RegistrationAssignment) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CreateOrUpdateThenPoll performs CreateOrUpdate then polls until it's completed +func (c RegistrationAssignmentsClient) CreateOrUpdateThenPoll(ctx context.Context, id ScopedRegistrationAssignmentId, input RegistrationAssignment) error { + result, err := c.CreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing CreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c RegistrationAssignmentsClient) preparerForCreateOrUpdate(ctx context.Context, id ScopedRegistrationAssignmentId, input RegistrationAssignment) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCreateOrUpdate sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c RegistrationAssignmentsClient) senderForCreateOrUpdate(ctx context.Context, req *http.Request) (future CreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_delete_autorest.go new file mode 100644 index 000000000000..68a0795ae443 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_delete_autorest.go @@ -0,0 +1,78 @@ +package registrationassignments + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Delete ... +func (c RegistrationAssignmentsClient) Delete(ctx context.Context, id ScopedRegistrationAssignmentId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = c.senderForDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// DeleteThenPoll performs Delete then polls until it's completed +func (c RegistrationAssignmentsClient) DeleteThenPoll(ctx context.Context, id ScopedRegistrationAssignmentId) error { + result, err := c.Delete(ctx, id) + if err != nil { + return fmt.Errorf("performing Delete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Delete: %+v", err) + } + + return nil +} + +// preparerForDelete prepares the Delete request. +func (c RegistrationAssignmentsClient) preparerForDelete(ctx context.Context, id ScopedRegistrationAssignmentId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForDelete sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (c RegistrationAssignmentsClient) senderForDelete(ctx context.Context, req *http.Request) (future DeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_get_autorest.go new file mode 100644 index 000000000000..6ddac3df29b3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_get_autorest.go @@ -0,0 +1,96 @@ +package registrationassignments + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *RegistrationAssignment +} + +type GetOperationOptions struct { + ExpandRegistrationDefinition *bool +} + +func DefaultGetOperationOptions() GetOperationOptions { + return GetOperationOptions{} +} + +func (o GetOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o GetOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.ExpandRegistrationDefinition != nil { + out["$expandRegistrationDefinition"] = *o.ExpandRegistrationDefinition + } + + return out +} + +// Get ... +func (c RegistrationAssignmentsClient) Get(ctx context.Context, id ScopedRegistrationAssignmentId, options GetOperationOptions) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c RegistrationAssignmentsClient) preparerForGet(ctx context.Context, id ScopedRegistrationAssignmentId, options GetOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c RegistrationAssignmentsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_list_autorest.go new file mode 100644 index 000000000000..e65c223e6a3d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/method_list_autorest.go @@ -0,0 +1,216 @@ +package registrationassignments + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *[]RegistrationAssignment + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) +} + +type ListCompleteResult struct { + Items []RegistrationAssignment +} + +func (r ListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type ListOperationOptions struct { + ExpandRegistrationDefinition *bool +} + +func DefaultListOperationOptions() ListOperationOptions { + return ListOperationOptions{} +} + +func (o ListOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o ListOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.ExpandRegistrationDefinition != nil { + out["$expandRegistrationDefinition"] = *o.ExpandRegistrationDefinition + } + + return out +} + +// List ... +func (c RegistrationAssignmentsClient) List(ctx context.Context, id commonids.ScopeId, options ListOperationOptions) (resp ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "List", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "List", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "List", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListComplete retrieves all of the results into a single object +func (c RegistrationAssignmentsClient) ListComplete(ctx context.Context, id commonids.ScopeId, options ListOperationOptions) (ListCompleteResult, error) { + return c.ListCompleteMatchingPredicate(ctx, id, options, RegistrationAssignmentOperationPredicate{}) +} + +// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c RegistrationAssignmentsClient) ListCompleteMatchingPredicate(ctx context.Context, id commonids.ScopeId, options ListOperationOptions, predicate RegistrationAssignmentOperationPredicate) (resp ListCompleteResult, err error) { + items := make([]RegistrationAssignment, 0) + + page, err := c.List(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForList prepares the List request. +func (c RegistrationAssignmentsClient) preparerForList(ctx context.Context, id commonids.ScopeId, options ListOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.ManagedServices/registrationAssignments", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListWithNextLink prepares the List request with the given nextLink token. +func (c RegistrationAssignmentsClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c RegistrationAssignmentsClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + type page struct { + Values []RegistrationAssignment `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { + req, err := c.preparerForListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationassignments.RegistrationAssignmentsClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_authorization.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_authorization.go new file mode 100644 index 000000000000..08268bf4414f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_authorization.go @@ -0,0 +1,11 @@ +package registrationassignments + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Authorization struct { + DelegatedRoleDefinitionIds *[]string `json:"delegatedRoleDefinitionIds,omitempty"` + PrincipalId string `json:"principalId"` + PrincipalIdDisplayName *string `json:"principalIdDisplayName,omitempty"` + RoleDefinitionId string `json:"roleDefinitionId"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_plan.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_plan.go new file mode 100644 index 000000000000..6a879190ebce --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_plan.go @@ -0,0 +1,11 @@ +package registrationassignments + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Plan struct { + Name string `json:"name"` + Product string `json:"product"` + Publisher string `json:"publisher"` + Version string `json:"version"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignment.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignment.go new file mode 100644 index 000000000000..12d3e13ea368 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignment.go @@ -0,0 +1,11 @@ +package registrationassignments + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegistrationAssignment struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *RegistrationAssignmentProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentproperties.go new file mode 100644 index 000000000000..63897dbeddf9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentproperties.go @@ -0,0 +1,10 @@ +package registrationassignments + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegistrationAssignmentProperties struct { + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` + RegistrationDefinition *RegistrationAssignmentPropertiesRegistrationDefinition `json:"registrationDefinition,omitempty"` + RegistrationDefinitionId string `json:"registrationDefinitionId"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentpropertiesregistrationdefinition.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentpropertiesregistrationdefinition.go new file mode 100644 index 000000000000..c9d35f75c996 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentpropertiesregistrationdefinition.go @@ -0,0 +1,12 @@ +package registrationassignments + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegistrationAssignmentPropertiesRegistrationDefinition struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Plan *Plan `json:"plan,omitempty"` + Properties *RegistrationAssignmentPropertiesRegistrationDefinitionProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/predicates.go new file mode 100644 index 000000000000..de0c361db9e4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/predicates.go @@ -0,0 +1,24 @@ +package registrationassignments + +type RegistrationAssignmentOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p RegistrationAssignmentOperationPredicate) Matches(input RegistrationAssignment) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/version.go new file mode 100644 index 000000000000..ff0f5886b0ee --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/version.go @@ -0,0 +1,12 @@ +package registrationassignments + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2019-06-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/registrationassignments/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/README.md new file mode 100644 index 000000000000..e1e3b00aaa75 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/README.md @@ -0,0 +1,86 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions` Documentation + +The `registrationdefinitions` SDK allows for interaction with the Azure Resource Manager Service `managedservices` (API Version `2019-06-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions" +``` + + +### Client Initialization + +```go +client := registrationdefinitions.NewRegistrationDefinitionsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `RegistrationDefinitionsClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := registrationdefinitions.NewScopedRegistrationDefinitionID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "registrationDefinitionIdValue") + +payload := registrationdefinitions.RegistrationDefinition{ + // ... +} + + +if err := client.CreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `RegistrationDefinitionsClient.Delete` + +```go +ctx := context.TODO() +id := registrationdefinitions.NewScopedRegistrationDefinitionID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "registrationDefinitionIdValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `RegistrationDefinitionsClient.Get` + +```go +ctx := context.TODO() +id := registrationdefinitions.NewScopedRegistrationDefinitionID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "registrationDefinitionIdValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `RegistrationDefinitionsClient.List` + +```go +ctx := context.TODO() +id := registrationdefinitions.NewScopeID() + +// alternatively `client.List(ctx, id)` can be used to do batched pagination +items, err := client.ListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/client.go new file mode 100644 index 000000000000..fcb7eab7cba1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/client.go @@ -0,0 +1,18 @@ +package registrationdefinitions + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegistrationDefinitionsClient struct { + Client autorest.Client + baseUri string +} + +func NewRegistrationDefinitionsClientWithBaseURI(endpoint string) RegistrationDefinitionsClient { + return RegistrationDefinitionsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/constants.go new file mode 100644 index 000000000000..bc08accd9216 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/constants.go @@ -0,0 +1,64 @@ +package registrationdefinitions + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ProvisioningState string + +const ( + ProvisioningStateAccepted ProvisioningState = "Accepted" + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateCreated ProvisioningState = "Created" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateDeleted ProvisioningState = "Deleted" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateNotSpecified ProvisioningState = "NotSpecified" + ProvisioningStateReady ProvisioningState = "Ready" + ProvisioningStateRunning ProvisioningState = "Running" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +func PossibleValuesForProvisioningState() []string { + return []string{ + string(ProvisioningStateAccepted), + string(ProvisioningStateCanceled), + string(ProvisioningStateCreated), + string(ProvisioningStateCreating), + string(ProvisioningStateDeleted), + string(ProvisioningStateDeleting), + string(ProvisioningStateFailed), + string(ProvisioningStateNotSpecified), + string(ProvisioningStateReady), + string(ProvisioningStateRunning), + string(ProvisioningStateSucceeded), + string(ProvisioningStateUpdating), + } +} + +func parseProvisioningState(input string) (*ProvisioningState, error) { + vals := map[string]ProvisioningState{ + "accepted": ProvisioningStateAccepted, + "canceled": ProvisioningStateCanceled, + "created": ProvisioningStateCreated, + "creating": ProvisioningStateCreating, + "deleted": ProvisioningStateDeleted, + "deleting": ProvisioningStateDeleting, + "failed": ProvisioningStateFailed, + "notspecified": ProvisioningStateNotSpecified, + "ready": ProvisioningStateReady, + "running": ProvisioningStateRunning, + "succeeded": ProvisioningStateSucceeded, + "updating": ProvisioningStateUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ProvisioningState(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/id_scopedregistrationdefinition.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/id_scopedregistrationdefinition.go new file mode 100644 index 000000000000..a1ac004b966f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/id_scopedregistrationdefinition.go @@ -0,0 +1,110 @@ +package registrationdefinitions + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ScopedRegistrationDefinitionId{} + +// ScopedRegistrationDefinitionId is a struct representing the Resource ID for a Scoped Registration Definition +type ScopedRegistrationDefinitionId struct { + Scope string + RegistrationDefinitionId string +} + +// NewScopedRegistrationDefinitionID returns a new ScopedRegistrationDefinitionId struct +func NewScopedRegistrationDefinitionID(scope string, registrationDefinitionId string) ScopedRegistrationDefinitionId { + return ScopedRegistrationDefinitionId{ + Scope: scope, + RegistrationDefinitionId: registrationDefinitionId, + } +} + +// ParseScopedRegistrationDefinitionID parses 'input' into a ScopedRegistrationDefinitionId +func ParseScopedRegistrationDefinitionID(input string) (*ScopedRegistrationDefinitionId, error) { + parser := resourceids.NewParserFromResourceIdType(ScopedRegistrationDefinitionId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ScopedRegistrationDefinitionId{} + + if id.Scope, ok = parsed.Parsed["scope"]; !ok { + return nil, fmt.Errorf("the segment 'scope' was not found in the resource id %q", input) + } + + if id.RegistrationDefinitionId, ok = parsed.Parsed["registrationDefinitionId"]; !ok { + return nil, fmt.Errorf("the segment 'registrationDefinitionId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseScopedRegistrationDefinitionIDInsensitively parses 'input' case-insensitively into a ScopedRegistrationDefinitionId +// note: this method should only be used for API response data and not user input +func ParseScopedRegistrationDefinitionIDInsensitively(input string) (*ScopedRegistrationDefinitionId, error) { + parser := resourceids.NewParserFromResourceIdType(ScopedRegistrationDefinitionId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ScopedRegistrationDefinitionId{} + + if id.Scope, ok = parsed.Parsed["scope"]; !ok { + return nil, fmt.Errorf("the segment 'scope' was not found in the resource id %q", input) + } + + if id.RegistrationDefinitionId, ok = parsed.Parsed["registrationDefinitionId"]; !ok { + return nil, fmt.Errorf("the segment 'registrationDefinitionId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateScopedRegistrationDefinitionID checks that 'input' can be parsed as a Scoped Registration Definition ID +func ValidateScopedRegistrationDefinitionID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseScopedRegistrationDefinitionID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Scoped Registration Definition ID +func (id ScopedRegistrationDefinitionId) ID() string { + fmtString := "/%s/providers/Microsoft.ManagedServices/registrationDefinitions/%s" + return fmt.Sprintf(fmtString, strings.TrimPrefix(id.Scope, "/"), id.RegistrationDefinitionId) +} + +// Segments returns a slice of Resource ID Segments which comprise this Scoped Registration Definition ID +func (id ScopedRegistrationDefinitionId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.ScopeSegment("scope", "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftManagedServices", "Microsoft.ManagedServices", "Microsoft.ManagedServices"), + resourceids.StaticSegment("staticRegistrationDefinitions", "registrationDefinitions", "registrationDefinitions"), + resourceids.UserSpecifiedSegment("registrationDefinitionId", "registrationDefinitionIdValue"), + } +} + +// String returns a human-readable description of this Scoped Registration Definition ID +func (id ScopedRegistrationDefinitionId) String() string { + components := []string{ + fmt.Sprintf("Scope: %q", id.Scope), + fmt.Sprintf("Registration Definition: %q", id.RegistrationDefinitionId), + } + return fmt.Sprintf("Scoped Registration Definition (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_createorupdate_autorest.go new file mode 100644 index 000000000000..e8bf5becdeb1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_createorupdate_autorest.go @@ -0,0 +1,79 @@ +package registrationdefinitions + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CreateOrUpdate ... +func (c RegistrationDefinitionsClient) CreateOrUpdate(ctx context.Context, id ScopedRegistrationDefinitionId, input RegistrationDefinition) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CreateOrUpdateThenPoll performs CreateOrUpdate then polls until it's completed +func (c RegistrationDefinitionsClient) CreateOrUpdateThenPoll(ctx context.Context, id ScopedRegistrationDefinitionId, input RegistrationDefinition) error { + result, err := c.CreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing CreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c RegistrationDefinitionsClient) preparerForCreateOrUpdate(ctx context.Context, id ScopedRegistrationDefinitionId, input RegistrationDefinition) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCreateOrUpdate sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c RegistrationDefinitionsClient) senderForCreateOrUpdate(ctx context.Context, req *http.Request) (future CreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_delete_autorest.go new file mode 100644 index 000000000000..ac829a6fd205 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_delete_autorest.go @@ -0,0 +1,65 @@ +package registrationdefinitions + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c RegistrationDefinitionsClient) Delete(ctx context.Context, id ScopedRegistrationDefinitionId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c RegistrationDefinitionsClient) preparerForDelete(ctx context.Context, id ScopedRegistrationDefinitionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c RegistrationDefinitionsClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_get_autorest.go new file mode 100644 index 000000000000..16bd29a437f3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_get_autorest.go @@ -0,0 +1,67 @@ +package registrationdefinitions + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *RegistrationDefinition +} + +// Get ... +func (c RegistrationDefinitionsClient) Get(ctx context.Context, id ScopedRegistrationDefinitionId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c RegistrationDefinitionsClient) preparerForGet(ctx context.Context, id ScopedRegistrationDefinitionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c RegistrationDefinitionsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_list_autorest.go new file mode 100644 index 000000000000..b935a709b729 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/method_list_autorest.go @@ -0,0 +1,187 @@ +package registrationdefinitions + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *[]RegistrationDefinition + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) +} + +type ListCompleteResult struct { + Items []RegistrationDefinition +} + +func (r ListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// List ... +func (c RegistrationDefinitionsClient) List(ctx context.Context, id commonids.ScopeId) (resp ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "List", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "List", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "List", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListComplete retrieves all of the results into a single object +func (c RegistrationDefinitionsClient) ListComplete(ctx context.Context, id commonids.ScopeId) (ListCompleteResult, error) { + return c.ListCompleteMatchingPredicate(ctx, id, RegistrationDefinitionOperationPredicate{}) +} + +// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c RegistrationDefinitionsClient) ListCompleteMatchingPredicate(ctx context.Context, id commonids.ScopeId, predicate RegistrationDefinitionOperationPredicate) (resp ListCompleteResult, err error) { + items := make([]RegistrationDefinition, 0) + + page, err := c.List(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForList prepares the List request. +func (c RegistrationDefinitionsClient) preparerForList(ctx context.Context, id commonids.ScopeId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.ManagedServices/registrationDefinitions", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListWithNextLink prepares the List request with the given nextLink token. +func (c RegistrationDefinitionsClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c RegistrationDefinitionsClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + type page struct { + Values []RegistrationDefinition `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { + req, err := c.preparerForListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "registrationdefinitions.RegistrationDefinitionsClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_authorization.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_authorization.go new file mode 100644 index 000000000000..46dece780ed0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_authorization.go @@ -0,0 +1,11 @@ +package registrationdefinitions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Authorization struct { + DelegatedRoleDefinitionIds *[]string `json:"delegatedRoleDefinitionIds,omitempty"` + PrincipalId string `json:"principalId"` + PrincipalIdDisplayName *string `json:"principalIdDisplayName,omitempty"` + RoleDefinitionId string `json:"roleDefinitionId"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_plan.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_plan.go new file mode 100644 index 000000000000..7c11e92703fa --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_plan.go @@ -0,0 +1,11 @@ +package registrationdefinitions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Plan struct { + Name string `json:"name"` + Product string `json:"product"` + Publisher string `json:"publisher"` + Version string `json:"version"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_registrationdefinition.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_registrationdefinition.go new file mode 100644 index 000000000000..8e9de0c07475 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_registrationdefinition.go @@ -0,0 +1,12 @@ +package registrationdefinitions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegistrationDefinition struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Plan *Plan `json:"plan,omitempty"` + Properties *RegistrationDefinitionProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_registrationdefinitionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_registrationdefinitionproperties.go new file mode 100644 index 000000000000..a389a2e3f7d0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/model_registrationdefinitionproperties.go @@ -0,0 +1,13 @@ +package registrationdefinitions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegistrationDefinitionProperties struct { + Authorizations []Authorization `json:"authorizations"` + Description *string `json:"description,omitempty"` + ManagedByTenantId string `json:"managedByTenantId"` + ManagedByTenantName *string `json:"managedByTenantName,omitempty"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` + RegistrationDefinitionName *string `json:"registrationDefinitionName,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/predicates.go new file mode 100644 index 000000000000..aeaea69b6579 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/predicates.go @@ -0,0 +1,24 @@ +package registrationdefinitions + +type RegistrationDefinitionOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p RegistrationDefinitionOperationPredicate) Matches(input RegistrationDefinition) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/version.go new file mode 100644 index 000000000000..88f39d4415a1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions/version.go @@ -0,0 +1,12 @@ +package registrationdefinitions + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2019-06-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/registrationdefinitions/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/README.md new file mode 100644 index 000000000000..a47f3c6bf12f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/README.md @@ -0,0 +1,99 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools` Documentation + +The `capacitypools` SDK allows for interaction with the Azure Resource Manager Service `netapp` (API Version `2021-10-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools" +``` + + +### Client Initialization + +```go +client := capacitypools.NewCapacityPoolsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `CapacityPoolsClient.PoolsCreateOrUpdate` + +```go +ctx := context.TODO() +id := capacitypools.NewCapacityPoolID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue") + +payload := capacitypools.CapacityPool{ + // ... +} + + +if err := client.PoolsCreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `CapacityPoolsClient.PoolsDelete` + +```go +ctx := context.TODO() +id := capacitypools.NewCapacityPoolID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue") + +if err := client.PoolsDeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `CapacityPoolsClient.PoolsGet` + +```go +ctx := context.TODO() +id := capacitypools.NewCapacityPoolID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue") + +read, err := client.PoolsGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `CapacityPoolsClient.PoolsList` + +```go +ctx := context.TODO() +id := capacitypools.NewNetAppAccountID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue") + +// alternatively `client.PoolsList(ctx, id)` can be used to do batched pagination +items, err := client.PoolsListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `CapacityPoolsClient.PoolsUpdate` + +```go +ctx := context.TODO() +id := capacitypools.NewCapacityPoolID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue") + +payload := capacitypools.CapacityPoolPatch{ + // ... +} + + +if err := client.PoolsUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/client.go new file mode 100644 index 000000000000..d31b6b301a25 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/client.go @@ -0,0 +1,18 @@ +package capacitypools + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CapacityPoolsClient struct { + Client autorest.Client + baseUri string +} + +func NewCapacityPoolsClientWithBaseURI(endpoint string) CapacityPoolsClient { + return CapacityPoolsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/constants.go new file mode 100644 index 000000000000..4856e8e79bc3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/constants.go @@ -0,0 +1,96 @@ +package capacitypools + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EncryptionType string + +const ( + EncryptionTypeDouble EncryptionType = "Double" + EncryptionTypeSingle EncryptionType = "Single" +) + +func PossibleValuesForEncryptionType() []string { + return []string{ + string(EncryptionTypeDouble), + string(EncryptionTypeSingle), + } +} + +func parseEncryptionType(input string) (*EncryptionType, error) { + vals := map[string]EncryptionType{ + "double": EncryptionTypeDouble, + "single": EncryptionTypeSingle, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EncryptionType(input) + return &out, nil +} + +type QosType string + +const ( + QosTypeAuto QosType = "Auto" + QosTypeManual QosType = "Manual" +) + +func PossibleValuesForQosType() []string { + return []string{ + string(QosTypeAuto), + string(QosTypeManual), + } +} + +func parseQosType(input string) (*QosType, error) { + vals := map[string]QosType{ + "auto": QosTypeAuto, + "manual": QosTypeManual, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := QosType(input) + return &out, nil +} + +type ServiceLevel string + +const ( + ServiceLevelPremium ServiceLevel = "Premium" + ServiceLevelStandard ServiceLevel = "Standard" + ServiceLevelStandardZRS ServiceLevel = "StandardZRS" + ServiceLevelUltra ServiceLevel = "Ultra" +) + +func PossibleValuesForServiceLevel() []string { + return []string{ + string(ServiceLevelPremium), + string(ServiceLevelStandard), + string(ServiceLevelStandardZRS), + string(ServiceLevelUltra), + } +} + +func parseServiceLevel(input string) (*ServiceLevel, error) { + vals := map[string]ServiceLevel{ + "premium": ServiceLevelPremium, + "standard": ServiceLevelStandard, + "standardzrs": ServiceLevelStandardZRS, + "ultra": ServiceLevelUltra, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ServiceLevel(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/id_capacitypool.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/id_capacitypool.go new file mode 100644 index 000000000000..a50e29408397 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/id_capacitypool.go @@ -0,0 +1,137 @@ +package capacitypools + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = CapacityPoolId{} + +// CapacityPoolId is a struct representing the Resource ID for a Capacity Pool +type CapacityPoolId struct { + SubscriptionId string + ResourceGroupName string + AccountName string + PoolName string +} + +// NewCapacityPoolID returns a new CapacityPoolId struct +func NewCapacityPoolID(subscriptionId string, resourceGroupName string, accountName string, poolName string) CapacityPoolId { + return CapacityPoolId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + PoolName: poolName, + } +} + +// ParseCapacityPoolID parses 'input' into a CapacityPoolId +func ParseCapacityPoolID(input string) (*CapacityPoolId, error) { + parser := resourceids.NewParserFromResourceIdType(CapacityPoolId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := CapacityPoolId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseCapacityPoolIDInsensitively parses 'input' case-insensitively into a CapacityPoolId +// note: this method should only be used for API response data and not user input +func ParseCapacityPoolIDInsensitively(input string) (*CapacityPoolId, error) { + parser := resourceids.NewParserFromResourceIdType(CapacityPoolId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := CapacityPoolId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateCapacityPoolID checks that 'input' can be parsed as a Capacity Pool ID +func ValidateCapacityPoolID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseCapacityPoolID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Capacity Pool ID +func (id CapacityPoolId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s/capacityPools/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName, id.PoolName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Capacity Pool ID +func (id CapacityPoolId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + resourceids.StaticSegment("staticCapacityPools", "capacityPools", "capacityPools"), + resourceids.UserSpecifiedSegment("poolName", "poolValue"), + } +} + +// String returns a human-readable description of this Capacity Pool ID +func (id CapacityPoolId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + fmt.Sprintf("Pool Name: %q", id.PoolName), + } + return fmt.Sprintf("Capacity Pool (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/id_netappaccount.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/id_netappaccount.go new file mode 100644 index 000000000000..86bd7fcada46 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/id_netappaccount.go @@ -0,0 +1,124 @@ +package capacitypools + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NetAppAccountId{} + +// NetAppAccountId is a struct representing the Resource ID for a Net App Account +type NetAppAccountId struct { + SubscriptionId string + ResourceGroupName string + AccountName string +} + +// NewNetAppAccountID returns a new NetAppAccountId struct +func NewNetAppAccountID(subscriptionId string, resourceGroupName string, accountName string) NetAppAccountId { + return NetAppAccountId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + } +} + +// ParseNetAppAccountID parses 'input' into a NetAppAccountId +func ParseNetAppAccountID(input string) (*NetAppAccountId, error) { + parser := resourceids.NewParserFromResourceIdType(NetAppAccountId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NetAppAccountId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNetAppAccountIDInsensitively parses 'input' case-insensitively into a NetAppAccountId +// note: this method should only be used for API response data and not user input +func ParseNetAppAccountIDInsensitively(input string) (*NetAppAccountId, error) { + parser := resourceids.NewParserFromResourceIdType(NetAppAccountId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NetAppAccountId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNetAppAccountID checks that 'input' can be parsed as a Net App Account ID +func ValidateNetAppAccountID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNetAppAccountID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Net App Account ID +func (id NetAppAccountId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Net App Account ID +func (id NetAppAccountId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + } +} + +// String returns a human-readable description of this Net App Account ID +func (id NetAppAccountId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + } + return fmt.Sprintf("Net App Account (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolscreateorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolscreateorupdate_autorest.go new file mode 100644 index 000000000000..72891f7b9dfb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolscreateorupdate_autorest.go @@ -0,0 +1,79 @@ +package capacitypools + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PoolsCreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// PoolsCreateOrUpdate ... +func (c CapacityPoolsClient) PoolsCreateOrUpdate(ctx context.Context, id CapacityPoolId, input CapacityPool) (result PoolsCreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForPoolsCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsCreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForPoolsCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsCreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// PoolsCreateOrUpdateThenPoll performs PoolsCreateOrUpdate then polls until it's completed +func (c CapacityPoolsClient) PoolsCreateOrUpdateThenPoll(ctx context.Context, id CapacityPoolId, input CapacityPool) error { + result, err := c.PoolsCreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing PoolsCreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after PoolsCreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForPoolsCreateOrUpdate prepares the PoolsCreateOrUpdate request. +func (c CapacityPoolsClient) preparerForPoolsCreateOrUpdate(ctx context.Context, id CapacityPoolId, input CapacityPool) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForPoolsCreateOrUpdate sends the PoolsCreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c CapacityPoolsClient) senderForPoolsCreateOrUpdate(ctx context.Context, req *http.Request) (future PoolsCreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsdelete_autorest.go new file mode 100644 index 000000000000..61d0e6104b15 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsdelete_autorest.go @@ -0,0 +1,78 @@ +package capacitypools + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PoolsDeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// PoolsDelete ... +func (c CapacityPoolsClient) PoolsDelete(ctx context.Context, id CapacityPoolId) (result PoolsDeleteOperationResponse, err error) { + req, err := c.preparerForPoolsDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsDelete", nil, "Failure preparing request") + return + } + + result, err = c.senderForPoolsDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsDelete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// PoolsDeleteThenPoll performs PoolsDelete then polls until it's completed +func (c CapacityPoolsClient) PoolsDeleteThenPoll(ctx context.Context, id CapacityPoolId) error { + result, err := c.PoolsDelete(ctx, id) + if err != nil { + return fmt.Errorf("performing PoolsDelete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after PoolsDelete: %+v", err) + } + + return nil +} + +// preparerForPoolsDelete prepares the PoolsDelete request. +func (c CapacityPoolsClient) preparerForPoolsDelete(ctx context.Context, id CapacityPoolId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForPoolsDelete sends the PoolsDelete request. The method will close the +// http.Response Body if it receives an error. +func (c CapacityPoolsClient) senderForPoolsDelete(ctx context.Context, req *http.Request) (future PoolsDeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsget_autorest.go new file mode 100644 index 000000000000..d2725693da9d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsget_autorest.go @@ -0,0 +1,67 @@ +package capacitypools + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PoolsGetOperationResponse struct { + HttpResponse *http.Response + Model *CapacityPool +} + +// PoolsGet ... +func (c CapacityPoolsClient) PoolsGet(ctx context.Context, id CapacityPoolId) (result PoolsGetOperationResponse, err error) { + req, err := c.preparerForPoolsGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForPoolsGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForPoolsGet prepares the PoolsGet request. +func (c CapacityPoolsClient) preparerForPoolsGet(ctx context.Context, id CapacityPoolId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForPoolsGet handles the response to the PoolsGet request. The method always +// closes the http.Response Body. +func (c CapacityPoolsClient) responderForPoolsGet(resp *http.Response) (result PoolsGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolslist_autorest.go new file mode 100644 index 000000000000..25c06a45e9bd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolslist_autorest.go @@ -0,0 +1,186 @@ +package capacitypools + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PoolsListOperationResponse struct { + HttpResponse *http.Response + Model *[]CapacityPool + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (PoolsListOperationResponse, error) +} + +type PoolsListCompleteResult struct { + Items []CapacityPool +} + +func (r PoolsListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r PoolsListOperationResponse) LoadMore(ctx context.Context) (resp PoolsListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// PoolsList ... +func (c CapacityPoolsClient) PoolsList(ctx context.Context, id NetAppAccountId) (resp PoolsListOperationResponse, err error) { + req, err := c.preparerForPoolsList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForPoolsList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// PoolsListComplete retrieves all of the results into a single object +func (c CapacityPoolsClient) PoolsListComplete(ctx context.Context, id NetAppAccountId) (PoolsListCompleteResult, error) { + return c.PoolsListCompleteMatchingPredicate(ctx, id, CapacityPoolOperationPredicate{}) +} + +// PoolsListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c CapacityPoolsClient) PoolsListCompleteMatchingPredicate(ctx context.Context, id NetAppAccountId, predicate CapacityPoolOperationPredicate) (resp PoolsListCompleteResult, err error) { + items := make([]CapacityPool, 0) + + page, err := c.PoolsList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := PoolsListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForPoolsList prepares the PoolsList request. +func (c CapacityPoolsClient) preparerForPoolsList(ctx context.Context, id NetAppAccountId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/capacityPools", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForPoolsListWithNextLink prepares the PoolsList request with the given nextLink token. +func (c CapacityPoolsClient) preparerForPoolsListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForPoolsList handles the response to the PoolsList request. The method always +// closes the http.Response Body. +func (c CapacityPoolsClient) responderForPoolsList(resp *http.Response) (result PoolsListOperationResponse, err error) { + type page struct { + Values []CapacityPool `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result PoolsListOperationResponse, err error) { + req, err := c.preparerForPoolsListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForPoolsList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsupdate_autorest.go new file mode 100644 index 000000000000..680bc19748a1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/method_poolsupdate_autorest.go @@ -0,0 +1,79 @@ +package capacitypools + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PoolsUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// PoolsUpdate ... +func (c CapacityPoolsClient) PoolsUpdate(ctx context.Context, id CapacityPoolId, input CapacityPoolPatch) (result PoolsUpdateOperationResponse, err error) { + req, err := c.preparerForPoolsUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForPoolsUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "capacitypools.CapacityPoolsClient", "PoolsUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// PoolsUpdateThenPoll performs PoolsUpdate then polls until it's completed +func (c CapacityPoolsClient) PoolsUpdateThenPoll(ctx context.Context, id CapacityPoolId, input CapacityPoolPatch) error { + result, err := c.PoolsUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing PoolsUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after PoolsUpdate: %+v", err) + } + + return nil +} + +// preparerForPoolsUpdate prepares the PoolsUpdate request. +func (c CapacityPoolsClient) preparerForPoolsUpdate(ctx context.Context, id CapacityPoolId, input CapacityPoolPatch) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForPoolsUpdate sends the PoolsUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c CapacityPoolsClient) senderForPoolsUpdate(ctx context.Context, req *http.Request) (future PoolsUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_capacitypool.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_capacitypool.go new file mode 100644 index 000000000000..f5d6f1ea86df --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_capacitypool.go @@ -0,0 +1,19 @@ +package capacitypools + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CapacityPool struct { + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties PoolProperties `json:"properties"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_capacitypoolpatch.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_capacitypoolpatch.go new file mode 100644 index 000000000000..46abcde6b330 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_capacitypoolpatch.go @@ -0,0 +1,13 @@ +package capacitypools + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CapacityPoolPatch struct { + Id *string `json:"id,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Properties *PoolPatchProperties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_poolpatchproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_poolpatchproperties.go new file mode 100644 index 000000000000..071dba445599 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_poolpatchproperties.go @@ -0,0 +1,9 @@ +package capacitypools + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PoolPatchProperties struct { + QosType *QosType `json:"qosType,omitempty"` + Size *int64 `json:"size,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_poolproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_poolproperties.go new file mode 100644 index 000000000000..a1fee733fb48 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/model_poolproperties.go @@ -0,0 +1,16 @@ +package capacitypools + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PoolProperties struct { + CoolAccess *bool `json:"coolAccess,omitempty"` + EncryptionType *EncryptionType `json:"encryptionType,omitempty"` + PoolId *string `json:"poolId,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + QosType *QosType `json:"qosType,omitempty"` + ServiceLevel ServiceLevel `json:"serviceLevel"` + Size int64 `json:"size"` + TotalThroughputMibps *float64 `json:"totalThroughputMibps,omitempty"` + UtilizedThroughputMibps *float64 `json:"utilizedThroughputMibps,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/predicates.go new file mode 100644 index 000000000000..67e2199aa2cd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/predicates.go @@ -0,0 +1,34 @@ +package capacitypools + +type CapacityPoolOperationPredicate struct { + Etag *string + Id *string + Location *string + Name *string + Type *string +} + +func (p CapacityPoolOperationPredicate) Matches(input CapacityPool) bool { + + if p.Etag != nil && (input.Etag == nil && *p.Etag != *input.Etag) { + return false + } + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/version.go new file mode 100644 index 000000000000..c647e1604368 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools/version.go @@ -0,0 +1,12 @@ +package capacitypools + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-10-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/capacitypools/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/README.md new file mode 100644 index 000000000000..487820e90f62 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/README.md @@ -0,0 +1,116 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts` Documentation + +The `netappaccounts` SDK allows for interaction with the Azure Resource Manager Service `netapp` (API Version `2021-10-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts" +``` + + +### Client Initialization + +```go +client := netappaccounts.NewNetAppAccountsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `NetAppAccountsClient.AccountsCreateOrUpdate` + +```go +ctx := context.TODO() +id := netappaccounts.NewNetAppAccountID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue") + +payload := netappaccounts.NetAppAccount{ + // ... +} + + +if err := client.AccountsCreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `NetAppAccountsClient.AccountsDelete` + +```go +ctx := context.TODO() +id := netappaccounts.NewNetAppAccountID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue") + +if err := client.AccountsDeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `NetAppAccountsClient.AccountsGet` + +```go +ctx := context.TODO() +id := netappaccounts.NewNetAppAccountID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue") + +read, err := client.AccountsGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NetAppAccountsClient.AccountsList` + +```go +ctx := context.TODO() +id := netappaccounts.NewResourceGroupID() + +// alternatively `client.AccountsList(ctx, id)` can be used to do batched pagination +items, err := client.AccountsListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `NetAppAccountsClient.AccountsListBySubscription` + +```go +ctx := context.TODO() +id := netappaccounts.NewSubscriptionID() + +// alternatively `client.AccountsListBySubscription(ctx, id)` can be used to do batched pagination +items, err := client.AccountsListBySubscriptionComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `NetAppAccountsClient.AccountsUpdate` + +```go +ctx := context.TODO() +id := netappaccounts.NewNetAppAccountID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue") + +payload := netappaccounts.NetAppAccountPatch{ + // ... +} + + +if err := client.AccountsUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/client.go new file mode 100644 index 000000000000..1a10ce8e9b65 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/client.go @@ -0,0 +1,18 @@ +package netappaccounts + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NetAppAccountsClient struct { + Client autorest.Client + baseUri string +} + +func NewNetAppAccountsClientWithBaseURI(endpoint string) NetAppAccountsClient { + return NetAppAccountsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/constants.go new file mode 100644 index 000000000000..6e41970873a4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/constants.go @@ -0,0 +1,43 @@ +package netappaccounts + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ActiveDirectoryStatus string + +const ( + ActiveDirectoryStatusCreated ActiveDirectoryStatus = "Created" + ActiveDirectoryStatusDeleted ActiveDirectoryStatus = "Deleted" + ActiveDirectoryStatusError ActiveDirectoryStatus = "Error" + ActiveDirectoryStatusInUse ActiveDirectoryStatus = "InUse" + ActiveDirectoryStatusUpdating ActiveDirectoryStatus = "Updating" +) + +func PossibleValuesForActiveDirectoryStatus() []string { + return []string{ + string(ActiveDirectoryStatusCreated), + string(ActiveDirectoryStatusDeleted), + string(ActiveDirectoryStatusError), + string(ActiveDirectoryStatusInUse), + string(ActiveDirectoryStatusUpdating), + } +} + +func parseActiveDirectoryStatus(input string) (*ActiveDirectoryStatus, error) { + vals := map[string]ActiveDirectoryStatus{ + "created": ActiveDirectoryStatusCreated, + "deleted": ActiveDirectoryStatusDeleted, + "error": ActiveDirectoryStatusError, + "inuse": ActiveDirectoryStatusInUse, + "updating": ActiveDirectoryStatusUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ActiveDirectoryStatus(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/id_netappaccount.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/id_netappaccount.go new file mode 100644 index 000000000000..68e53f4815fc --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/id_netappaccount.go @@ -0,0 +1,124 @@ +package netappaccounts + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NetAppAccountId{} + +// NetAppAccountId is a struct representing the Resource ID for a Net App Account +type NetAppAccountId struct { + SubscriptionId string + ResourceGroupName string + AccountName string +} + +// NewNetAppAccountID returns a new NetAppAccountId struct +func NewNetAppAccountID(subscriptionId string, resourceGroupName string, accountName string) NetAppAccountId { + return NetAppAccountId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + } +} + +// ParseNetAppAccountID parses 'input' into a NetAppAccountId +func ParseNetAppAccountID(input string) (*NetAppAccountId, error) { + parser := resourceids.NewParserFromResourceIdType(NetAppAccountId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NetAppAccountId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNetAppAccountIDInsensitively parses 'input' case-insensitively into a NetAppAccountId +// note: this method should only be used for API response data and not user input +func ParseNetAppAccountIDInsensitively(input string) (*NetAppAccountId, error) { + parser := resourceids.NewParserFromResourceIdType(NetAppAccountId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NetAppAccountId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNetAppAccountID checks that 'input' can be parsed as a Net App Account ID +func ValidateNetAppAccountID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNetAppAccountID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Net App Account ID +func (id NetAppAccountId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Net App Account ID +func (id NetAppAccountId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + } +} + +// String returns a human-readable description of this Net App Account ID +func (id NetAppAccountId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + } + return fmt.Sprintf("Net App Account (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountscreateorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountscreateorupdate_autorest.go new file mode 100644 index 000000000000..b192ede4f692 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountscreateorupdate_autorest.go @@ -0,0 +1,79 @@ +package netappaccounts + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccountsCreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// AccountsCreateOrUpdate ... +func (c NetAppAccountsClient) AccountsCreateOrUpdate(ctx context.Context, id NetAppAccountId, input NetAppAccount) (result AccountsCreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForAccountsCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsCreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForAccountsCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsCreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// AccountsCreateOrUpdateThenPoll performs AccountsCreateOrUpdate then polls until it's completed +func (c NetAppAccountsClient) AccountsCreateOrUpdateThenPoll(ctx context.Context, id NetAppAccountId, input NetAppAccount) error { + result, err := c.AccountsCreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing AccountsCreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after AccountsCreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForAccountsCreateOrUpdate prepares the AccountsCreateOrUpdate request. +func (c NetAppAccountsClient) preparerForAccountsCreateOrUpdate(ctx context.Context, id NetAppAccountId, input NetAppAccount) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForAccountsCreateOrUpdate sends the AccountsCreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c NetAppAccountsClient) senderForAccountsCreateOrUpdate(ctx context.Context, req *http.Request) (future AccountsCreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsdelete_autorest.go new file mode 100644 index 000000000000..4506db44c634 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsdelete_autorest.go @@ -0,0 +1,78 @@ +package netappaccounts + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccountsDeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// AccountsDelete ... +func (c NetAppAccountsClient) AccountsDelete(ctx context.Context, id NetAppAccountId) (result AccountsDeleteOperationResponse, err error) { + req, err := c.preparerForAccountsDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsDelete", nil, "Failure preparing request") + return + } + + result, err = c.senderForAccountsDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsDelete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// AccountsDeleteThenPoll performs AccountsDelete then polls until it's completed +func (c NetAppAccountsClient) AccountsDeleteThenPoll(ctx context.Context, id NetAppAccountId) error { + result, err := c.AccountsDelete(ctx, id) + if err != nil { + return fmt.Errorf("performing AccountsDelete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after AccountsDelete: %+v", err) + } + + return nil +} + +// preparerForAccountsDelete prepares the AccountsDelete request. +func (c NetAppAccountsClient) preparerForAccountsDelete(ctx context.Context, id NetAppAccountId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForAccountsDelete sends the AccountsDelete request. The method will close the +// http.Response Body if it receives an error. +func (c NetAppAccountsClient) senderForAccountsDelete(ctx context.Context, req *http.Request) (future AccountsDeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsget_autorest.go new file mode 100644 index 000000000000..1c1edc04ccfb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsget_autorest.go @@ -0,0 +1,67 @@ +package netappaccounts + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccountsGetOperationResponse struct { + HttpResponse *http.Response + Model *NetAppAccount +} + +// AccountsGet ... +func (c NetAppAccountsClient) AccountsGet(ctx context.Context, id NetAppAccountId) (result AccountsGetOperationResponse, err error) { + req, err := c.preparerForAccountsGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForAccountsGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForAccountsGet prepares the AccountsGet request. +func (c NetAppAccountsClient) preparerForAccountsGet(ctx context.Context, id NetAppAccountId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForAccountsGet handles the response to the AccountsGet request. The method always +// closes the http.Response Body. +func (c NetAppAccountsClient) responderForAccountsGet(resp *http.Response) (result AccountsGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountslist_autorest.go new file mode 100644 index 000000000000..dd93604fbcd5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountslist_autorest.go @@ -0,0 +1,187 @@ +package netappaccounts + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccountsListOperationResponse struct { + HttpResponse *http.Response + Model *[]NetAppAccount + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (AccountsListOperationResponse, error) +} + +type AccountsListCompleteResult struct { + Items []NetAppAccount +} + +func (r AccountsListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r AccountsListOperationResponse) LoadMore(ctx context.Context) (resp AccountsListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// AccountsList ... +func (c NetAppAccountsClient) AccountsList(ctx context.Context, id commonids.ResourceGroupId) (resp AccountsListOperationResponse, err error) { + req, err := c.preparerForAccountsList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForAccountsList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// AccountsListComplete retrieves all of the results into a single object +func (c NetAppAccountsClient) AccountsListComplete(ctx context.Context, id commonids.ResourceGroupId) (AccountsListCompleteResult, error) { + return c.AccountsListCompleteMatchingPredicate(ctx, id, NetAppAccountOperationPredicate{}) +} + +// AccountsListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c NetAppAccountsClient) AccountsListCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate NetAppAccountOperationPredicate) (resp AccountsListCompleteResult, err error) { + items := make([]NetAppAccount, 0) + + page, err := c.AccountsList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := AccountsListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForAccountsList prepares the AccountsList request. +func (c NetAppAccountsClient) preparerForAccountsList(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.NetApp/netAppAccounts", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForAccountsListWithNextLink prepares the AccountsList request with the given nextLink token. +func (c NetAppAccountsClient) preparerForAccountsListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForAccountsList handles the response to the AccountsList request. The method always +// closes the http.Response Body. +func (c NetAppAccountsClient) responderForAccountsList(resp *http.Response) (result AccountsListOperationResponse, err error) { + type page struct { + Values []NetAppAccount `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result AccountsListOperationResponse, err error) { + req, err := c.preparerForAccountsListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForAccountsList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountslistbysubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountslistbysubscription_autorest.go new file mode 100644 index 000000000000..bd65578f1751 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountslistbysubscription_autorest.go @@ -0,0 +1,187 @@ +package netappaccounts + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccountsListBySubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *[]NetAppAccount + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (AccountsListBySubscriptionOperationResponse, error) +} + +type AccountsListBySubscriptionCompleteResult struct { + Items []NetAppAccount +} + +func (r AccountsListBySubscriptionOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r AccountsListBySubscriptionOperationResponse) LoadMore(ctx context.Context) (resp AccountsListBySubscriptionOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// AccountsListBySubscription ... +func (c NetAppAccountsClient) AccountsListBySubscription(ctx context.Context, id commonids.SubscriptionId) (resp AccountsListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForAccountsListBySubscription(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsListBySubscription", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsListBySubscription", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForAccountsListBySubscription(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsListBySubscription", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// AccountsListBySubscriptionComplete retrieves all of the results into a single object +func (c NetAppAccountsClient) AccountsListBySubscriptionComplete(ctx context.Context, id commonids.SubscriptionId) (AccountsListBySubscriptionCompleteResult, error) { + return c.AccountsListBySubscriptionCompleteMatchingPredicate(ctx, id, NetAppAccountOperationPredicate{}) +} + +// AccountsListBySubscriptionCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c NetAppAccountsClient) AccountsListBySubscriptionCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate NetAppAccountOperationPredicate) (resp AccountsListBySubscriptionCompleteResult, err error) { + items := make([]NetAppAccount, 0) + + page, err := c.AccountsListBySubscription(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := AccountsListBySubscriptionCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForAccountsListBySubscription prepares the AccountsListBySubscription request. +func (c NetAppAccountsClient) preparerForAccountsListBySubscription(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.NetApp/netAppAccounts", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForAccountsListBySubscriptionWithNextLink prepares the AccountsListBySubscription request with the given nextLink token. +func (c NetAppAccountsClient) preparerForAccountsListBySubscriptionWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForAccountsListBySubscription handles the response to the AccountsListBySubscription request. The method always +// closes the http.Response Body. +func (c NetAppAccountsClient) responderForAccountsListBySubscription(resp *http.Response) (result AccountsListBySubscriptionOperationResponse, err error) { + type page struct { + Values []NetAppAccount `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result AccountsListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForAccountsListBySubscriptionWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsListBySubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsListBySubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForAccountsListBySubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsListBySubscription", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsupdate_autorest.go new file mode 100644 index 000000000000..8ed5cd37c4ce --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/method_accountsupdate_autorest.go @@ -0,0 +1,79 @@ +package netappaccounts + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccountsUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// AccountsUpdate ... +func (c NetAppAccountsClient) AccountsUpdate(ctx context.Context, id NetAppAccountId, input NetAppAccountPatch) (result AccountsUpdateOperationResponse, err error) { + req, err := c.preparerForAccountsUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForAccountsUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "netappaccounts.NetAppAccountsClient", "AccountsUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// AccountsUpdateThenPoll performs AccountsUpdate then polls until it's completed +func (c NetAppAccountsClient) AccountsUpdateThenPoll(ctx context.Context, id NetAppAccountId, input NetAppAccountPatch) error { + result, err := c.AccountsUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing AccountsUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after AccountsUpdate: %+v", err) + } + + return nil +} + +// preparerForAccountsUpdate prepares the AccountsUpdate request. +func (c NetAppAccountsClient) preparerForAccountsUpdate(ctx context.Context, id NetAppAccountId, input NetAppAccountPatch) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForAccountsUpdate sends the AccountsUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c NetAppAccountsClient) senderForAccountsUpdate(ctx context.Context, req *http.Request) (future AccountsUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_accountencryption.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_accountencryption.go new file mode 100644 index 000000000000..39a9282ce500 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_accountencryption.go @@ -0,0 +1,8 @@ +package netappaccounts + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccountEncryption struct { + KeySource *string `json:"keySource,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_accountproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_accountproperties.go new file mode 100644 index 000000000000..b158b47fc946 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_accountproperties.go @@ -0,0 +1,10 @@ +package netappaccounts + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccountProperties struct { + ActiveDirectories *[]ActiveDirectory `json:"activeDirectories,omitempty"` + Encryption *AccountEncryption `json:"encryption,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_activedirectory.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_activedirectory.go new file mode 100644 index 000000000000..da90d13da0a4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_activedirectory.go @@ -0,0 +1,29 @@ +package netappaccounts + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ActiveDirectory struct { + ActiveDirectoryId *string `json:"activeDirectoryId,omitempty"` + AdName *string `json:"adName,omitempty"` + Administrators *[]string `json:"administrators,omitempty"` + AesEncryption *bool `json:"aesEncryption,omitempty"` + AllowLocalNfsUsersWithLdap *bool `json:"allowLocalNfsUsersWithLdap,omitempty"` + BackupOperators *[]string `json:"backupOperators,omitempty"` + Dns *string `json:"dns,omitempty"` + Domain *string `json:"domain,omitempty"` + EncryptDCConnections *bool `json:"encryptDCConnections,omitempty"` + KdcIP *string `json:"kdcIP,omitempty"` + LdapOverTLS *bool `json:"ldapOverTLS,omitempty"` + LdapSearchScope *LdapSearchScopeOpt `json:"ldapSearchScope,omitempty"` + LdapSigning *bool `json:"ldapSigning,omitempty"` + OrganizationalUnit *string `json:"organizationalUnit,omitempty"` + Password *string `json:"password,omitempty"` + SecurityOperators *[]string `json:"securityOperators,omitempty"` + ServerRootCACertificate *string `json:"serverRootCACertificate,omitempty"` + Site *string `json:"site,omitempty"` + SmbServerName *string `json:"smbServerName,omitempty"` + Status *ActiveDirectoryStatus `json:"status,omitempty"` + StatusDetails *string `json:"statusDetails,omitempty"` + Username *string `json:"username,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_ldapsearchscopeopt.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_ldapsearchscopeopt.go new file mode 100644 index 000000000000..c476b0f0875f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_ldapsearchscopeopt.go @@ -0,0 +1,10 @@ +package netappaccounts + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type LdapSearchScopeOpt struct { + GroupDN *string `json:"groupDN,omitempty"` + GroupMembershipFilter *string `json:"groupMembershipFilter,omitempty"` + UserDN *string `json:"userDN,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_netappaccount.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_netappaccount.go new file mode 100644 index 000000000000..ec2ed4aa10c5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_netappaccount.go @@ -0,0 +1,19 @@ +package netappaccounts + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NetAppAccount struct { + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties *AccountProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_netappaccountpatch.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_netappaccountpatch.go new file mode 100644 index 000000000000..d3c6c1efcc20 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/model_netappaccountpatch.go @@ -0,0 +1,13 @@ +package netappaccounts + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NetAppAccountPatch struct { + Id *string `json:"id,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Properties *AccountProperties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/predicates.go new file mode 100644 index 000000000000..cc139fd85c4a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/predicates.go @@ -0,0 +1,34 @@ +package netappaccounts + +type NetAppAccountOperationPredicate struct { + Etag *string + Id *string + Location *string + Name *string + Type *string +} + +func (p NetAppAccountOperationPredicate) Matches(input NetAppAccount) bool { + + if p.Etag != nil && (input.Etag == nil && *p.Etag != *input.Etag) { + return false + } + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/version.go new file mode 100644 index 000000000000..3de2667a1a82 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts/version.go @@ -0,0 +1,12 @@ +package netappaccounts + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-10-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/netappaccounts/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/README.md new file mode 100644 index 000000000000..802de9b9653a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/README.md @@ -0,0 +1,102 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy` Documentation + +The `snapshotpolicy` SDK allows for interaction with the Azure Resource Manager Service `netapp` (API Version `2021-10-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy" +``` + + +### Client Initialization + +```go +client := snapshotpolicy.NewSnapshotPolicyClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `SnapshotPolicyClient.SnapshotPoliciesCreate` + +```go +ctx := context.TODO() +id := snapshotpolicy.NewSnapshotPoliciesID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "snapshotPolicyValue") + +payload := snapshotpolicy.SnapshotPolicy{ + // ... +} + + +read, err := client.SnapshotPoliciesCreate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SnapshotPolicyClient.SnapshotPoliciesDelete` + +```go +ctx := context.TODO() +id := snapshotpolicy.NewSnapshotPoliciesID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "snapshotPolicyValue") + +if err := client.SnapshotPoliciesDeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `SnapshotPolicyClient.SnapshotPoliciesGet` + +```go +ctx := context.TODO() +id := snapshotpolicy.NewSnapshotPoliciesID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "snapshotPolicyValue") + +read, err := client.SnapshotPoliciesGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SnapshotPolicyClient.SnapshotPoliciesList` + +```go +ctx := context.TODO() +id := snapshotpolicy.NewNetAppAccountID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue") + +read, err := client.SnapshotPoliciesList(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SnapshotPolicyClient.SnapshotPoliciesUpdate` + +```go +ctx := context.TODO() +id := snapshotpolicy.NewSnapshotPoliciesID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "snapshotPolicyValue") + +payload := snapshotpolicy.SnapshotPolicyPatch{ + // ... +} + + +if err := client.SnapshotPoliciesUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/client.go new file mode 100644 index 000000000000..63c20fd6ea4d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/client.go @@ -0,0 +1,18 @@ +package snapshotpolicy + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPolicyClient struct { + Client autorest.Client + baseUri string +} + +func NewSnapshotPolicyClientWithBaseURI(endpoint string) SnapshotPolicyClient { + return SnapshotPolicyClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/id_netappaccount.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/id_netappaccount.go new file mode 100644 index 000000000000..726c28f92e9c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/id_netappaccount.go @@ -0,0 +1,124 @@ +package snapshotpolicy + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NetAppAccountId{} + +// NetAppAccountId is a struct representing the Resource ID for a Net App Account +type NetAppAccountId struct { + SubscriptionId string + ResourceGroupName string + AccountName string +} + +// NewNetAppAccountID returns a new NetAppAccountId struct +func NewNetAppAccountID(subscriptionId string, resourceGroupName string, accountName string) NetAppAccountId { + return NetAppAccountId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + } +} + +// ParseNetAppAccountID parses 'input' into a NetAppAccountId +func ParseNetAppAccountID(input string) (*NetAppAccountId, error) { + parser := resourceids.NewParserFromResourceIdType(NetAppAccountId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NetAppAccountId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNetAppAccountIDInsensitively parses 'input' case-insensitively into a NetAppAccountId +// note: this method should only be used for API response data and not user input +func ParseNetAppAccountIDInsensitively(input string) (*NetAppAccountId, error) { + parser := resourceids.NewParserFromResourceIdType(NetAppAccountId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NetAppAccountId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNetAppAccountID checks that 'input' can be parsed as a Net App Account ID +func ValidateNetAppAccountID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNetAppAccountID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Net App Account ID +func (id NetAppAccountId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Net App Account ID +func (id NetAppAccountId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + } +} + +// String returns a human-readable description of this Net App Account ID +func (id NetAppAccountId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + } + return fmt.Sprintf("Net App Account (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/id_snapshotpolicies.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/id_snapshotpolicies.go new file mode 100644 index 000000000000..f0662d3bf339 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/id_snapshotpolicies.go @@ -0,0 +1,137 @@ +package snapshotpolicy + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = SnapshotPoliciesId{} + +// SnapshotPoliciesId is a struct representing the Resource ID for a Snapshot Policies +type SnapshotPoliciesId struct { + SubscriptionId string + ResourceGroupName string + AccountName string + SnapshotPolicyName string +} + +// NewSnapshotPoliciesID returns a new SnapshotPoliciesId struct +func NewSnapshotPoliciesID(subscriptionId string, resourceGroupName string, accountName string, snapshotPolicyName string) SnapshotPoliciesId { + return SnapshotPoliciesId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + SnapshotPolicyName: snapshotPolicyName, + } +} + +// ParseSnapshotPoliciesID parses 'input' into a SnapshotPoliciesId +func ParseSnapshotPoliciesID(input string) (*SnapshotPoliciesId, error) { + parser := resourceids.NewParserFromResourceIdType(SnapshotPoliciesId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SnapshotPoliciesId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.SnapshotPolicyName, ok = parsed.Parsed["snapshotPolicyName"]; !ok { + return nil, fmt.Errorf("the segment 'snapshotPolicyName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseSnapshotPoliciesIDInsensitively parses 'input' case-insensitively into a SnapshotPoliciesId +// note: this method should only be used for API response data and not user input +func ParseSnapshotPoliciesIDInsensitively(input string) (*SnapshotPoliciesId, error) { + parser := resourceids.NewParserFromResourceIdType(SnapshotPoliciesId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SnapshotPoliciesId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.SnapshotPolicyName, ok = parsed.Parsed["snapshotPolicyName"]; !ok { + return nil, fmt.Errorf("the segment 'snapshotPolicyName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateSnapshotPoliciesID checks that 'input' can be parsed as a Snapshot Policies ID +func ValidateSnapshotPoliciesID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseSnapshotPoliciesID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Snapshot Policies ID +func (id SnapshotPoliciesId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s/snapshotPolicies/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName, id.SnapshotPolicyName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Snapshot Policies ID +func (id SnapshotPoliciesId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + resourceids.StaticSegment("staticSnapshotPolicies", "snapshotPolicies", "snapshotPolicies"), + resourceids.UserSpecifiedSegment("snapshotPolicyName", "snapshotPolicyValue"), + } +} + +// String returns a human-readable description of this Snapshot Policies ID +func (id SnapshotPoliciesId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + fmt.Sprintf("Snapshot Policy Name: %q", id.SnapshotPolicyName), + } + return fmt.Sprintf("Snapshot Policies (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciescreate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciescreate_autorest.go new file mode 100644 index 000000000000..43d25be8b167 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciescreate_autorest.go @@ -0,0 +1,68 @@ +package snapshotpolicy + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPoliciesCreateOperationResponse struct { + HttpResponse *http.Response + Model *SnapshotPolicy +} + +// SnapshotPoliciesCreate ... +func (c SnapshotPolicyClient) SnapshotPoliciesCreate(ctx context.Context, id SnapshotPoliciesId, input SnapshotPolicy) (result SnapshotPoliciesCreateOperationResponse, err error) { + req, err := c.preparerForSnapshotPoliciesCreate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesCreate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesCreate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForSnapshotPoliciesCreate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesCreate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForSnapshotPoliciesCreate prepares the SnapshotPoliciesCreate request. +func (c SnapshotPolicyClient) preparerForSnapshotPoliciesCreate(ctx context.Context, id SnapshotPoliciesId, input SnapshotPolicy) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForSnapshotPoliciesCreate handles the response to the SnapshotPoliciesCreate request. The method always +// closes the http.Response Body. +func (c SnapshotPolicyClient) responderForSnapshotPoliciesCreate(resp *http.Response) (result SnapshotPoliciesCreateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesdelete_autorest.go new file mode 100644 index 000000000000..0b2ba8905215 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesdelete_autorest.go @@ -0,0 +1,78 @@ +package snapshotpolicy + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPoliciesDeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// SnapshotPoliciesDelete ... +func (c SnapshotPolicyClient) SnapshotPoliciesDelete(ctx context.Context, id SnapshotPoliciesId) (result SnapshotPoliciesDeleteOperationResponse, err error) { + req, err := c.preparerForSnapshotPoliciesDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesDelete", nil, "Failure preparing request") + return + } + + result, err = c.senderForSnapshotPoliciesDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesDelete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// SnapshotPoliciesDeleteThenPoll performs SnapshotPoliciesDelete then polls until it's completed +func (c SnapshotPolicyClient) SnapshotPoliciesDeleteThenPoll(ctx context.Context, id SnapshotPoliciesId) error { + result, err := c.SnapshotPoliciesDelete(ctx, id) + if err != nil { + return fmt.Errorf("performing SnapshotPoliciesDelete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after SnapshotPoliciesDelete: %+v", err) + } + + return nil +} + +// preparerForSnapshotPoliciesDelete prepares the SnapshotPoliciesDelete request. +func (c SnapshotPolicyClient) preparerForSnapshotPoliciesDelete(ctx context.Context, id SnapshotPoliciesId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForSnapshotPoliciesDelete sends the SnapshotPoliciesDelete request. The method will close the +// http.Response Body if it receives an error. +func (c SnapshotPolicyClient) senderForSnapshotPoliciesDelete(ctx context.Context, req *http.Request) (future SnapshotPoliciesDeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesget_autorest.go new file mode 100644 index 000000000000..26d3741d8b6c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesget_autorest.go @@ -0,0 +1,67 @@ +package snapshotpolicy + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPoliciesGetOperationResponse struct { + HttpResponse *http.Response + Model *SnapshotPolicy +} + +// SnapshotPoliciesGet ... +func (c SnapshotPolicyClient) SnapshotPoliciesGet(ctx context.Context, id SnapshotPoliciesId) (result SnapshotPoliciesGetOperationResponse, err error) { + req, err := c.preparerForSnapshotPoliciesGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForSnapshotPoliciesGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForSnapshotPoliciesGet prepares the SnapshotPoliciesGet request. +func (c SnapshotPolicyClient) preparerForSnapshotPoliciesGet(ctx context.Context, id SnapshotPoliciesId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForSnapshotPoliciesGet handles the response to the SnapshotPoliciesGet request. The method always +// closes the http.Response Body. +func (c SnapshotPolicyClient) responderForSnapshotPoliciesGet(resp *http.Response) (result SnapshotPoliciesGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpolicieslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpolicieslist_autorest.go new file mode 100644 index 000000000000..b9f36c35c96f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpolicieslist_autorest.go @@ -0,0 +1,68 @@ +package snapshotpolicy + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPoliciesListOperationResponse struct { + HttpResponse *http.Response + Model *SnapshotPoliciesList +} + +// SnapshotPoliciesList ... +func (c SnapshotPolicyClient) SnapshotPoliciesList(ctx context.Context, id NetAppAccountId) (result SnapshotPoliciesListOperationResponse, err error) { + req, err := c.preparerForSnapshotPoliciesList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForSnapshotPoliciesList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesList", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForSnapshotPoliciesList prepares the SnapshotPoliciesList request. +func (c SnapshotPolicyClient) preparerForSnapshotPoliciesList(ctx context.Context, id NetAppAccountId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/snapshotPolicies", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForSnapshotPoliciesList handles the response to the SnapshotPoliciesList request. The method always +// closes the http.Response Body. +func (c SnapshotPolicyClient) responderForSnapshotPoliciesList(resp *http.Response) (result SnapshotPoliciesListOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesupdate_autorest.go new file mode 100644 index 000000000000..eea75a1378c0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/method_snapshotpoliciesupdate_autorest.go @@ -0,0 +1,79 @@ +package snapshotpolicy + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPoliciesUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// SnapshotPoliciesUpdate ... +func (c SnapshotPolicyClient) SnapshotPoliciesUpdate(ctx context.Context, id SnapshotPoliciesId, input SnapshotPolicyPatch) (result SnapshotPoliciesUpdateOperationResponse, err error) { + req, err := c.preparerForSnapshotPoliciesUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForSnapshotPoliciesUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshotpolicy.SnapshotPolicyClient", "SnapshotPoliciesUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// SnapshotPoliciesUpdateThenPoll performs SnapshotPoliciesUpdate then polls until it's completed +func (c SnapshotPolicyClient) SnapshotPoliciesUpdateThenPoll(ctx context.Context, id SnapshotPoliciesId, input SnapshotPolicyPatch) error { + result, err := c.SnapshotPoliciesUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing SnapshotPoliciesUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after SnapshotPoliciesUpdate: %+v", err) + } + + return nil +} + +// preparerForSnapshotPoliciesUpdate prepares the SnapshotPoliciesUpdate request. +func (c SnapshotPolicyClient) preparerForSnapshotPoliciesUpdate(ctx context.Context, id SnapshotPoliciesId, input SnapshotPolicyPatch) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForSnapshotPoliciesUpdate sends the SnapshotPoliciesUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c SnapshotPolicyClient) senderForSnapshotPoliciesUpdate(ctx context.Context, req *http.Request) (future SnapshotPoliciesUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_dailyschedule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_dailyschedule.go new file mode 100644 index 000000000000..bdafb72e6e09 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_dailyschedule.go @@ -0,0 +1,11 @@ +package snapshotpolicy + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DailySchedule struct { + Hour *int64 `json:"hour,omitempty"` + Minute *int64 `json:"minute,omitempty"` + SnapshotsToKeep *int64 `json:"snapshotsToKeep,omitempty"` + UsedBytes *int64 `json:"usedBytes,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_hourlyschedule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_hourlyschedule.go new file mode 100644 index 000000000000..a1e5d0fa0283 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_hourlyschedule.go @@ -0,0 +1,10 @@ +package snapshotpolicy + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type HourlySchedule struct { + Minute *int64 `json:"minute,omitempty"` + SnapshotsToKeep *int64 `json:"snapshotsToKeep,omitempty"` + UsedBytes *int64 `json:"usedBytes,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_monthlyschedule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_monthlyschedule.go new file mode 100644 index 000000000000..02cbcad6a592 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_monthlyschedule.go @@ -0,0 +1,12 @@ +package snapshotpolicy + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type MonthlySchedule struct { + DaysOfMonth *string `json:"daysOfMonth,omitempty"` + Hour *int64 `json:"hour,omitempty"` + Minute *int64 `json:"minute,omitempty"` + SnapshotsToKeep *int64 `json:"snapshotsToKeep,omitempty"` + UsedBytes *int64 `json:"usedBytes,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicieslist.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicieslist.go new file mode 100644 index 000000000000..910e2519adbe --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicieslist.go @@ -0,0 +1,8 @@ +package snapshotpolicy + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPoliciesList struct { + Value *[]SnapshotPolicy `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicy.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicy.go new file mode 100644 index 000000000000..310cfaaf1bb9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicy.go @@ -0,0 +1,19 @@ +package snapshotpolicy + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPolicy struct { + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties SnapshotPolicyProperties `json:"properties"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicypatch.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicypatch.go new file mode 100644 index 000000000000..76df9be172b9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicypatch.go @@ -0,0 +1,13 @@ +package snapshotpolicy + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPolicyPatch struct { + Id *string `json:"id,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SnapshotPolicyProperties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicyproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicyproperties.go new file mode 100644 index 000000000000..fb4fb0fcb05a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_snapshotpolicyproperties.go @@ -0,0 +1,13 @@ +package snapshotpolicy + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotPolicyProperties struct { + DailySchedule *DailySchedule `json:"dailySchedule,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + HourlySchedule *HourlySchedule `json:"hourlySchedule,omitempty"` + MonthlySchedule *MonthlySchedule `json:"monthlySchedule,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + WeeklySchedule *WeeklySchedule `json:"weeklySchedule,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_weeklyschedule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_weeklyschedule.go new file mode 100644 index 000000000000..128ece7ef5ef --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/model_weeklyschedule.go @@ -0,0 +1,12 @@ +package snapshotpolicy + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type WeeklySchedule struct { + Day *string `json:"day,omitempty"` + Hour *int64 `json:"hour,omitempty"` + Minute *int64 `json:"minute,omitempty"` + SnapshotsToKeep *int64 `json:"snapshotsToKeep,omitempty"` + UsedBytes *int64 `json:"usedBytes,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/version.go new file mode 100644 index 000000000000..00061163a3a7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy/version.go @@ -0,0 +1,12 @@ +package snapshotpolicy + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-10-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/snapshotpolicy/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/README.md new file mode 100644 index 000000000000..e6d357e24b68 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/README.md @@ -0,0 +1,111 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots` Documentation + +The `snapshots` SDK allows for interaction with the Azure Resource Manager Service `netapp` (API Version `2021-10-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots" +``` + + +### Client Initialization + +```go +client := snapshots.NewSnapshotsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `SnapshotsClient.Create` + +```go +ctx := context.TODO() +id := snapshots.NewSnapshotID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue", "snapshotValue") + +payload := snapshots.Snapshot{ + // ... +} + + +if err := client.CreateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `SnapshotsClient.Delete` + +```go +ctx := context.TODO() +id := snapshots.NewSnapshotID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue", "snapshotValue") + +if err := client.DeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `SnapshotsClient.Get` + +```go +ctx := context.TODO() +id := snapshots.NewSnapshotID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue", "snapshotValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SnapshotsClient.List` + +```go +ctx := context.TODO() +id := snapshots.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +read, err := client.List(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SnapshotsClient.RestoreFiles` + +```go +ctx := context.TODO() +id := snapshots.NewSnapshotID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue", "snapshotValue") + +payload := snapshots.SnapshotRestoreFiles{ + // ... +} + + +if err := client.RestoreFilesThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `SnapshotsClient.Update` + +```go +ctx := context.TODO() +id := snapshots.NewSnapshotID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue", "snapshotValue") +var payload interface{} + +if err := client.UpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/client.go new file mode 100644 index 000000000000..62d2a1323835 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/client.go @@ -0,0 +1,18 @@ +package snapshots + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotsClient struct { + Client autorest.Client + baseUri string +} + +func NewSnapshotsClientWithBaseURI(endpoint string) SnapshotsClient { + return SnapshotsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/id_snapshot.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/id_snapshot.go new file mode 100644 index 000000000000..d38fb8cb8f01 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/id_snapshot.go @@ -0,0 +1,163 @@ +package snapshots + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = SnapshotId{} + +// SnapshotId is a struct representing the Resource ID for a Snapshot +type SnapshotId struct { + SubscriptionId string + ResourceGroupName string + AccountName string + PoolName string + VolumeName string + SnapshotName string +} + +// NewSnapshotID returns a new SnapshotId struct +func NewSnapshotID(subscriptionId string, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) SnapshotId { + return SnapshotId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + PoolName: poolName, + VolumeName: volumeName, + SnapshotName: snapshotName, + } +} + +// ParseSnapshotID parses 'input' into a SnapshotId +func ParseSnapshotID(input string) (*SnapshotId, error) { + parser := resourceids.NewParserFromResourceIdType(SnapshotId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SnapshotId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + if id.VolumeName, ok = parsed.Parsed["volumeName"]; !ok { + return nil, fmt.Errorf("the segment 'volumeName' was not found in the resource id %q", input) + } + + if id.SnapshotName, ok = parsed.Parsed["snapshotName"]; !ok { + return nil, fmt.Errorf("the segment 'snapshotName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseSnapshotIDInsensitively parses 'input' case-insensitively into a SnapshotId +// note: this method should only be used for API response data and not user input +func ParseSnapshotIDInsensitively(input string) (*SnapshotId, error) { + parser := resourceids.NewParserFromResourceIdType(SnapshotId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SnapshotId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + if id.VolumeName, ok = parsed.Parsed["volumeName"]; !ok { + return nil, fmt.Errorf("the segment 'volumeName' was not found in the resource id %q", input) + } + + if id.SnapshotName, ok = parsed.Parsed["snapshotName"]; !ok { + return nil, fmt.Errorf("the segment 'snapshotName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateSnapshotID checks that 'input' can be parsed as a Snapshot ID +func ValidateSnapshotID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseSnapshotID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Snapshot ID +func (id SnapshotId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s/capacityPools/%s/volumes/%s/snapshots/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName, id.PoolName, id.VolumeName, id.SnapshotName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Snapshot ID +func (id SnapshotId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + resourceids.StaticSegment("staticCapacityPools", "capacityPools", "capacityPools"), + resourceids.UserSpecifiedSegment("poolName", "poolValue"), + resourceids.StaticSegment("staticVolumes", "volumes", "volumes"), + resourceids.UserSpecifiedSegment("volumeName", "volumeValue"), + resourceids.StaticSegment("staticSnapshots", "snapshots", "snapshots"), + resourceids.UserSpecifiedSegment("snapshotName", "snapshotValue"), + } +} + +// String returns a human-readable description of this Snapshot ID +func (id SnapshotId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + fmt.Sprintf("Pool Name: %q", id.PoolName), + fmt.Sprintf("Volume Name: %q", id.VolumeName), + fmt.Sprintf("Snapshot Name: %q", id.SnapshotName), + } + return fmt.Sprintf("Snapshot (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/id_volume.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/id_volume.go new file mode 100644 index 000000000000..c5cc73e141c7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/id_volume.go @@ -0,0 +1,150 @@ +package snapshots + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = VolumeId{} + +// VolumeId is a struct representing the Resource ID for a Volume +type VolumeId struct { + SubscriptionId string + ResourceGroupName string + AccountName string + PoolName string + VolumeName string +} + +// NewVolumeID returns a new VolumeId struct +func NewVolumeID(subscriptionId string, resourceGroupName string, accountName string, poolName string, volumeName string) VolumeId { + return VolumeId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + PoolName: poolName, + VolumeName: volumeName, + } +} + +// ParseVolumeID parses 'input' into a VolumeId +func ParseVolumeID(input string) (*VolumeId, error) { + parser := resourceids.NewParserFromResourceIdType(VolumeId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := VolumeId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + if id.VolumeName, ok = parsed.Parsed["volumeName"]; !ok { + return nil, fmt.Errorf("the segment 'volumeName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseVolumeIDInsensitively parses 'input' case-insensitively into a VolumeId +// note: this method should only be used for API response data and not user input +func ParseVolumeIDInsensitively(input string) (*VolumeId, error) { + parser := resourceids.NewParserFromResourceIdType(VolumeId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := VolumeId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + if id.VolumeName, ok = parsed.Parsed["volumeName"]; !ok { + return nil, fmt.Errorf("the segment 'volumeName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateVolumeID checks that 'input' can be parsed as a Volume ID +func ValidateVolumeID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseVolumeID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Volume ID +func (id VolumeId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s/capacityPools/%s/volumes/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName, id.PoolName, id.VolumeName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Volume ID +func (id VolumeId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + resourceids.StaticSegment("staticCapacityPools", "capacityPools", "capacityPools"), + resourceids.UserSpecifiedSegment("poolName", "poolValue"), + resourceids.StaticSegment("staticVolumes", "volumes", "volumes"), + resourceids.UserSpecifiedSegment("volumeName", "volumeValue"), + } +} + +// String returns a human-readable description of this Volume ID +func (id VolumeId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + fmt.Sprintf("Pool Name: %q", id.PoolName), + fmt.Sprintf("Volume Name: %q", id.VolumeName), + } + return fmt.Sprintf("Volume (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_create_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_create_autorest.go new file mode 100644 index 000000000000..90b33471adef --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_create_autorest.go @@ -0,0 +1,79 @@ +package snapshots + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Create ... +func (c SnapshotsClient) Create(ctx context.Context, id SnapshotId, input Snapshot) (result CreateOperationResponse, err error) { + req, err := c.preparerForCreate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "Create", nil, "Failure preparing request") + return + } + + result, err = c.senderForCreate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "Create", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CreateThenPoll performs Create then polls until it's completed +func (c SnapshotsClient) CreateThenPoll(ctx context.Context, id SnapshotId, input Snapshot) error { + result, err := c.Create(ctx, id, input) + if err != nil { + return fmt.Errorf("performing Create: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Create: %+v", err) + } + + return nil +} + +// preparerForCreate prepares the Create request. +func (c SnapshotsClient) preparerForCreate(ctx context.Context, id SnapshotId, input Snapshot) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCreate sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (c SnapshotsClient) senderForCreate(ctx context.Context, req *http.Request) (future CreateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_delete_autorest.go new file mode 100644 index 000000000000..55f7d9d07967 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_delete_autorest.go @@ -0,0 +1,78 @@ +package snapshots + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Delete ... +func (c SnapshotsClient) Delete(ctx context.Context, id SnapshotId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = c.senderForDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// DeleteThenPoll performs Delete then polls until it's completed +func (c SnapshotsClient) DeleteThenPoll(ctx context.Context, id SnapshotId) error { + result, err := c.Delete(ctx, id) + if err != nil { + return fmt.Errorf("performing Delete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Delete: %+v", err) + } + + return nil +} + +// preparerForDelete prepares the Delete request. +func (c SnapshotsClient) preparerForDelete(ctx context.Context, id SnapshotId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForDelete sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (c SnapshotsClient) senderForDelete(ctx context.Context, req *http.Request) (future DeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_get_autorest.go new file mode 100644 index 000000000000..4764bf6f0606 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_get_autorest.go @@ -0,0 +1,67 @@ +package snapshots + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *Snapshot +} + +// Get ... +func (c SnapshotsClient) Get(ctx context.Context, id SnapshotId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c SnapshotsClient) preparerForGet(ctx context.Context, id SnapshotId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c SnapshotsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_list_autorest.go new file mode 100644 index 000000000000..5d2f714bdc1f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_list_autorest.go @@ -0,0 +1,68 @@ +package snapshots + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *SnapshotsList +} + +// List ... +func (c SnapshotsClient) List(ctx context.Context, id VolumeId) (result ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForList prepares the List request. +func (c SnapshotsClient) preparerForList(ctx context.Context, id VolumeId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/snapshots", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c SnapshotsClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_restorefiles_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_restorefiles_autorest.go new file mode 100644 index 000000000000..18ef248aa733 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_restorefiles_autorest.go @@ -0,0 +1,79 @@ +package snapshots + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RestoreFilesOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// RestoreFiles ... +func (c SnapshotsClient) RestoreFiles(ctx context.Context, id SnapshotId, input SnapshotRestoreFiles) (result RestoreFilesOperationResponse, err error) { + req, err := c.preparerForRestoreFiles(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "RestoreFiles", nil, "Failure preparing request") + return + } + + result, err = c.senderForRestoreFiles(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "RestoreFiles", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// RestoreFilesThenPoll performs RestoreFiles then polls until it's completed +func (c SnapshotsClient) RestoreFilesThenPoll(ctx context.Context, id SnapshotId, input SnapshotRestoreFiles) error { + result, err := c.RestoreFiles(ctx, id, input) + if err != nil { + return fmt.Errorf("performing RestoreFiles: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after RestoreFiles: %+v", err) + } + + return nil +} + +// preparerForRestoreFiles prepares the RestoreFiles request. +func (c SnapshotsClient) preparerForRestoreFiles(ctx context.Context, id SnapshotId, input SnapshotRestoreFiles) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/restoreFiles", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForRestoreFiles sends the RestoreFiles request. The method will close the +// http.Response Body if it receives an error. +func (c SnapshotsClient) senderForRestoreFiles(ctx context.Context, req *http.Request) (future RestoreFilesOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_update_autorest.go new file mode 100644 index 000000000000..f96261c20b0b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/method_update_autorest.go @@ -0,0 +1,79 @@ +package snapshots + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Update ... +func (c SnapshotsClient) Update(ctx context.Context, id SnapshotId, input interface{}) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = c.senderForUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "snapshots.SnapshotsClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// UpdateThenPoll performs Update then polls until it's completed +func (c SnapshotsClient) UpdateThenPoll(ctx context.Context, id SnapshotId, input interface{}) error { + result, err := c.Update(ctx, id, input) + if err != nil { + return fmt.Errorf("performing Update: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Update: %+v", err) + } + + return nil +} + +// preparerForUpdate prepares the Update request. +func (c SnapshotsClient) preparerForUpdate(ctx context.Context, id SnapshotId, input interface{}) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForUpdate sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (c SnapshotsClient) senderForUpdate(ctx context.Context, req *http.Request) (future UpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshot.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshot.go new file mode 100644 index 000000000000..996c7160dd19 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshot.go @@ -0,0 +1,12 @@ +package snapshots + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Snapshot struct { + Id *string `json:"id,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties *SnapshotProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotproperties.go new file mode 100644 index 000000000000..fe60537eaaa9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotproperties.go @@ -0,0 +1,28 @@ +package snapshots + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotProperties struct { + Created *string `json:"created,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + SnapshotId *string `json:"snapshotId,omitempty"` +} + +func (o *SnapshotProperties) GetCreatedAsTime() (*time.Time, error) { + if o.Created == nil { + return nil, nil + } + return dates.ParseAsFormat(o.Created, "2006-01-02T15:04:05Z07:00") +} + +func (o *SnapshotProperties) SetCreatedAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.Created = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotrestorefiles.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotrestorefiles.go new file mode 100644 index 000000000000..de80d971dcf6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotrestorefiles.go @@ -0,0 +1,9 @@ +package snapshots + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotRestoreFiles struct { + DestinationPath *string `json:"destinationPath,omitempty"` + FilePaths []string `json:"filePaths"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotslist.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotslist.go new file mode 100644 index 000000000000..bf283b0d2ac6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/model_snapshotslist.go @@ -0,0 +1,8 @@ +package snapshots + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SnapshotsList struct { + Value *[]Snapshot `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/version.go new file mode 100644 index 000000000000..90179a6f56ae --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots/version.go @@ -0,0 +1,12 @@ +package snapshots + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-10-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/snapshots/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/README.md new file mode 100644 index 000000000000..c42f7262724b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/README.md @@ -0,0 +1,99 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes` Documentation + +The `volumes` SDK allows for interaction with the Azure Resource Manager Service `netapp` (API Version `2021-10-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes" +``` + + +### Client Initialization + +```go +client := volumes.NewVolumesClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `VolumesClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := volumes.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +payload := volumes.Volume{ + // ... +} + + +if err := client.CreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `VolumesClient.Delete` + +```go +ctx := context.TODO() +id := volumes.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +if err := client.DeleteThenPoll(ctx, id, volumes.DefaultDeleteOperationOptions()); err != nil { + // handle the error +} +``` + + +### Example Usage: `VolumesClient.Get` + +```go +ctx := context.TODO() +id := volumes.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `VolumesClient.List` + +```go +ctx := context.TODO() +id := volumes.NewCapacityPoolID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue") + +// alternatively `client.List(ctx, id)` can be used to do batched pagination +items, err := client.ListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `VolumesClient.Update` + +```go +ctx := context.TODO() +id := volumes.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +payload := volumes.VolumePatch{ + // ... +} + + +if err := client.UpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/client.go new file mode 100644 index 000000000000..d0a40573bf00 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/client.go @@ -0,0 +1,18 @@ +package volumes + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumesClient struct { + Client autorest.Client + baseUri string +} + +func NewVolumesClientWithBaseURI(endpoint string) VolumesClient { + return VolumesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/constants.go new file mode 100644 index 000000000000..4c9bed0d63be --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/constants.go @@ -0,0 +1,270 @@ +package volumes + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AvsDataStore string + +const ( + AvsDataStoreDisabled AvsDataStore = "Disabled" + AvsDataStoreEnabled AvsDataStore = "Enabled" +) + +func PossibleValuesForAvsDataStore() []string { + return []string{ + string(AvsDataStoreDisabled), + string(AvsDataStoreEnabled), + } +} + +func parseAvsDataStore(input string) (*AvsDataStore, error) { + vals := map[string]AvsDataStore{ + "disabled": AvsDataStoreDisabled, + "enabled": AvsDataStoreEnabled, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AvsDataStore(input) + return &out, nil +} + +type ChownMode string + +const ( + ChownModeRestricted ChownMode = "Restricted" + ChownModeUnrestricted ChownMode = "Unrestricted" +) + +func PossibleValuesForChownMode() []string { + return []string{ + string(ChownModeRestricted), + string(ChownModeUnrestricted), + } +} + +func parseChownMode(input string) (*ChownMode, error) { + vals := map[string]ChownMode{ + "restricted": ChownModeRestricted, + "unrestricted": ChownModeUnrestricted, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ChownMode(input) + return &out, nil +} + +type EnableSubvolumes string + +const ( + EnableSubvolumesDisabled EnableSubvolumes = "Disabled" + EnableSubvolumesEnabled EnableSubvolumes = "Enabled" +) + +func PossibleValuesForEnableSubvolumes() []string { + return []string{ + string(EnableSubvolumesDisabled), + string(EnableSubvolumesEnabled), + } +} + +func parseEnableSubvolumes(input string) (*EnableSubvolumes, error) { + vals := map[string]EnableSubvolumes{ + "disabled": EnableSubvolumesDisabled, + "enabled": EnableSubvolumesEnabled, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EnableSubvolumes(input) + return &out, nil +} + +type EndpointType string + +const ( + EndpointTypeDst EndpointType = "dst" + EndpointTypeSrc EndpointType = "src" +) + +func PossibleValuesForEndpointType() []string { + return []string{ + string(EndpointTypeDst), + string(EndpointTypeSrc), + } +} + +func parseEndpointType(input string) (*EndpointType, error) { + vals := map[string]EndpointType{ + "dst": EndpointTypeDst, + "src": EndpointTypeSrc, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EndpointType(input) + return &out, nil +} + +type NetworkFeatures string + +const ( + NetworkFeaturesBasic NetworkFeatures = "Basic" + NetworkFeaturesStandard NetworkFeatures = "Standard" +) + +func PossibleValuesForNetworkFeatures() []string { + return []string{ + string(NetworkFeaturesBasic), + string(NetworkFeaturesStandard), + } +} + +func parseNetworkFeatures(input string) (*NetworkFeatures, error) { + vals := map[string]NetworkFeatures{ + "basic": NetworkFeaturesBasic, + "standard": NetworkFeaturesStandard, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := NetworkFeatures(input) + return &out, nil +} + +type ReplicationSchedule string + +const ( + ReplicationScheduleDaily ReplicationSchedule = "daily" + ReplicationScheduleHourly ReplicationSchedule = "hourly" + ReplicationScheduleOneZerominutely ReplicationSchedule = "_10minutely" +) + +func PossibleValuesForReplicationSchedule() []string { + return []string{ + string(ReplicationScheduleDaily), + string(ReplicationScheduleHourly), + string(ReplicationScheduleOneZerominutely), + } +} + +func parseReplicationSchedule(input string) (*ReplicationSchedule, error) { + vals := map[string]ReplicationSchedule{ + "daily": ReplicationScheduleDaily, + "hourly": ReplicationScheduleHourly, + "_10minutely": ReplicationScheduleOneZerominutely, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ReplicationSchedule(input) + return &out, nil +} + +type SecurityStyle string + +const ( + SecurityStyleNtfs SecurityStyle = "ntfs" + SecurityStyleUnix SecurityStyle = "unix" +) + +func PossibleValuesForSecurityStyle() []string { + return []string{ + string(SecurityStyleNtfs), + string(SecurityStyleUnix), + } +} + +func parseSecurityStyle(input string) (*SecurityStyle, error) { + vals := map[string]SecurityStyle{ + "ntfs": SecurityStyleNtfs, + "unix": SecurityStyleUnix, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := SecurityStyle(input) + return &out, nil +} + +type ServiceLevel string + +const ( + ServiceLevelPremium ServiceLevel = "Premium" + ServiceLevelStandard ServiceLevel = "Standard" + ServiceLevelStandardZRS ServiceLevel = "StandardZRS" + ServiceLevelUltra ServiceLevel = "Ultra" +) + +func PossibleValuesForServiceLevel() []string { + return []string{ + string(ServiceLevelPremium), + string(ServiceLevelStandard), + string(ServiceLevelStandardZRS), + string(ServiceLevelUltra), + } +} + +func parseServiceLevel(input string) (*ServiceLevel, error) { + vals := map[string]ServiceLevel{ + "premium": ServiceLevelPremium, + "standard": ServiceLevelStandard, + "standardzrs": ServiceLevelStandardZRS, + "ultra": ServiceLevelUltra, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ServiceLevel(input) + return &out, nil +} + +type VolumeStorageToNetworkProximity string + +const ( + VolumeStorageToNetworkProximityDefault VolumeStorageToNetworkProximity = "Default" + VolumeStorageToNetworkProximityTOne VolumeStorageToNetworkProximity = "T1" + VolumeStorageToNetworkProximityTTwo VolumeStorageToNetworkProximity = "T2" +) + +func PossibleValuesForVolumeStorageToNetworkProximity() []string { + return []string{ + string(VolumeStorageToNetworkProximityDefault), + string(VolumeStorageToNetworkProximityTOne), + string(VolumeStorageToNetworkProximityTTwo), + } +} + +func parseVolumeStorageToNetworkProximity(input string) (*VolumeStorageToNetworkProximity, error) { + vals := map[string]VolumeStorageToNetworkProximity{ + "default": VolumeStorageToNetworkProximityDefault, + "t1": VolumeStorageToNetworkProximityTOne, + "t2": VolumeStorageToNetworkProximityTTwo, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := VolumeStorageToNetworkProximity(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/id_capacitypool.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/id_capacitypool.go new file mode 100644 index 000000000000..06f8b4531bd9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/id_capacitypool.go @@ -0,0 +1,137 @@ +package volumes + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = CapacityPoolId{} + +// CapacityPoolId is a struct representing the Resource ID for a Capacity Pool +type CapacityPoolId struct { + SubscriptionId string + ResourceGroupName string + AccountName string + PoolName string +} + +// NewCapacityPoolID returns a new CapacityPoolId struct +func NewCapacityPoolID(subscriptionId string, resourceGroupName string, accountName string, poolName string) CapacityPoolId { + return CapacityPoolId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + PoolName: poolName, + } +} + +// ParseCapacityPoolID parses 'input' into a CapacityPoolId +func ParseCapacityPoolID(input string) (*CapacityPoolId, error) { + parser := resourceids.NewParserFromResourceIdType(CapacityPoolId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := CapacityPoolId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseCapacityPoolIDInsensitively parses 'input' case-insensitively into a CapacityPoolId +// note: this method should only be used for API response data and not user input +func ParseCapacityPoolIDInsensitively(input string) (*CapacityPoolId, error) { + parser := resourceids.NewParserFromResourceIdType(CapacityPoolId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := CapacityPoolId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateCapacityPoolID checks that 'input' can be parsed as a Capacity Pool ID +func ValidateCapacityPoolID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseCapacityPoolID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Capacity Pool ID +func (id CapacityPoolId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s/capacityPools/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName, id.PoolName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Capacity Pool ID +func (id CapacityPoolId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + resourceids.StaticSegment("staticCapacityPools", "capacityPools", "capacityPools"), + resourceids.UserSpecifiedSegment("poolName", "poolValue"), + } +} + +// String returns a human-readable description of this Capacity Pool ID +func (id CapacityPoolId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + fmt.Sprintf("Pool Name: %q", id.PoolName), + } + return fmt.Sprintf("Capacity Pool (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/id_volume.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/id_volume.go new file mode 100644 index 000000000000..d4e93b387a44 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/id_volume.go @@ -0,0 +1,150 @@ +package volumes + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = VolumeId{} + +// VolumeId is a struct representing the Resource ID for a Volume +type VolumeId struct { + SubscriptionId string + ResourceGroupName string + AccountName string + PoolName string + VolumeName string +} + +// NewVolumeID returns a new VolumeId struct +func NewVolumeID(subscriptionId string, resourceGroupName string, accountName string, poolName string, volumeName string) VolumeId { + return VolumeId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + PoolName: poolName, + VolumeName: volumeName, + } +} + +// ParseVolumeID parses 'input' into a VolumeId +func ParseVolumeID(input string) (*VolumeId, error) { + parser := resourceids.NewParserFromResourceIdType(VolumeId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := VolumeId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + if id.VolumeName, ok = parsed.Parsed["volumeName"]; !ok { + return nil, fmt.Errorf("the segment 'volumeName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseVolumeIDInsensitively parses 'input' case-insensitively into a VolumeId +// note: this method should only be used for API response data and not user input +func ParseVolumeIDInsensitively(input string) (*VolumeId, error) { + parser := resourceids.NewParserFromResourceIdType(VolumeId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := VolumeId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + if id.VolumeName, ok = parsed.Parsed["volumeName"]; !ok { + return nil, fmt.Errorf("the segment 'volumeName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateVolumeID checks that 'input' can be parsed as a Volume ID +func ValidateVolumeID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseVolumeID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Volume ID +func (id VolumeId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s/capacityPools/%s/volumes/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName, id.PoolName, id.VolumeName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Volume ID +func (id VolumeId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + resourceids.StaticSegment("staticCapacityPools", "capacityPools", "capacityPools"), + resourceids.UserSpecifiedSegment("poolName", "poolValue"), + resourceids.StaticSegment("staticVolumes", "volumes", "volumes"), + resourceids.UserSpecifiedSegment("volumeName", "volumeValue"), + } +} + +// String returns a human-readable description of this Volume ID +func (id VolumeId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + fmt.Sprintf("Pool Name: %q", id.PoolName), + fmt.Sprintf("Volume Name: %q", id.VolumeName), + } + return fmt.Sprintf("Volume (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_createorupdate_autorest.go new file mode 100644 index 000000000000..ae61c0fe91ec --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_createorupdate_autorest.go @@ -0,0 +1,79 @@ +package volumes + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CreateOrUpdate ... +func (c VolumesClient) CreateOrUpdate(ctx context.Context, id VolumeId, input Volume) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CreateOrUpdateThenPoll performs CreateOrUpdate then polls until it's completed +func (c VolumesClient) CreateOrUpdateThenPoll(ctx context.Context, id VolumeId, input Volume) error { + result, err := c.CreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing CreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c VolumesClient) preparerForCreateOrUpdate(ctx context.Context, id VolumeId, input Volume) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCreateOrUpdate sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c VolumesClient) senderForCreateOrUpdate(ctx context.Context, req *http.Request) (future CreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_delete_autorest.go new file mode 100644 index 000000000000..1b97fdf87abf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_delete_autorest.go @@ -0,0 +1,107 @@ +package volumes + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +type DeleteOperationOptions struct { + ForceDelete *bool +} + +func DefaultDeleteOperationOptions() DeleteOperationOptions { + return DeleteOperationOptions{} +} + +func (o DeleteOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o DeleteOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.ForceDelete != nil { + out["forceDelete"] = *o.ForceDelete + } + + return out +} + +// Delete ... +func (c VolumesClient) Delete(ctx context.Context, id VolumeId, options DeleteOperationOptions) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = c.senderForDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// DeleteThenPoll performs Delete then polls until it's completed +func (c VolumesClient) DeleteThenPoll(ctx context.Context, id VolumeId, options DeleteOperationOptions) error { + result, err := c.Delete(ctx, id, options) + if err != nil { + return fmt.Errorf("performing Delete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Delete: %+v", err) + } + + return nil +} + +// preparerForDelete prepares the Delete request. +func (c VolumesClient) preparerForDelete(ctx context.Context, id VolumeId, options DeleteOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForDelete sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (c VolumesClient) senderForDelete(ctx context.Context, req *http.Request) (future DeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_get_autorest.go new file mode 100644 index 000000000000..f35ab8d36ba5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_get_autorest.go @@ -0,0 +1,67 @@ +package volumes + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *Volume +} + +// Get ... +func (c VolumesClient) Get(ctx context.Context, id VolumeId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c VolumesClient) preparerForGet(ctx context.Context, id VolumeId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c VolumesClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_list_autorest.go new file mode 100644 index 000000000000..40c311905e59 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_list_autorest.go @@ -0,0 +1,186 @@ +package volumes + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *[]Volume + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) +} + +type ListCompleteResult struct { + Items []Volume +} + +func (r ListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// List ... +func (c VolumesClient) List(ctx context.Context, id CapacityPoolId) (resp ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "List", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "List", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "List", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListComplete retrieves all of the results into a single object +func (c VolumesClient) ListComplete(ctx context.Context, id CapacityPoolId) (ListCompleteResult, error) { + return c.ListCompleteMatchingPredicate(ctx, id, VolumeOperationPredicate{}) +} + +// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c VolumesClient) ListCompleteMatchingPredicate(ctx context.Context, id CapacityPoolId, predicate VolumeOperationPredicate) (resp ListCompleteResult, err error) { + items := make([]Volume, 0) + + page, err := c.List(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForList prepares the List request. +func (c VolumesClient) preparerForList(ctx context.Context, id CapacityPoolId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/volumes", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListWithNextLink prepares the List request with the given nextLink token. +func (c VolumesClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c VolumesClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + type page struct { + Values []Volume `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { + req, err := c.preparerForListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_update_autorest.go new file mode 100644 index 000000000000..7e6872e1513e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/method_update_autorest.go @@ -0,0 +1,79 @@ +package volumes + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Update ... +func (c VolumesClient) Update(ctx context.Context, id VolumeId, input VolumePatch) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "Update", nil, "Failure preparing request") + return + } + + result, err = c.senderForUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "volumes.VolumesClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// UpdateThenPoll performs Update then polls until it's completed +func (c VolumesClient) UpdateThenPoll(ctx context.Context, id VolumeId, input VolumePatch) error { + result, err := c.Update(ctx, id, input) + if err != nil { + return fmt.Errorf("performing Update: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Update: %+v", err) + } + + return nil +} + +// preparerForUpdate prepares the Update request. +func (c VolumesClient) preparerForUpdate(ctx context.Context, id VolumeId, input VolumePatch) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForUpdate sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (c VolumesClient) senderForUpdate(ctx context.Context, req *http.Request) (future UpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_exportpolicyrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_exportpolicyrule.go new file mode 100644 index 000000000000..9b059c747578 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_exportpolicyrule.go @@ -0,0 +1,22 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ExportPolicyRule struct { + AllowedClients *string `json:"allowedClients,omitempty"` + ChownMode *ChownMode `json:"chownMode,omitempty"` + Cifs *bool `json:"cifs,omitempty"` + HasRootAccess *bool `json:"hasRootAccess,omitempty"` + Kerberos5ReadOnly *bool `json:"kerberos5ReadOnly,omitempty"` + Kerberos5ReadWrite *bool `json:"kerberos5ReadWrite,omitempty"` + Kerberos5iReadOnly *bool `json:"kerberos5iReadOnly,omitempty"` + Kerberos5iReadWrite *bool `json:"kerberos5iReadWrite,omitempty"` + Kerberos5pReadOnly *bool `json:"kerberos5pReadOnly,omitempty"` + Kerberos5pReadWrite *bool `json:"kerberos5pReadWrite,omitempty"` + Nfsv3 *bool `json:"nfsv3,omitempty"` + Nfsv41 *bool `json:"nfsv41,omitempty"` + RuleIndex *int64 `json:"ruleIndex,omitempty"` + UnixReadOnly *bool `json:"unixReadOnly,omitempty"` + UnixReadWrite *bool `json:"unixReadWrite,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_mounttargetproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_mounttargetproperties.go new file mode 100644 index 000000000000..b92b9edb4154 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_mounttargetproperties.go @@ -0,0 +1,11 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type MountTargetProperties struct { + FileSystemId string `json:"fileSystemId"` + IpAddress *string `json:"ipAddress,omitempty"` + MountTargetId *string `json:"mountTargetId,omitempty"` + SmbServerFqdn *string `json:"smbServerFqdn,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_placementkeyvaluepairs.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_placementkeyvaluepairs.go new file mode 100644 index 000000000000..588e9729c1e4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_placementkeyvaluepairs.go @@ -0,0 +1,9 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PlacementKeyValuePairs struct { + Key string `json:"key"` + Value string `json:"value"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_replicationobject.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_replicationobject.go new file mode 100644 index 000000000000..b7d6873811e2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_replicationobject.go @@ -0,0 +1,12 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ReplicationObject struct { + EndpointType *EndpointType `json:"endpointType,omitempty"` + RemoteVolumeRegion *string `json:"remoteVolumeRegion,omitempty"` + RemoteVolumeResourceId string `json:"remoteVolumeResourceId"` + ReplicationId *string `json:"replicationId,omitempty"` + ReplicationSchedule *ReplicationSchedule `json:"replicationSchedule,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volume.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volume.go new file mode 100644 index 000000000000..f92955c95e93 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volume.go @@ -0,0 +1,19 @@ +package volumes + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Volume struct { + Etag *string `json:"etag,omitempty"` + Id *string `json:"id,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties VolumeProperties `json:"properties"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumebackupproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumebackupproperties.go new file mode 100644 index 000000000000..1de25f15e330 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumebackupproperties.go @@ -0,0 +1,11 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumeBackupProperties struct { + BackupEnabled *bool `json:"backupEnabled,omitempty"` + BackupPolicyId *string `json:"backupPolicyId,omitempty"` + PolicyEnforced *bool `json:"policyEnforced,omitempty"` + VaultId *string `json:"vaultId,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatch.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatch.go new file mode 100644 index 000000000000..b39ea01aee89 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatch.go @@ -0,0 +1,13 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumePatch struct { + Id *string `json:"id,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Properties *VolumePatchProperties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchproperties.go new file mode 100644 index 000000000000..ed4479ca252b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchproperties.go @@ -0,0 +1,16 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumePatchProperties struct { + DataProtection *VolumePatchPropertiesDataProtection `json:"dataProtection,omitempty"` + DefaultGroupQuotaInKiBs *int64 `json:"defaultGroupQuotaInKiBs,omitempty"` + DefaultUserQuotaInKiBs *int64 `json:"defaultUserQuotaInKiBs,omitempty"` + ExportPolicy *VolumePatchPropertiesExportPolicy `json:"exportPolicy,omitempty"` + IsDefaultQuotaEnabled *bool `json:"isDefaultQuotaEnabled,omitempty"` + ServiceLevel *ServiceLevel `json:"serviceLevel,omitempty"` + ThroughputMibps *float64 `json:"throughputMibps,omitempty"` + UnixPermissions *string `json:"unixPermissions,omitempty"` + UsageThreshold *int64 `json:"usageThreshold,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchpropertiesdataprotection.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchpropertiesdataprotection.go new file mode 100644 index 000000000000..8c9edc10ff72 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchpropertiesdataprotection.go @@ -0,0 +1,9 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumePatchPropertiesDataProtection struct { + Backup *VolumeBackupProperties `json:"backup,omitempty"` + Snapshot *VolumeSnapshotProperties `json:"snapshot,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchpropertiesexportpolicy.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchpropertiesexportpolicy.go new file mode 100644 index 000000000000..ae83a5fc1b4f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepatchpropertiesexportpolicy.go @@ -0,0 +1,8 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumePatchPropertiesExportPolicy struct { + Rules *[]ExportPolicyRule `json:"rules,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumeproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumeproperties.go new file mode 100644 index 000000000000..6ae23e00b8da --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumeproperties.go @@ -0,0 +1,49 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumeProperties struct { + AvsDataStore *AvsDataStore `json:"avsDataStore,omitempty"` + BackupId *string `json:"backupId,omitempty"` + BaremetalTenantId *string `json:"baremetalTenantId,omitempty"` + CapacityPoolResourceId *string `json:"capacityPoolResourceId,omitempty"` + CloneProgress *int64 `json:"cloneProgress,omitempty"` + CoolAccess *bool `json:"coolAccess,omitempty"` + CoolnessPeriod *int64 `json:"coolnessPeriod,omitempty"` + CreationToken string `json:"creationToken"` + DataProtection *VolumePropertiesDataProtection `json:"dataProtection,omitempty"` + DefaultGroupQuotaInKiBs *int64 `json:"defaultGroupQuotaInKiBs,omitempty"` + DefaultUserQuotaInKiBs *int64 `json:"defaultUserQuotaInKiBs,omitempty"` + EnableSubvolumes *EnableSubvolumes `json:"enableSubvolumes,omitempty"` + EncryptionKeySource *string `json:"encryptionKeySource,omitempty"` + ExportPolicy *VolumePropertiesExportPolicy `json:"exportPolicy,omitempty"` + FileSystemId *string `json:"fileSystemId,omitempty"` + IsDefaultQuotaEnabled *bool `json:"isDefaultQuotaEnabled,omitempty"` + IsRestoring *bool `json:"isRestoring,omitempty"` + KerberosEnabled *bool `json:"kerberosEnabled,omitempty"` + LdapEnabled *bool `json:"ldapEnabled,omitempty"` + MaximumNumberOfFiles *int64 `json:"maximumNumberOfFiles,omitempty"` + MountTargets *[]MountTargetProperties `json:"mountTargets,omitempty"` + NetworkFeatures *NetworkFeatures `json:"networkFeatures,omitempty"` + NetworkSiblingSetId *string `json:"networkSiblingSetId,omitempty"` + PlacementRules *[]PlacementKeyValuePairs `json:"placementRules,omitempty"` + ProtocolTypes *[]string `json:"protocolTypes,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + ProximityPlacementGroup *string `json:"proximityPlacementGroup,omitempty"` + SecurityStyle *SecurityStyle `json:"securityStyle,omitempty"` + ServiceLevel *ServiceLevel `json:"serviceLevel,omitempty"` + SmbContinuouslyAvailable *bool `json:"smbContinuouslyAvailable,omitempty"` + SmbEncryption *bool `json:"smbEncryption,omitempty"` + SnapshotDirectoryVisible *bool `json:"snapshotDirectoryVisible,omitempty"` + SnapshotId *string `json:"snapshotId,omitempty"` + StorageToNetworkProximity *VolumeStorageToNetworkProximity `json:"storageToNetworkProximity,omitempty"` + SubnetId string `json:"subnetId"` + T2Network *string `json:"t2Network,omitempty"` + ThroughputMibps *float64 `json:"throughputMibps,omitempty"` + UnixPermissions *string `json:"unixPermissions,omitempty"` + UsageThreshold int64 `json:"usageThreshold"` + VolumeGroupName *string `json:"volumeGroupName,omitempty"` + VolumeSpecName *string `json:"volumeSpecName,omitempty"` + VolumeType *string `json:"volumeType,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepropertiesdataprotection.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepropertiesdataprotection.go new file mode 100644 index 000000000000..28163c70a51c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepropertiesdataprotection.go @@ -0,0 +1,10 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumePropertiesDataProtection struct { + Backup *VolumeBackupProperties `json:"backup,omitempty"` + Replication *ReplicationObject `json:"replication,omitempty"` + Snapshot *VolumeSnapshotProperties `json:"snapshot,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepropertiesexportpolicy.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepropertiesexportpolicy.go new file mode 100644 index 000000000000..fda5f4739dee --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumepropertiesexportpolicy.go @@ -0,0 +1,8 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumePropertiesExportPolicy struct { + Rules *[]ExportPolicyRule `json:"rules,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumesnapshotproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumesnapshotproperties.go new file mode 100644 index 000000000000..48aba2acce0d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/model_volumesnapshotproperties.go @@ -0,0 +1,8 @@ +package volumes + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumeSnapshotProperties struct { + SnapshotPolicyId *string `json:"snapshotPolicyId,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/predicates.go new file mode 100644 index 000000000000..536d6a70dc81 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/predicates.go @@ -0,0 +1,34 @@ +package volumes + +type VolumeOperationPredicate struct { + Etag *string + Id *string + Location *string + Name *string + Type *string +} + +func (p VolumeOperationPredicate) Matches(input Volume) bool { + + if p.Etag != nil && (input.Etag == nil && *p.Etag != *input.Etag) { + return false + } + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/version.go new file mode 100644 index 000000000000..55ac8a54fde6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes/version.go @@ -0,0 +1,12 @@ +package volumes + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-10-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/volumes/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/README.md new file mode 100644 index 000000000000..037bd15af1bb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/README.md @@ -0,0 +1,106 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication` Documentation + +The `volumesreplication` SDK allows for interaction with the Azure Resource Manager Service `netapp` (API Version `2021-10-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication" +``` + + +### Client Initialization + +```go +client := volumesreplication.NewVolumesReplicationClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `VolumesReplicationClient.VolumesAuthorizeReplication` + +```go +ctx := context.TODO() +id := volumesreplication.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +payload := volumesreplication.AuthorizeRequest{ + // ... +} + + +if err := client.VolumesAuthorizeReplicationThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `VolumesReplicationClient.VolumesBreakReplication` + +```go +ctx := context.TODO() +id := volumesreplication.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +payload := volumesreplication.BreakReplicationRequest{ + // ... +} + + +if err := client.VolumesBreakReplicationThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `VolumesReplicationClient.VolumesDeleteReplication` + +```go +ctx := context.TODO() +id := volumesreplication.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +if err := client.VolumesDeleteReplicationThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `VolumesReplicationClient.VolumesReInitializeReplication` + +```go +ctx := context.TODO() +id := volumesreplication.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +if err := client.VolumesReInitializeReplicationThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `VolumesReplicationClient.VolumesReplicationStatus` + +```go +ctx := context.TODO() +id := volumesreplication.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +read, err := client.VolumesReplicationStatus(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `VolumesReplicationClient.VolumesResyncReplication` + +```go +ctx := context.TODO() +id := volumesreplication.NewVolumeID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "poolValue", "volumeValue") + +if err := client.VolumesResyncReplicationThenPoll(ctx, id); err != nil { + // handle the error +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/client.go new file mode 100644 index 000000000000..64a4d559d37e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/client.go @@ -0,0 +1,18 @@ +package volumesreplication + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumesReplicationClient struct { + Client autorest.Client + baseUri string +} + +func NewVolumesReplicationClientWithBaseURI(endpoint string) VolumesReplicationClient { + return VolumesReplicationClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/constants.go new file mode 100644 index 000000000000..6b67c17d5884 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/constants.go @@ -0,0 +1,65 @@ +package volumesreplication + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type MirrorState string + +const ( + MirrorStateBroken MirrorState = "Broken" + MirrorStateMirrored MirrorState = "Mirrored" + MirrorStateUninitialized MirrorState = "Uninitialized" +) + +func PossibleValuesForMirrorState() []string { + return []string{ + string(MirrorStateBroken), + string(MirrorStateMirrored), + string(MirrorStateUninitialized), + } +} + +func parseMirrorState(input string) (*MirrorState, error) { + vals := map[string]MirrorState{ + "broken": MirrorStateBroken, + "mirrored": MirrorStateMirrored, + "uninitialized": MirrorStateUninitialized, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := MirrorState(input) + return &out, nil +} + +type RelationshipStatus string + +const ( + RelationshipStatusIdle RelationshipStatus = "Idle" + RelationshipStatusTransferring RelationshipStatus = "Transferring" +) + +func PossibleValuesForRelationshipStatus() []string { + return []string{ + string(RelationshipStatusIdle), + string(RelationshipStatusTransferring), + } +} + +func parseRelationshipStatus(input string) (*RelationshipStatus, error) { + vals := map[string]RelationshipStatus{ + "idle": RelationshipStatusIdle, + "transferring": RelationshipStatusTransferring, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := RelationshipStatus(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/id_volume.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/id_volume.go new file mode 100644 index 000000000000..c88adaf98587 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/id_volume.go @@ -0,0 +1,150 @@ +package volumesreplication + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = VolumeId{} + +// VolumeId is a struct representing the Resource ID for a Volume +type VolumeId struct { + SubscriptionId string + ResourceGroupName string + AccountName string + PoolName string + VolumeName string +} + +// NewVolumeID returns a new VolumeId struct +func NewVolumeID(subscriptionId string, resourceGroupName string, accountName string, poolName string, volumeName string) VolumeId { + return VolumeId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + PoolName: poolName, + VolumeName: volumeName, + } +} + +// ParseVolumeID parses 'input' into a VolumeId +func ParseVolumeID(input string) (*VolumeId, error) { + parser := resourceids.NewParserFromResourceIdType(VolumeId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := VolumeId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + if id.VolumeName, ok = parsed.Parsed["volumeName"]; !ok { + return nil, fmt.Errorf("the segment 'volumeName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseVolumeIDInsensitively parses 'input' case-insensitively into a VolumeId +// note: this method should only be used for API response data and not user input +func ParseVolumeIDInsensitively(input string) (*VolumeId, error) { + parser := resourceids.NewParserFromResourceIdType(VolumeId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := VolumeId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.PoolName, ok = parsed.Parsed["poolName"]; !ok { + return nil, fmt.Errorf("the segment 'poolName' was not found in the resource id %q", input) + } + + if id.VolumeName, ok = parsed.Parsed["volumeName"]; !ok { + return nil, fmt.Errorf("the segment 'volumeName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateVolumeID checks that 'input' can be parsed as a Volume ID +func ValidateVolumeID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseVolumeID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Volume ID +func (id VolumeId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.NetApp/netAppAccounts/%s/capacityPools/%s/volumes/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName, id.PoolName, id.VolumeName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Volume ID +func (id VolumeId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftNetApp", "Microsoft.NetApp", "Microsoft.NetApp"), + resourceids.StaticSegment("staticNetAppAccounts", "netAppAccounts", "netAppAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + resourceids.StaticSegment("staticCapacityPools", "capacityPools", "capacityPools"), + resourceids.UserSpecifiedSegment("poolName", "poolValue"), + resourceids.StaticSegment("staticVolumes", "volumes", "volumes"), + resourceids.UserSpecifiedSegment("volumeName", "volumeValue"), + } +} + +// String returns a human-readable description of this Volume ID +func (id VolumeId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + fmt.Sprintf("Pool Name: %q", id.PoolName), + fmt.Sprintf("Volume Name: %q", id.VolumeName), + } + return fmt.Sprintf("Volume (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesauthorizereplication_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesauthorizereplication_autorest.go new file mode 100644 index 000000000000..76b9f035e73f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesauthorizereplication_autorest.go @@ -0,0 +1,79 @@ +package volumesreplication + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumesAuthorizeReplicationOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// VolumesAuthorizeReplication ... +func (c VolumesReplicationClient) VolumesAuthorizeReplication(ctx context.Context, id VolumeId, input AuthorizeRequest) (result VolumesAuthorizeReplicationOperationResponse, err error) { + req, err := c.preparerForVolumesAuthorizeReplication(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesAuthorizeReplication", nil, "Failure preparing request") + return + } + + result, err = c.senderForVolumesAuthorizeReplication(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesAuthorizeReplication", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// VolumesAuthorizeReplicationThenPoll performs VolumesAuthorizeReplication then polls until it's completed +func (c VolumesReplicationClient) VolumesAuthorizeReplicationThenPoll(ctx context.Context, id VolumeId, input AuthorizeRequest) error { + result, err := c.VolumesAuthorizeReplication(ctx, id, input) + if err != nil { + return fmt.Errorf("performing VolumesAuthorizeReplication: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after VolumesAuthorizeReplication: %+v", err) + } + + return nil +} + +// preparerForVolumesAuthorizeReplication prepares the VolumesAuthorizeReplication request. +func (c VolumesReplicationClient) preparerForVolumesAuthorizeReplication(ctx context.Context, id VolumeId, input AuthorizeRequest) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/authorizeReplication", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForVolumesAuthorizeReplication sends the VolumesAuthorizeReplication request. The method will close the +// http.Response Body if it receives an error. +func (c VolumesReplicationClient) senderForVolumesAuthorizeReplication(ctx context.Context, req *http.Request) (future VolumesAuthorizeReplicationOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesbreakreplication_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesbreakreplication_autorest.go new file mode 100644 index 000000000000..2d1739198e38 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesbreakreplication_autorest.go @@ -0,0 +1,79 @@ +package volumesreplication + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumesBreakReplicationOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// VolumesBreakReplication ... +func (c VolumesReplicationClient) VolumesBreakReplication(ctx context.Context, id VolumeId, input BreakReplicationRequest) (result VolumesBreakReplicationOperationResponse, err error) { + req, err := c.preparerForVolumesBreakReplication(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesBreakReplication", nil, "Failure preparing request") + return + } + + result, err = c.senderForVolumesBreakReplication(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesBreakReplication", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// VolumesBreakReplicationThenPoll performs VolumesBreakReplication then polls until it's completed +func (c VolumesReplicationClient) VolumesBreakReplicationThenPoll(ctx context.Context, id VolumeId, input BreakReplicationRequest) error { + result, err := c.VolumesBreakReplication(ctx, id, input) + if err != nil { + return fmt.Errorf("performing VolumesBreakReplication: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after VolumesBreakReplication: %+v", err) + } + + return nil +} + +// preparerForVolumesBreakReplication prepares the VolumesBreakReplication request. +func (c VolumesReplicationClient) preparerForVolumesBreakReplication(ctx context.Context, id VolumeId, input BreakReplicationRequest) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/breakReplication", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForVolumesBreakReplication sends the VolumesBreakReplication request. The method will close the +// http.Response Body if it receives an error. +func (c VolumesReplicationClient) senderForVolumesBreakReplication(ctx context.Context, req *http.Request) (future VolumesBreakReplicationOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesdeletereplication_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesdeletereplication_autorest.go new file mode 100644 index 000000000000..6dd32453b2de --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesdeletereplication_autorest.go @@ -0,0 +1,78 @@ +package volumesreplication + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumesDeleteReplicationOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// VolumesDeleteReplication ... +func (c VolumesReplicationClient) VolumesDeleteReplication(ctx context.Context, id VolumeId) (result VolumesDeleteReplicationOperationResponse, err error) { + req, err := c.preparerForVolumesDeleteReplication(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesDeleteReplication", nil, "Failure preparing request") + return + } + + result, err = c.senderForVolumesDeleteReplication(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesDeleteReplication", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// VolumesDeleteReplicationThenPoll performs VolumesDeleteReplication then polls until it's completed +func (c VolumesReplicationClient) VolumesDeleteReplicationThenPoll(ctx context.Context, id VolumeId) error { + result, err := c.VolumesDeleteReplication(ctx, id) + if err != nil { + return fmt.Errorf("performing VolumesDeleteReplication: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after VolumesDeleteReplication: %+v", err) + } + + return nil +} + +// preparerForVolumesDeleteReplication prepares the VolumesDeleteReplication request. +func (c VolumesReplicationClient) preparerForVolumesDeleteReplication(ctx context.Context, id VolumeId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/deleteReplication", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForVolumesDeleteReplication sends the VolumesDeleteReplication request. The method will close the +// http.Response Body if it receives an error. +func (c VolumesReplicationClient) senderForVolumesDeleteReplication(ctx context.Context, req *http.Request) (future VolumesDeleteReplicationOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesreinitializereplication_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesreinitializereplication_autorest.go new file mode 100644 index 000000000000..f894605753fa --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesreinitializereplication_autorest.go @@ -0,0 +1,78 @@ +package volumesreplication + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumesReInitializeReplicationOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// VolumesReInitializeReplication ... +func (c VolumesReplicationClient) VolumesReInitializeReplication(ctx context.Context, id VolumeId) (result VolumesReInitializeReplicationOperationResponse, err error) { + req, err := c.preparerForVolumesReInitializeReplication(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesReInitializeReplication", nil, "Failure preparing request") + return + } + + result, err = c.senderForVolumesReInitializeReplication(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesReInitializeReplication", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// VolumesReInitializeReplicationThenPoll performs VolumesReInitializeReplication then polls until it's completed +func (c VolumesReplicationClient) VolumesReInitializeReplicationThenPoll(ctx context.Context, id VolumeId) error { + result, err := c.VolumesReInitializeReplication(ctx, id) + if err != nil { + return fmt.Errorf("performing VolumesReInitializeReplication: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after VolumesReInitializeReplication: %+v", err) + } + + return nil +} + +// preparerForVolumesReInitializeReplication prepares the VolumesReInitializeReplication request. +func (c VolumesReplicationClient) preparerForVolumesReInitializeReplication(ctx context.Context, id VolumeId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/reinitializeReplication", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForVolumesReInitializeReplication sends the VolumesReInitializeReplication request. The method will close the +// http.Response Body if it receives an error. +func (c VolumesReplicationClient) senderForVolumesReInitializeReplication(ctx context.Context, req *http.Request) (future VolumesReInitializeReplicationOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesreplicationstatus_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesreplicationstatus_autorest.go new file mode 100644 index 000000000000..12b0382b0cd4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesreplicationstatus_autorest.go @@ -0,0 +1,68 @@ +package volumesreplication + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumesReplicationStatusOperationResponse struct { + HttpResponse *http.Response + Model *ReplicationStatus +} + +// VolumesReplicationStatus ... +func (c VolumesReplicationClient) VolumesReplicationStatus(ctx context.Context, id VolumeId) (result VolumesReplicationStatusOperationResponse, err error) { + req, err := c.preparerForVolumesReplicationStatus(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesReplicationStatus", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesReplicationStatus", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForVolumesReplicationStatus(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesReplicationStatus", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForVolumesReplicationStatus prepares the VolumesReplicationStatus request. +func (c VolumesReplicationClient) preparerForVolumesReplicationStatus(ctx context.Context, id VolumeId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/replicationStatus", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForVolumesReplicationStatus handles the response to the VolumesReplicationStatus request. The method always +// closes the http.Response Body. +func (c VolumesReplicationClient) responderForVolumesReplicationStatus(resp *http.Response) (result VolumesReplicationStatusOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesresyncreplication_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesresyncreplication_autorest.go new file mode 100644 index 000000000000..05f303966fa5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/method_volumesresyncreplication_autorest.go @@ -0,0 +1,78 @@ +package volumesreplication + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type VolumesResyncReplicationOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// VolumesResyncReplication ... +func (c VolumesReplicationClient) VolumesResyncReplication(ctx context.Context, id VolumeId) (result VolumesResyncReplicationOperationResponse, err error) { + req, err := c.preparerForVolumesResyncReplication(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesResyncReplication", nil, "Failure preparing request") + return + } + + result, err = c.senderForVolumesResyncReplication(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "volumesreplication.VolumesReplicationClient", "VolumesResyncReplication", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// VolumesResyncReplicationThenPoll performs VolumesResyncReplication then polls until it's completed +func (c VolumesReplicationClient) VolumesResyncReplicationThenPoll(ctx context.Context, id VolumeId) error { + result, err := c.VolumesResyncReplication(ctx, id) + if err != nil { + return fmt.Errorf("performing VolumesResyncReplication: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after VolumesResyncReplication: %+v", err) + } + + return nil +} + +// preparerForVolumesResyncReplication prepares the VolumesResyncReplication request. +func (c VolumesReplicationClient) preparerForVolumesResyncReplication(ctx context.Context, id VolumeId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/resyncReplication", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForVolumesResyncReplication sends the VolumesResyncReplication request. The method will close the +// http.Response Body if it receives an error. +func (c VolumesReplicationClient) senderForVolumesResyncReplication(ctx context.Context, req *http.Request) (future VolumesResyncReplicationOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_authorizerequest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_authorizerequest.go new file mode 100644 index 000000000000..ff1cefa31efa --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_authorizerequest.go @@ -0,0 +1,8 @@ +package volumesreplication + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AuthorizeRequest struct { + RemoteVolumeResourceId *string `json:"remoteVolumeResourceId,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_breakreplicationrequest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_breakreplicationrequest.go new file mode 100644 index 000000000000..b6a0a179a9c6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_breakreplicationrequest.go @@ -0,0 +1,8 @@ +package volumesreplication + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type BreakReplicationRequest struct { + ForceBreakReplication *bool `json:"forceBreakReplication,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_replicationstatus.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_replicationstatus.go new file mode 100644 index 000000000000..2a79dddf7a40 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/model_replicationstatus.go @@ -0,0 +1,12 @@ +package volumesreplication + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ReplicationStatus struct { + ErrorMessage *string `json:"errorMessage,omitempty"` + Healthy *bool `json:"healthy,omitempty"` + MirrorState *MirrorState `json:"mirrorState,omitempty"` + RelationshipStatus *RelationshipStatus `json:"relationshipStatus,omitempty"` + TotalProgress *string `json:"totalProgress,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/version.go new file mode 100644 index 000000000000..5a6266022a22 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication/version.go @@ -0,0 +1,12 @@ +package volumesreplication + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-10-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/volumesreplication/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/README.md new file mode 100644 index 000000000000..1c697f60f778 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/README.md @@ -0,0 +1,432 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights` Documentation + +The `policyinsights` SDK allows for interaction with the Azure Resource Manager Service `policyinsights` (API Version `2021-10-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights" +``` + + +### Client Initialization + +```go +client := policyinsights.NewPolicyInsightsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsCancelAtManagementGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviders2RemediationID("managementGroupIdValue", "remediationValue") + +read, err := client.RemediationsCancelAtManagementGroup(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsCancelAtResource` + +```go +ctx := context.TODO() +id := policyinsights.NewScopedRemediationID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "remediationValue") + +read, err := client.RemediationsCancelAtResource(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsCancelAtResourceGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviderRemediationID("12345678-1234-9876-4563-123456789012", "example-resource-group", "remediationValue") + +read, err := client.RemediationsCancelAtResourceGroup(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsCancelAtSubscription` + +```go +ctx := context.TODO() +id := policyinsights.NewRemediationID("12345678-1234-9876-4563-123456789012", "remediationValue") + +read, err := client.RemediationsCancelAtSubscription(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsCreateOrUpdateAtManagementGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviders2RemediationID("managementGroupIdValue", "remediationValue") + +payload := policyinsights.Remediation{ + // ... +} + + +read, err := client.RemediationsCreateOrUpdateAtManagementGroup(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsCreateOrUpdateAtResource` + +```go +ctx := context.TODO() +id := policyinsights.NewScopedRemediationID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "remediationValue") + +payload := policyinsights.Remediation{ + // ... +} + + +read, err := client.RemediationsCreateOrUpdateAtResource(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsCreateOrUpdateAtResourceGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviderRemediationID("12345678-1234-9876-4563-123456789012", "example-resource-group", "remediationValue") + +payload := policyinsights.Remediation{ + // ... +} + + +read, err := client.RemediationsCreateOrUpdateAtResourceGroup(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsCreateOrUpdateAtSubscription` + +```go +ctx := context.TODO() +id := policyinsights.NewRemediationID("12345678-1234-9876-4563-123456789012", "remediationValue") + +payload := policyinsights.Remediation{ + // ... +} + + +read, err := client.RemediationsCreateOrUpdateAtSubscription(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsDeleteAtManagementGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviders2RemediationID("managementGroupIdValue", "remediationValue") + +read, err := client.RemediationsDeleteAtManagementGroup(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsDeleteAtResource` + +```go +ctx := context.TODO() +id := policyinsights.NewScopedRemediationID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "remediationValue") + +read, err := client.RemediationsDeleteAtResource(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsDeleteAtResourceGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviderRemediationID("12345678-1234-9876-4563-123456789012", "example-resource-group", "remediationValue") + +read, err := client.RemediationsDeleteAtResourceGroup(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsDeleteAtSubscription` + +```go +ctx := context.TODO() +id := policyinsights.NewRemediationID("12345678-1234-9876-4563-123456789012", "remediationValue") + +read, err := client.RemediationsDeleteAtSubscription(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsGetAtManagementGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviders2RemediationID("managementGroupIdValue", "remediationValue") + +read, err := client.RemediationsGetAtManagementGroup(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsGetAtResource` + +```go +ctx := context.TODO() +id := policyinsights.NewScopedRemediationID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "remediationValue") + +read, err := client.RemediationsGetAtResource(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsGetAtResourceGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviderRemediationID("12345678-1234-9876-4563-123456789012", "example-resource-group", "remediationValue") + +read, err := client.RemediationsGetAtResourceGroup(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsGetAtSubscription` + +```go +ctx := context.TODO() +id := policyinsights.NewRemediationID("12345678-1234-9876-4563-123456789012", "remediationValue") + +read, err := client.RemediationsGetAtSubscription(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsListDeploymentsAtManagementGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviders2RemediationID("managementGroupIdValue", "remediationValue") + +// alternatively `client.RemediationsListDeploymentsAtManagementGroup(ctx, id, policyinsights.DefaultRemediationsListDeploymentsAtManagementGroupOperationOptions())` can be used to do batched pagination +items, err := client.RemediationsListDeploymentsAtManagementGroupComplete(ctx, id, policyinsights.DefaultRemediationsListDeploymentsAtManagementGroupOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsListDeploymentsAtResource` + +```go +ctx := context.TODO() +id := policyinsights.NewScopedRemediationID("/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group", "remediationValue") + +// alternatively `client.RemediationsListDeploymentsAtResource(ctx, id, policyinsights.DefaultRemediationsListDeploymentsAtResourceOperationOptions())` can be used to do batched pagination +items, err := client.RemediationsListDeploymentsAtResourceComplete(ctx, id, policyinsights.DefaultRemediationsListDeploymentsAtResourceOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsListDeploymentsAtResourceGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewProviderRemediationID("12345678-1234-9876-4563-123456789012", "example-resource-group", "remediationValue") + +// alternatively `client.RemediationsListDeploymentsAtResourceGroup(ctx, id, policyinsights.DefaultRemediationsListDeploymentsAtResourceGroupOperationOptions())` can be used to do batched pagination +items, err := client.RemediationsListDeploymentsAtResourceGroupComplete(ctx, id, policyinsights.DefaultRemediationsListDeploymentsAtResourceGroupOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsListDeploymentsAtSubscription` + +```go +ctx := context.TODO() +id := policyinsights.NewRemediationID("12345678-1234-9876-4563-123456789012", "remediationValue") + +// alternatively `client.RemediationsListDeploymentsAtSubscription(ctx, id, policyinsights.DefaultRemediationsListDeploymentsAtSubscriptionOperationOptions())` can be used to do batched pagination +items, err := client.RemediationsListDeploymentsAtSubscriptionComplete(ctx, id, policyinsights.DefaultRemediationsListDeploymentsAtSubscriptionOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsListForManagementGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewManagementGroupID("managementGroupIdValue") + +// alternatively `client.RemediationsListForManagementGroup(ctx, id, policyinsights.DefaultRemediationsListForManagementGroupOperationOptions())` can be used to do batched pagination +items, err := client.RemediationsListForManagementGroupComplete(ctx, id, policyinsights.DefaultRemediationsListForManagementGroupOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsListForResource` + +```go +ctx := context.TODO() +id := policyinsights.NewScopeID() + +// alternatively `client.RemediationsListForResource(ctx, id, policyinsights.DefaultRemediationsListForResourceOperationOptions())` can be used to do batched pagination +items, err := client.RemediationsListForResourceComplete(ctx, id, policyinsights.DefaultRemediationsListForResourceOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsListForResourceGroup` + +```go +ctx := context.TODO() +id := policyinsights.NewResourceGroupID() + +// alternatively `client.RemediationsListForResourceGroup(ctx, id, policyinsights.DefaultRemediationsListForResourceGroupOperationOptions())` can be used to do batched pagination +items, err := client.RemediationsListForResourceGroupComplete(ctx, id, policyinsights.DefaultRemediationsListForResourceGroupOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `PolicyInsightsClient.RemediationsListForSubscription` + +```go +ctx := context.TODO() +id := policyinsights.NewSubscriptionID() + +// alternatively `client.RemediationsListForSubscription(ctx, id, policyinsights.DefaultRemediationsListForSubscriptionOperationOptions())` can be used to do batched pagination +items, err := client.RemediationsListForSubscriptionComplete(ctx, id, policyinsights.DefaultRemediationsListForSubscriptionOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/client.go new file mode 100644 index 000000000000..1f34a06b408f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/client.go @@ -0,0 +1,18 @@ +package policyinsights + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PolicyInsightsClient struct { + Client autorest.Client + baseUri string +} + +func NewPolicyInsightsClientWithBaseURI(endpoint string) PolicyInsightsClient { + return PolicyInsightsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/constants.go new file mode 100644 index 000000000000..26a1a1a6abe5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/constants.go @@ -0,0 +1,34 @@ +package policyinsights + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ResourceDiscoveryMode string + +const ( + ResourceDiscoveryModeExistingNonCompliant ResourceDiscoveryMode = "ExistingNonCompliant" + ResourceDiscoveryModeReEvaluateCompliance ResourceDiscoveryMode = "ReEvaluateCompliance" +) + +func PossibleValuesForResourceDiscoveryMode() []string { + return []string{ + string(ResourceDiscoveryModeExistingNonCompliant), + string(ResourceDiscoveryModeReEvaluateCompliance), + } +} + +func parseResourceDiscoveryMode(input string) (*ResourceDiscoveryMode, error) { + vals := map[string]ResourceDiscoveryMode{ + "existingnoncompliant": ResourceDiscoveryModeExistingNonCompliant, + "reevaluatecompliance": ResourceDiscoveryModeReEvaluateCompliance, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ResourceDiscoveryMode(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_managementgroup.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_managementgroup.go new file mode 100644 index 000000000000..1f098ef546f4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_managementgroup.go @@ -0,0 +1,98 @@ +package policyinsights + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ManagementGroupId{} + +// ManagementGroupId is a struct representing the Resource ID for a Management Group +type ManagementGroupId struct { + ManagementGroupId string +} + +// NewManagementGroupID returns a new ManagementGroupId struct +func NewManagementGroupID(managementGroupId string) ManagementGroupId { + return ManagementGroupId{ + ManagementGroupId: managementGroupId, + } +} + +// ParseManagementGroupID parses 'input' into a ManagementGroupId +func ParseManagementGroupID(input string) (*ManagementGroupId, error) { + parser := resourceids.NewParserFromResourceIdType(ManagementGroupId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ManagementGroupId{} + + if id.ManagementGroupId, ok = parsed.Parsed["managementGroupId"]; !ok { + return nil, fmt.Errorf("the segment 'managementGroupId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseManagementGroupIDInsensitively parses 'input' case-insensitively into a ManagementGroupId +// note: this method should only be used for API response data and not user input +func ParseManagementGroupIDInsensitively(input string) (*ManagementGroupId, error) { + parser := resourceids.NewParserFromResourceIdType(ManagementGroupId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ManagementGroupId{} + + if id.ManagementGroupId, ok = parsed.Parsed["managementGroupId"]; !ok { + return nil, fmt.Errorf("the segment 'managementGroupId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateManagementGroupID checks that 'input' can be parsed as a Management Group ID +func ValidateManagementGroupID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseManagementGroupID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Management Group ID +func (id ManagementGroupId) ID() string { + fmtString := "/providers/Microsoft.Management/managementGroups/%s" + return fmt.Sprintf(fmtString, id.ManagementGroupId) +} + +// Segments returns a slice of Resource ID Segments which comprise this Management Group ID +func (id ManagementGroupId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.StaticSegment("managementGroupsNamespace", "Microsoft.Management", "Microsoft.Management"), + resourceids.StaticSegment("staticManagementGroups", "managementGroups", "managementGroups"), + resourceids.UserSpecifiedSegment("managementGroupId", "managementGroupIdValue"), + } +} + +// String returns a human-readable description of this Management Group ID +func (id ManagementGroupId) String() string { + components := []string{ + fmt.Sprintf("Management Group: %q", id.ManagementGroupId), + } + return fmt.Sprintf("Management Group (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_providerremediation.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_providerremediation.go new file mode 100644 index 000000000000..ec6e2caaabed --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_providerremediation.go @@ -0,0 +1,124 @@ +package policyinsights + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ProviderRemediationId{} + +// ProviderRemediationId is a struct representing the Resource ID for a Provider Remediation +type ProviderRemediationId struct { + SubscriptionId string + ResourceGroupName string + RemediationName string +} + +// NewProviderRemediationID returns a new ProviderRemediationId struct +func NewProviderRemediationID(subscriptionId string, resourceGroupName string, remediationName string) ProviderRemediationId { + return ProviderRemediationId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + RemediationName: remediationName, + } +} + +// ParseProviderRemediationID parses 'input' into a ProviderRemediationId +func ParseProviderRemediationID(input string) (*ProviderRemediationId, error) { + parser := resourceids.NewParserFromResourceIdType(ProviderRemediationId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ProviderRemediationId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.RemediationName, ok = parsed.Parsed["remediationName"]; !ok { + return nil, fmt.Errorf("the segment 'remediationName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseProviderRemediationIDInsensitively parses 'input' case-insensitively into a ProviderRemediationId +// note: this method should only be used for API response data and not user input +func ParseProviderRemediationIDInsensitively(input string) (*ProviderRemediationId, error) { + parser := resourceids.NewParserFromResourceIdType(ProviderRemediationId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ProviderRemediationId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.RemediationName, ok = parsed.Parsed["remediationName"]; !ok { + return nil, fmt.Errorf("the segment 'remediationName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateProviderRemediationID checks that 'input' can be parsed as a Provider Remediation ID +func ValidateProviderRemediationID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseProviderRemediationID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Provider Remediation ID +func (id ProviderRemediationId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.PolicyInsights/remediations/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.RemediationName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Provider Remediation ID +func (id ProviderRemediationId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftPolicyInsights", "Microsoft.PolicyInsights", "Microsoft.PolicyInsights"), + resourceids.StaticSegment("staticRemediations", "remediations", "remediations"), + resourceids.UserSpecifiedSegment("remediationName", "remediationValue"), + } +} + +// String returns a human-readable description of this Provider Remediation ID +func (id ProviderRemediationId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Remediation Name: %q", id.RemediationName), + } + return fmt.Sprintf("Provider Remediation (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_providers2remediation.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_providers2remediation.go new file mode 100644 index 000000000000..3094a75bcae7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_providers2remediation.go @@ -0,0 +1,113 @@ +package policyinsights + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = Providers2RemediationId{} + +// Providers2RemediationId is a struct representing the Resource ID for a Providers 2 Remediation +type Providers2RemediationId struct { + ManagementGroupId string + RemediationName string +} + +// NewProviders2RemediationID returns a new Providers2RemediationId struct +func NewProviders2RemediationID(managementGroupId string, remediationName string) Providers2RemediationId { + return Providers2RemediationId{ + ManagementGroupId: managementGroupId, + RemediationName: remediationName, + } +} + +// ParseProviders2RemediationID parses 'input' into a Providers2RemediationId +func ParseProviders2RemediationID(input string) (*Providers2RemediationId, error) { + parser := resourceids.NewParserFromResourceIdType(Providers2RemediationId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := Providers2RemediationId{} + + if id.ManagementGroupId, ok = parsed.Parsed["managementGroupId"]; !ok { + return nil, fmt.Errorf("the segment 'managementGroupId' was not found in the resource id %q", input) + } + + if id.RemediationName, ok = parsed.Parsed["remediationName"]; !ok { + return nil, fmt.Errorf("the segment 'remediationName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseProviders2RemediationIDInsensitively parses 'input' case-insensitively into a Providers2RemediationId +// note: this method should only be used for API response data and not user input +func ParseProviders2RemediationIDInsensitively(input string) (*Providers2RemediationId, error) { + parser := resourceids.NewParserFromResourceIdType(Providers2RemediationId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := Providers2RemediationId{} + + if id.ManagementGroupId, ok = parsed.Parsed["managementGroupId"]; !ok { + return nil, fmt.Errorf("the segment 'managementGroupId' was not found in the resource id %q", input) + } + + if id.RemediationName, ok = parsed.Parsed["remediationName"]; !ok { + return nil, fmt.Errorf("the segment 'remediationName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateProviders2RemediationID checks that 'input' can be parsed as a Providers 2 Remediation ID +func ValidateProviders2RemediationID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseProviders2RemediationID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Providers 2 Remediation ID +func (id Providers2RemediationId) ID() string { + fmtString := "/providers/Microsoft.Management/managementGroups/%s/providers/Microsoft.PolicyInsights/remediations/%s" + return fmt.Sprintf(fmtString, id.ManagementGroupId, id.RemediationName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Providers 2 Remediation ID +func (id Providers2RemediationId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.StaticSegment("managementGroupsNamespace", "Microsoft.Management", "Microsoft.Management"), + resourceids.StaticSegment("staticManagementGroups", "managementGroups", "managementGroups"), + resourceids.UserSpecifiedSegment("managementGroupId", "managementGroupIdValue"), + resourceids.StaticSegment("staticProviders2", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftPolicyInsights", "Microsoft.PolicyInsights", "Microsoft.PolicyInsights"), + resourceids.StaticSegment("staticRemediations", "remediations", "remediations"), + resourceids.UserSpecifiedSegment("remediationName", "remediationValue"), + } +} + +// String returns a human-readable description of this Providers 2 Remediation ID +func (id Providers2RemediationId) String() string { + components := []string{ + fmt.Sprintf("Management Group: %q", id.ManagementGroupId), + fmt.Sprintf("Remediation Name: %q", id.RemediationName), + } + return fmt.Sprintf("Providers 2 Remediation (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_remediation.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_remediation.go new file mode 100644 index 000000000000..e38039981e3d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_remediation.go @@ -0,0 +1,111 @@ +package policyinsights + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = RemediationId{} + +// RemediationId is a struct representing the Resource ID for a Remediation +type RemediationId struct { + SubscriptionId string + RemediationName string +} + +// NewRemediationID returns a new RemediationId struct +func NewRemediationID(subscriptionId string, remediationName string) RemediationId { + return RemediationId{ + SubscriptionId: subscriptionId, + RemediationName: remediationName, + } +} + +// ParseRemediationID parses 'input' into a RemediationId +func ParseRemediationID(input string) (*RemediationId, error) { + parser := resourceids.NewParserFromResourceIdType(RemediationId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := RemediationId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.RemediationName, ok = parsed.Parsed["remediationName"]; !ok { + return nil, fmt.Errorf("the segment 'remediationName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseRemediationIDInsensitively parses 'input' case-insensitively into a RemediationId +// note: this method should only be used for API response data and not user input +func ParseRemediationIDInsensitively(input string) (*RemediationId, error) { + parser := resourceids.NewParserFromResourceIdType(RemediationId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := RemediationId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.RemediationName, ok = parsed.Parsed["remediationName"]; !ok { + return nil, fmt.Errorf("the segment 'remediationName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateRemediationID checks that 'input' can be parsed as a Remediation ID +func ValidateRemediationID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseRemediationID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Remediation ID +func (id RemediationId) ID() string { + fmtString := "/subscriptions/%s/providers/Microsoft.PolicyInsights/remediations/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.RemediationName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Remediation ID +func (id RemediationId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftPolicyInsights", "Microsoft.PolicyInsights", "Microsoft.PolicyInsights"), + resourceids.StaticSegment("staticRemediations", "remediations", "remediations"), + resourceids.UserSpecifiedSegment("remediationName", "remediationValue"), + } +} + +// String returns a human-readable description of this Remediation ID +func (id RemediationId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Remediation Name: %q", id.RemediationName), + } + return fmt.Sprintf("Remediation (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_scopedremediation.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_scopedremediation.go new file mode 100644 index 000000000000..d8c6f2f5f76b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/id_scopedremediation.go @@ -0,0 +1,110 @@ +package policyinsights + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ScopedRemediationId{} + +// ScopedRemediationId is a struct representing the Resource ID for a Scoped Remediation +type ScopedRemediationId struct { + ResourceId string + RemediationName string +} + +// NewScopedRemediationID returns a new ScopedRemediationId struct +func NewScopedRemediationID(resourceId string, remediationName string) ScopedRemediationId { + return ScopedRemediationId{ + ResourceId: resourceId, + RemediationName: remediationName, + } +} + +// ParseScopedRemediationID parses 'input' into a ScopedRemediationId +func ParseScopedRemediationID(input string) (*ScopedRemediationId, error) { + parser := resourceids.NewParserFromResourceIdType(ScopedRemediationId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ScopedRemediationId{} + + if id.ResourceId, ok = parsed.Parsed["resourceId"]; !ok { + return nil, fmt.Errorf("the segment 'resourceId' was not found in the resource id %q", input) + } + + if id.RemediationName, ok = parsed.Parsed["remediationName"]; !ok { + return nil, fmt.Errorf("the segment 'remediationName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseScopedRemediationIDInsensitively parses 'input' case-insensitively into a ScopedRemediationId +// note: this method should only be used for API response data and not user input +func ParseScopedRemediationIDInsensitively(input string) (*ScopedRemediationId, error) { + parser := resourceids.NewParserFromResourceIdType(ScopedRemediationId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ScopedRemediationId{} + + if id.ResourceId, ok = parsed.Parsed["resourceId"]; !ok { + return nil, fmt.Errorf("the segment 'resourceId' was not found in the resource id %q", input) + } + + if id.RemediationName, ok = parsed.Parsed["remediationName"]; !ok { + return nil, fmt.Errorf("the segment 'remediationName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateScopedRemediationID checks that 'input' can be parsed as a Scoped Remediation ID +func ValidateScopedRemediationID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseScopedRemediationID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Scoped Remediation ID +func (id ScopedRemediationId) ID() string { + fmtString := "/%s/providers/Microsoft.PolicyInsights/remediations/%s" + return fmt.Sprintf(fmtString, strings.TrimPrefix(id.ResourceId, "/"), id.RemediationName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Scoped Remediation ID +func (id ScopedRemediationId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.ScopeSegment("resourceId", "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/some-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftPolicyInsights", "Microsoft.PolicyInsights", "Microsoft.PolicyInsights"), + resourceids.StaticSegment("staticRemediations", "remediations", "remediations"), + resourceids.UserSpecifiedSegment("remediationName", "remediationValue"), + } +} + +// String returns a human-readable description of this Scoped Remediation ID +func (id ScopedRemediationId) String() string { + components := []string{ + fmt.Sprintf("Resource: %q", id.ResourceId), + fmt.Sprintf("Remediation Name: %q", id.RemediationName), + } + return fmt.Sprintf("Scoped Remediation (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatmanagementgroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatmanagementgroup_autorest.go new file mode 100644 index 000000000000..7051725ee698 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatmanagementgroup_autorest.go @@ -0,0 +1,68 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsCancelAtManagementGroupOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsCancelAtManagementGroup ... +func (c PolicyInsightsClient) RemediationsCancelAtManagementGroup(ctx context.Context, id Providers2RemediationId) (result RemediationsCancelAtManagementGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsCancelAtManagementGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtManagementGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtManagementGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsCancelAtManagementGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtManagementGroup", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsCancelAtManagementGroup prepares the RemediationsCancelAtManagementGroup request. +func (c PolicyInsightsClient) preparerForRemediationsCancelAtManagementGroup(ctx context.Context, id Providers2RemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/cancel", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsCancelAtManagementGroup handles the response to the RemediationsCancelAtManagementGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsCancelAtManagementGroup(resp *http.Response) (result RemediationsCancelAtManagementGroupOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatresource_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatresource_autorest.go new file mode 100644 index 000000000000..a845ea029996 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatresource_autorest.go @@ -0,0 +1,68 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsCancelAtResourceOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsCancelAtResource ... +func (c PolicyInsightsClient) RemediationsCancelAtResource(ctx context.Context, id ScopedRemediationId) (result RemediationsCancelAtResourceOperationResponse, err error) { + req, err := c.preparerForRemediationsCancelAtResource(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtResource", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtResource", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsCancelAtResource(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtResource", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsCancelAtResource prepares the RemediationsCancelAtResource request. +func (c PolicyInsightsClient) preparerForRemediationsCancelAtResource(ctx context.Context, id ScopedRemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/cancel", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsCancelAtResource handles the response to the RemediationsCancelAtResource request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsCancelAtResource(resp *http.Response) (result RemediationsCancelAtResourceOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatresourcegroup_autorest.go new file mode 100644 index 000000000000..4e9b5424ca33 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatresourcegroup_autorest.go @@ -0,0 +1,68 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsCancelAtResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsCancelAtResourceGroup ... +func (c PolicyInsightsClient) RemediationsCancelAtResourceGroup(ctx context.Context, id ProviderRemediationId) (result RemediationsCancelAtResourceGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsCancelAtResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsCancelAtResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsCancelAtResourceGroup prepares the RemediationsCancelAtResourceGroup request. +func (c PolicyInsightsClient) preparerForRemediationsCancelAtResourceGroup(ctx context.Context, id ProviderRemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/cancel", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsCancelAtResourceGroup handles the response to the RemediationsCancelAtResourceGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsCancelAtResourceGroup(resp *http.Response) (result RemediationsCancelAtResourceGroupOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatsubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatsubscription_autorest.go new file mode 100644 index 000000000000..0b3721d0c137 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscancelatsubscription_autorest.go @@ -0,0 +1,68 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsCancelAtSubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsCancelAtSubscription ... +func (c PolicyInsightsClient) RemediationsCancelAtSubscription(ctx context.Context, id RemediationId) (result RemediationsCancelAtSubscriptionOperationResponse, err error) { + req, err := c.preparerForRemediationsCancelAtSubscription(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtSubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtSubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsCancelAtSubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCancelAtSubscription", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsCancelAtSubscription prepares the RemediationsCancelAtSubscription request. +func (c PolicyInsightsClient) preparerForRemediationsCancelAtSubscription(ctx context.Context, id RemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/cancel", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsCancelAtSubscription handles the response to the RemediationsCancelAtSubscription request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsCancelAtSubscription(resp *http.Response) (result RemediationsCancelAtSubscriptionOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatmanagementgroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatmanagementgroup_autorest.go new file mode 100644 index 000000000000..40a3e85fe1fd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatmanagementgroup_autorest.go @@ -0,0 +1,68 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsCreateOrUpdateAtManagementGroupOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsCreateOrUpdateAtManagementGroup ... +func (c PolicyInsightsClient) RemediationsCreateOrUpdateAtManagementGroup(ctx context.Context, id Providers2RemediationId, input Remediation) (result RemediationsCreateOrUpdateAtManagementGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsCreateOrUpdateAtManagementGroup(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtManagementGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtManagementGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsCreateOrUpdateAtManagementGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtManagementGroup", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsCreateOrUpdateAtManagementGroup prepares the RemediationsCreateOrUpdateAtManagementGroup request. +func (c PolicyInsightsClient) preparerForRemediationsCreateOrUpdateAtManagementGroup(ctx context.Context, id Providers2RemediationId, input Remediation) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsCreateOrUpdateAtManagementGroup handles the response to the RemediationsCreateOrUpdateAtManagementGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsCreateOrUpdateAtManagementGroup(resp *http.Response) (result RemediationsCreateOrUpdateAtManagementGroupOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatresource_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatresource_autorest.go new file mode 100644 index 000000000000..bb52593c23bb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatresource_autorest.go @@ -0,0 +1,68 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsCreateOrUpdateAtResourceOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsCreateOrUpdateAtResource ... +func (c PolicyInsightsClient) RemediationsCreateOrUpdateAtResource(ctx context.Context, id ScopedRemediationId, input Remediation) (result RemediationsCreateOrUpdateAtResourceOperationResponse, err error) { + req, err := c.preparerForRemediationsCreateOrUpdateAtResource(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtResource", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtResource", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsCreateOrUpdateAtResource(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtResource", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsCreateOrUpdateAtResource prepares the RemediationsCreateOrUpdateAtResource request. +func (c PolicyInsightsClient) preparerForRemediationsCreateOrUpdateAtResource(ctx context.Context, id ScopedRemediationId, input Remediation) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsCreateOrUpdateAtResource handles the response to the RemediationsCreateOrUpdateAtResource request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsCreateOrUpdateAtResource(resp *http.Response) (result RemediationsCreateOrUpdateAtResourceOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatresourcegroup_autorest.go new file mode 100644 index 000000000000..6313f673d65c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatresourcegroup_autorest.go @@ -0,0 +1,68 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsCreateOrUpdateAtResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsCreateOrUpdateAtResourceGroup ... +func (c PolicyInsightsClient) RemediationsCreateOrUpdateAtResourceGroup(ctx context.Context, id ProviderRemediationId, input Remediation) (result RemediationsCreateOrUpdateAtResourceGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsCreateOrUpdateAtResourceGroup(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsCreateOrUpdateAtResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsCreateOrUpdateAtResourceGroup prepares the RemediationsCreateOrUpdateAtResourceGroup request. +func (c PolicyInsightsClient) preparerForRemediationsCreateOrUpdateAtResourceGroup(ctx context.Context, id ProviderRemediationId, input Remediation) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsCreateOrUpdateAtResourceGroup handles the response to the RemediationsCreateOrUpdateAtResourceGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsCreateOrUpdateAtResourceGroup(resp *http.Response) (result RemediationsCreateOrUpdateAtResourceGroupOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatsubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatsubscription_autorest.go new file mode 100644 index 000000000000..a63491aa0f77 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationscreateorupdateatsubscription_autorest.go @@ -0,0 +1,68 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsCreateOrUpdateAtSubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsCreateOrUpdateAtSubscription ... +func (c PolicyInsightsClient) RemediationsCreateOrUpdateAtSubscription(ctx context.Context, id RemediationId, input Remediation) (result RemediationsCreateOrUpdateAtSubscriptionOperationResponse, err error) { + req, err := c.preparerForRemediationsCreateOrUpdateAtSubscription(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtSubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtSubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsCreateOrUpdateAtSubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsCreateOrUpdateAtSubscription", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsCreateOrUpdateAtSubscription prepares the RemediationsCreateOrUpdateAtSubscription request. +func (c PolicyInsightsClient) preparerForRemediationsCreateOrUpdateAtSubscription(ctx context.Context, id RemediationId, input Remediation) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsCreateOrUpdateAtSubscription handles the response to the RemediationsCreateOrUpdateAtSubscription request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsCreateOrUpdateAtSubscription(resp *http.Response) (result RemediationsCreateOrUpdateAtSubscriptionOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatmanagementgroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatmanagementgroup_autorest.go new file mode 100644 index 000000000000..53831444161c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatmanagementgroup_autorest.go @@ -0,0 +1,67 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsDeleteAtManagementGroupOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsDeleteAtManagementGroup ... +func (c PolicyInsightsClient) RemediationsDeleteAtManagementGroup(ctx context.Context, id Providers2RemediationId) (result RemediationsDeleteAtManagementGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsDeleteAtManagementGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtManagementGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtManagementGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsDeleteAtManagementGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtManagementGroup", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsDeleteAtManagementGroup prepares the RemediationsDeleteAtManagementGroup request. +func (c PolicyInsightsClient) preparerForRemediationsDeleteAtManagementGroup(ctx context.Context, id Providers2RemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsDeleteAtManagementGroup handles the response to the RemediationsDeleteAtManagementGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsDeleteAtManagementGroup(resp *http.Response) (result RemediationsDeleteAtManagementGroupOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatresource_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatresource_autorest.go new file mode 100644 index 000000000000..e02d70d3da60 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatresource_autorest.go @@ -0,0 +1,67 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsDeleteAtResourceOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsDeleteAtResource ... +func (c PolicyInsightsClient) RemediationsDeleteAtResource(ctx context.Context, id ScopedRemediationId) (result RemediationsDeleteAtResourceOperationResponse, err error) { + req, err := c.preparerForRemediationsDeleteAtResource(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtResource", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtResource", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsDeleteAtResource(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtResource", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsDeleteAtResource prepares the RemediationsDeleteAtResource request. +func (c PolicyInsightsClient) preparerForRemediationsDeleteAtResource(ctx context.Context, id ScopedRemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsDeleteAtResource handles the response to the RemediationsDeleteAtResource request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsDeleteAtResource(resp *http.Response) (result RemediationsDeleteAtResourceOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatresourcegroup_autorest.go new file mode 100644 index 000000000000..beed336d856d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatresourcegroup_autorest.go @@ -0,0 +1,67 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsDeleteAtResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsDeleteAtResourceGroup ... +func (c PolicyInsightsClient) RemediationsDeleteAtResourceGroup(ctx context.Context, id ProviderRemediationId) (result RemediationsDeleteAtResourceGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsDeleteAtResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsDeleteAtResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsDeleteAtResourceGroup prepares the RemediationsDeleteAtResourceGroup request. +func (c PolicyInsightsClient) preparerForRemediationsDeleteAtResourceGroup(ctx context.Context, id ProviderRemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsDeleteAtResourceGroup handles the response to the RemediationsDeleteAtResourceGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsDeleteAtResourceGroup(resp *http.Response) (result RemediationsDeleteAtResourceGroupOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatsubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatsubscription_autorest.go new file mode 100644 index 000000000000..2ba9b6b402a2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsdeleteatsubscription_autorest.go @@ -0,0 +1,67 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsDeleteAtSubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsDeleteAtSubscription ... +func (c PolicyInsightsClient) RemediationsDeleteAtSubscription(ctx context.Context, id RemediationId) (result RemediationsDeleteAtSubscriptionOperationResponse, err error) { + req, err := c.preparerForRemediationsDeleteAtSubscription(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtSubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtSubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsDeleteAtSubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsDeleteAtSubscription", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsDeleteAtSubscription prepares the RemediationsDeleteAtSubscription request. +func (c PolicyInsightsClient) preparerForRemediationsDeleteAtSubscription(ctx context.Context, id RemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsDeleteAtSubscription handles the response to the RemediationsDeleteAtSubscription request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsDeleteAtSubscription(resp *http.Response) (result RemediationsDeleteAtSubscriptionOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatmanagementgroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatmanagementgroup_autorest.go new file mode 100644 index 000000000000..4e3817967bee --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatmanagementgroup_autorest.go @@ -0,0 +1,67 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsGetAtManagementGroupOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsGetAtManagementGroup ... +func (c PolicyInsightsClient) RemediationsGetAtManagementGroup(ctx context.Context, id Providers2RemediationId) (result RemediationsGetAtManagementGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsGetAtManagementGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtManagementGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtManagementGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsGetAtManagementGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtManagementGroup", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsGetAtManagementGroup prepares the RemediationsGetAtManagementGroup request. +func (c PolicyInsightsClient) preparerForRemediationsGetAtManagementGroup(ctx context.Context, id Providers2RemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsGetAtManagementGroup handles the response to the RemediationsGetAtManagementGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsGetAtManagementGroup(resp *http.Response) (result RemediationsGetAtManagementGroupOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatresource_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatresource_autorest.go new file mode 100644 index 000000000000..f196bdb4af6c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatresource_autorest.go @@ -0,0 +1,67 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsGetAtResourceOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsGetAtResource ... +func (c PolicyInsightsClient) RemediationsGetAtResource(ctx context.Context, id ScopedRemediationId) (result RemediationsGetAtResourceOperationResponse, err error) { + req, err := c.preparerForRemediationsGetAtResource(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtResource", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtResource", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsGetAtResource(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtResource", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsGetAtResource prepares the RemediationsGetAtResource request. +func (c PolicyInsightsClient) preparerForRemediationsGetAtResource(ctx context.Context, id ScopedRemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsGetAtResource handles the response to the RemediationsGetAtResource request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsGetAtResource(resp *http.Response) (result RemediationsGetAtResourceOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatresourcegroup_autorest.go new file mode 100644 index 000000000000..6d6b13860e14 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatresourcegroup_autorest.go @@ -0,0 +1,67 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsGetAtResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsGetAtResourceGroup ... +func (c PolicyInsightsClient) RemediationsGetAtResourceGroup(ctx context.Context, id ProviderRemediationId) (result RemediationsGetAtResourceGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsGetAtResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsGetAtResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsGetAtResourceGroup prepares the RemediationsGetAtResourceGroup request. +func (c PolicyInsightsClient) preparerForRemediationsGetAtResourceGroup(ctx context.Context, id ProviderRemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsGetAtResourceGroup handles the response to the RemediationsGetAtResourceGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsGetAtResourceGroup(resp *http.Response) (result RemediationsGetAtResourceGroupOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatsubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatsubscription_autorest.go new file mode 100644 index 000000000000..86089f4d913c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationsgetatsubscription_autorest.go @@ -0,0 +1,67 @@ +package policyinsights + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsGetAtSubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *Remediation +} + +// RemediationsGetAtSubscription ... +func (c PolicyInsightsClient) RemediationsGetAtSubscription(ctx context.Context, id RemediationId) (result RemediationsGetAtSubscriptionOperationResponse, err error) { + req, err := c.preparerForRemediationsGetAtSubscription(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtSubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtSubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsGetAtSubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsGetAtSubscription", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRemediationsGetAtSubscription prepares the RemediationsGetAtSubscription request. +func (c PolicyInsightsClient) preparerForRemediationsGetAtSubscription(ctx context.Context, id RemediationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsGetAtSubscription handles the response to the RemediationsGetAtSubscription request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsGetAtSubscription(resp *http.Response) (result RemediationsGetAtSubscriptionOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatmanagementgroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatmanagementgroup_autorest.go new file mode 100644 index 000000000000..3f8498215095 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatmanagementgroup_autorest.go @@ -0,0 +1,215 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsListDeploymentsAtManagementGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]RemediationDeployment + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (RemediationsListDeploymentsAtManagementGroupOperationResponse, error) +} + +type RemediationsListDeploymentsAtManagementGroupCompleteResult struct { + Items []RemediationDeployment +} + +func (r RemediationsListDeploymentsAtManagementGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r RemediationsListDeploymentsAtManagementGroupOperationResponse) LoadMore(ctx context.Context) (resp RemediationsListDeploymentsAtManagementGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type RemediationsListDeploymentsAtManagementGroupOperationOptions struct { + Top *int64 +} + +func DefaultRemediationsListDeploymentsAtManagementGroupOperationOptions() RemediationsListDeploymentsAtManagementGroupOperationOptions { + return RemediationsListDeploymentsAtManagementGroupOperationOptions{} +} + +func (o RemediationsListDeploymentsAtManagementGroupOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o RemediationsListDeploymentsAtManagementGroupOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// RemediationsListDeploymentsAtManagementGroup ... +func (c PolicyInsightsClient) RemediationsListDeploymentsAtManagementGroup(ctx context.Context, id Providers2RemediationId, options RemediationsListDeploymentsAtManagementGroupOperationOptions) (resp RemediationsListDeploymentsAtManagementGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsListDeploymentsAtManagementGroup(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtManagementGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtManagementGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForRemediationsListDeploymentsAtManagementGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtManagementGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// RemediationsListDeploymentsAtManagementGroupComplete retrieves all of the results into a single object +func (c PolicyInsightsClient) RemediationsListDeploymentsAtManagementGroupComplete(ctx context.Context, id Providers2RemediationId, options RemediationsListDeploymentsAtManagementGroupOperationOptions) (RemediationsListDeploymentsAtManagementGroupCompleteResult, error) { + return c.RemediationsListDeploymentsAtManagementGroupCompleteMatchingPredicate(ctx, id, options, RemediationDeploymentOperationPredicate{}) +} + +// RemediationsListDeploymentsAtManagementGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c PolicyInsightsClient) RemediationsListDeploymentsAtManagementGroupCompleteMatchingPredicate(ctx context.Context, id Providers2RemediationId, options RemediationsListDeploymentsAtManagementGroupOperationOptions, predicate RemediationDeploymentOperationPredicate) (resp RemediationsListDeploymentsAtManagementGroupCompleteResult, err error) { + items := make([]RemediationDeployment, 0) + + page, err := c.RemediationsListDeploymentsAtManagementGroup(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := RemediationsListDeploymentsAtManagementGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForRemediationsListDeploymentsAtManagementGroup prepares the RemediationsListDeploymentsAtManagementGroup request. +func (c PolicyInsightsClient) preparerForRemediationsListDeploymentsAtManagementGroup(ctx context.Context, id Providers2RemediationId, options RemediationsListDeploymentsAtManagementGroupOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/listDeployments", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForRemediationsListDeploymentsAtManagementGroupWithNextLink prepares the RemediationsListDeploymentsAtManagementGroup request with the given nextLink token. +func (c PolicyInsightsClient) preparerForRemediationsListDeploymentsAtManagementGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsListDeploymentsAtManagementGroup handles the response to the RemediationsListDeploymentsAtManagementGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsListDeploymentsAtManagementGroup(resp *http.Response) (result RemediationsListDeploymentsAtManagementGroupOperationResponse, err error) { + type page struct { + Values []RemediationDeployment `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result RemediationsListDeploymentsAtManagementGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsListDeploymentsAtManagementGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtManagementGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtManagementGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsListDeploymentsAtManagementGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtManagementGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatresource_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatresource_autorest.go new file mode 100644 index 000000000000..fd82c4339713 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatresource_autorest.go @@ -0,0 +1,215 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsListDeploymentsAtResourceOperationResponse struct { + HttpResponse *http.Response + Model *[]RemediationDeployment + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (RemediationsListDeploymentsAtResourceOperationResponse, error) +} + +type RemediationsListDeploymentsAtResourceCompleteResult struct { + Items []RemediationDeployment +} + +func (r RemediationsListDeploymentsAtResourceOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r RemediationsListDeploymentsAtResourceOperationResponse) LoadMore(ctx context.Context) (resp RemediationsListDeploymentsAtResourceOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type RemediationsListDeploymentsAtResourceOperationOptions struct { + Top *int64 +} + +func DefaultRemediationsListDeploymentsAtResourceOperationOptions() RemediationsListDeploymentsAtResourceOperationOptions { + return RemediationsListDeploymentsAtResourceOperationOptions{} +} + +func (o RemediationsListDeploymentsAtResourceOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o RemediationsListDeploymentsAtResourceOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// RemediationsListDeploymentsAtResource ... +func (c PolicyInsightsClient) RemediationsListDeploymentsAtResource(ctx context.Context, id ScopedRemediationId, options RemediationsListDeploymentsAtResourceOperationOptions) (resp RemediationsListDeploymentsAtResourceOperationResponse, err error) { + req, err := c.preparerForRemediationsListDeploymentsAtResource(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResource", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResource", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForRemediationsListDeploymentsAtResource(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResource", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// RemediationsListDeploymentsAtResourceComplete retrieves all of the results into a single object +func (c PolicyInsightsClient) RemediationsListDeploymentsAtResourceComplete(ctx context.Context, id ScopedRemediationId, options RemediationsListDeploymentsAtResourceOperationOptions) (RemediationsListDeploymentsAtResourceCompleteResult, error) { + return c.RemediationsListDeploymentsAtResourceCompleteMatchingPredicate(ctx, id, options, RemediationDeploymentOperationPredicate{}) +} + +// RemediationsListDeploymentsAtResourceCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c PolicyInsightsClient) RemediationsListDeploymentsAtResourceCompleteMatchingPredicate(ctx context.Context, id ScopedRemediationId, options RemediationsListDeploymentsAtResourceOperationOptions, predicate RemediationDeploymentOperationPredicate) (resp RemediationsListDeploymentsAtResourceCompleteResult, err error) { + items := make([]RemediationDeployment, 0) + + page, err := c.RemediationsListDeploymentsAtResource(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := RemediationsListDeploymentsAtResourceCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForRemediationsListDeploymentsAtResource prepares the RemediationsListDeploymentsAtResource request. +func (c PolicyInsightsClient) preparerForRemediationsListDeploymentsAtResource(ctx context.Context, id ScopedRemediationId, options RemediationsListDeploymentsAtResourceOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/listDeployments", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForRemediationsListDeploymentsAtResourceWithNextLink prepares the RemediationsListDeploymentsAtResource request with the given nextLink token. +func (c PolicyInsightsClient) preparerForRemediationsListDeploymentsAtResourceWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsListDeploymentsAtResource handles the response to the RemediationsListDeploymentsAtResource request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsListDeploymentsAtResource(resp *http.Response) (result RemediationsListDeploymentsAtResourceOperationResponse, err error) { + type page struct { + Values []RemediationDeployment `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result RemediationsListDeploymentsAtResourceOperationResponse, err error) { + req, err := c.preparerForRemediationsListDeploymentsAtResourceWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResource", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResource", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsListDeploymentsAtResource(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResource", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatresourcegroup_autorest.go new file mode 100644 index 000000000000..ac8f20557850 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatresourcegroup_autorest.go @@ -0,0 +1,215 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsListDeploymentsAtResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]RemediationDeployment + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (RemediationsListDeploymentsAtResourceGroupOperationResponse, error) +} + +type RemediationsListDeploymentsAtResourceGroupCompleteResult struct { + Items []RemediationDeployment +} + +func (r RemediationsListDeploymentsAtResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r RemediationsListDeploymentsAtResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp RemediationsListDeploymentsAtResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type RemediationsListDeploymentsAtResourceGroupOperationOptions struct { + Top *int64 +} + +func DefaultRemediationsListDeploymentsAtResourceGroupOperationOptions() RemediationsListDeploymentsAtResourceGroupOperationOptions { + return RemediationsListDeploymentsAtResourceGroupOperationOptions{} +} + +func (o RemediationsListDeploymentsAtResourceGroupOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o RemediationsListDeploymentsAtResourceGroupOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// RemediationsListDeploymentsAtResourceGroup ... +func (c PolicyInsightsClient) RemediationsListDeploymentsAtResourceGroup(ctx context.Context, id ProviderRemediationId, options RemediationsListDeploymentsAtResourceGroupOperationOptions) (resp RemediationsListDeploymentsAtResourceGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsListDeploymentsAtResourceGroup(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForRemediationsListDeploymentsAtResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// RemediationsListDeploymentsAtResourceGroupComplete retrieves all of the results into a single object +func (c PolicyInsightsClient) RemediationsListDeploymentsAtResourceGroupComplete(ctx context.Context, id ProviderRemediationId, options RemediationsListDeploymentsAtResourceGroupOperationOptions) (RemediationsListDeploymentsAtResourceGroupCompleteResult, error) { + return c.RemediationsListDeploymentsAtResourceGroupCompleteMatchingPredicate(ctx, id, options, RemediationDeploymentOperationPredicate{}) +} + +// RemediationsListDeploymentsAtResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c PolicyInsightsClient) RemediationsListDeploymentsAtResourceGroupCompleteMatchingPredicate(ctx context.Context, id ProviderRemediationId, options RemediationsListDeploymentsAtResourceGroupOperationOptions, predicate RemediationDeploymentOperationPredicate) (resp RemediationsListDeploymentsAtResourceGroupCompleteResult, err error) { + items := make([]RemediationDeployment, 0) + + page, err := c.RemediationsListDeploymentsAtResourceGroup(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := RemediationsListDeploymentsAtResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForRemediationsListDeploymentsAtResourceGroup prepares the RemediationsListDeploymentsAtResourceGroup request. +func (c PolicyInsightsClient) preparerForRemediationsListDeploymentsAtResourceGroup(ctx context.Context, id ProviderRemediationId, options RemediationsListDeploymentsAtResourceGroupOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/listDeployments", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForRemediationsListDeploymentsAtResourceGroupWithNextLink prepares the RemediationsListDeploymentsAtResourceGroup request with the given nextLink token. +func (c PolicyInsightsClient) preparerForRemediationsListDeploymentsAtResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsListDeploymentsAtResourceGroup handles the response to the RemediationsListDeploymentsAtResourceGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsListDeploymentsAtResourceGroup(resp *http.Response) (result RemediationsListDeploymentsAtResourceGroupOperationResponse, err error) { + type page struct { + Values []RemediationDeployment `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result RemediationsListDeploymentsAtResourceGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsListDeploymentsAtResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsListDeploymentsAtResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatsubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatsubscription_autorest.go new file mode 100644 index 000000000000..8d6af304154d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistdeploymentsatsubscription_autorest.go @@ -0,0 +1,215 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsListDeploymentsAtSubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *[]RemediationDeployment + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (RemediationsListDeploymentsAtSubscriptionOperationResponse, error) +} + +type RemediationsListDeploymentsAtSubscriptionCompleteResult struct { + Items []RemediationDeployment +} + +func (r RemediationsListDeploymentsAtSubscriptionOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r RemediationsListDeploymentsAtSubscriptionOperationResponse) LoadMore(ctx context.Context) (resp RemediationsListDeploymentsAtSubscriptionOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type RemediationsListDeploymentsAtSubscriptionOperationOptions struct { + Top *int64 +} + +func DefaultRemediationsListDeploymentsAtSubscriptionOperationOptions() RemediationsListDeploymentsAtSubscriptionOperationOptions { + return RemediationsListDeploymentsAtSubscriptionOperationOptions{} +} + +func (o RemediationsListDeploymentsAtSubscriptionOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o RemediationsListDeploymentsAtSubscriptionOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// RemediationsListDeploymentsAtSubscription ... +func (c PolicyInsightsClient) RemediationsListDeploymentsAtSubscription(ctx context.Context, id RemediationId, options RemediationsListDeploymentsAtSubscriptionOperationOptions) (resp RemediationsListDeploymentsAtSubscriptionOperationResponse, err error) { + req, err := c.preparerForRemediationsListDeploymentsAtSubscription(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtSubscription", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtSubscription", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForRemediationsListDeploymentsAtSubscription(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtSubscription", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// RemediationsListDeploymentsAtSubscriptionComplete retrieves all of the results into a single object +func (c PolicyInsightsClient) RemediationsListDeploymentsAtSubscriptionComplete(ctx context.Context, id RemediationId, options RemediationsListDeploymentsAtSubscriptionOperationOptions) (RemediationsListDeploymentsAtSubscriptionCompleteResult, error) { + return c.RemediationsListDeploymentsAtSubscriptionCompleteMatchingPredicate(ctx, id, options, RemediationDeploymentOperationPredicate{}) +} + +// RemediationsListDeploymentsAtSubscriptionCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c PolicyInsightsClient) RemediationsListDeploymentsAtSubscriptionCompleteMatchingPredicate(ctx context.Context, id RemediationId, options RemediationsListDeploymentsAtSubscriptionOperationOptions, predicate RemediationDeploymentOperationPredicate) (resp RemediationsListDeploymentsAtSubscriptionCompleteResult, err error) { + items := make([]RemediationDeployment, 0) + + page, err := c.RemediationsListDeploymentsAtSubscription(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := RemediationsListDeploymentsAtSubscriptionCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForRemediationsListDeploymentsAtSubscription prepares the RemediationsListDeploymentsAtSubscription request. +func (c PolicyInsightsClient) preparerForRemediationsListDeploymentsAtSubscription(ctx context.Context, id RemediationId, options RemediationsListDeploymentsAtSubscriptionOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/listDeployments", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForRemediationsListDeploymentsAtSubscriptionWithNextLink prepares the RemediationsListDeploymentsAtSubscription request with the given nextLink token. +func (c PolicyInsightsClient) preparerForRemediationsListDeploymentsAtSubscriptionWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsListDeploymentsAtSubscription handles the response to the RemediationsListDeploymentsAtSubscription request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsListDeploymentsAtSubscription(resp *http.Response) (result RemediationsListDeploymentsAtSubscriptionOperationResponse, err error) { + type page struct { + Values []RemediationDeployment `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result RemediationsListDeploymentsAtSubscriptionOperationResponse, err error) { + req, err := c.preparerForRemediationsListDeploymentsAtSubscriptionWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtSubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtSubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsListDeploymentsAtSubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListDeploymentsAtSubscription", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistformanagementgroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistformanagementgroup_autorest.go new file mode 100644 index 000000000000..c01bae19732d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistformanagementgroup_autorest.go @@ -0,0 +1,220 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsListForManagementGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]Remediation + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (RemediationsListForManagementGroupOperationResponse, error) +} + +type RemediationsListForManagementGroupCompleteResult struct { + Items []Remediation +} + +func (r RemediationsListForManagementGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r RemediationsListForManagementGroupOperationResponse) LoadMore(ctx context.Context) (resp RemediationsListForManagementGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type RemediationsListForManagementGroupOperationOptions struct { + Filter *string + Top *int64 +} + +func DefaultRemediationsListForManagementGroupOperationOptions() RemediationsListForManagementGroupOperationOptions { + return RemediationsListForManagementGroupOperationOptions{} +} + +func (o RemediationsListForManagementGroupOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o RemediationsListForManagementGroupOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Filter != nil { + out["$filter"] = *o.Filter + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// RemediationsListForManagementGroup ... +func (c PolicyInsightsClient) RemediationsListForManagementGroup(ctx context.Context, id ManagementGroupId, options RemediationsListForManagementGroupOperationOptions) (resp RemediationsListForManagementGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsListForManagementGroup(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForManagementGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForManagementGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForRemediationsListForManagementGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForManagementGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// RemediationsListForManagementGroupComplete retrieves all of the results into a single object +func (c PolicyInsightsClient) RemediationsListForManagementGroupComplete(ctx context.Context, id ManagementGroupId, options RemediationsListForManagementGroupOperationOptions) (RemediationsListForManagementGroupCompleteResult, error) { + return c.RemediationsListForManagementGroupCompleteMatchingPredicate(ctx, id, options, RemediationOperationPredicate{}) +} + +// RemediationsListForManagementGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c PolicyInsightsClient) RemediationsListForManagementGroupCompleteMatchingPredicate(ctx context.Context, id ManagementGroupId, options RemediationsListForManagementGroupOperationOptions, predicate RemediationOperationPredicate) (resp RemediationsListForManagementGroupCompleteResult, err error) { + items := make([]Remediation, 0) + + page, err := c.RemediationsListForManagementGroup(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := RemediationsListForManagementGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForRemediationsListForManagementGroup prepares the RemediationsListForManagementGroup request. +func (c PolicyInsightsClient) preparerForRemediationsListForManagementGroup(ctx context.Context, id ManagementGroupId, options RemediationsListForManagementGroupOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.PolicyInsights/remediations", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForRemediationsListForManagementGroupWithNextLink prepares the RemediationsListForManagementGroup request with the given nextLink token. +func (c PolicyInsightsClient) preparerForRemediationsListForManagementGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsListForManagementGroup handles the response to the RemediationsListForManagementGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsListForManagementGroup(resp *http.Response) (result RemediationsListForManagementGroupOperationResponse, err error) { + type page struct { + Values []Remediation `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result RemediationsListForManagementGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsListForManagementGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForManagementGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForManagementGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsListForManagementGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForManagementGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforresource_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforresource_autorest.go new file mode 100644 index 000000000000..216197b93b02 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforresource_autorest.go @@ -0,0 +1,221 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsListForResourceOperationResponse struct { + HttpResponse *http.Response + Model *[]Remediation + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (RemediationsListForResourceOperationResponse, error) +} + +type RemediationsListForResourceCompleteResult struct { + Items []Remediation +} + +func (r RemediationsListForResourceOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r RemediationsListForResourceOperationResponse) LoadMore(ctx context.Context) (resp RemediationsListForResourceOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type RemediationsListForResourceOperationOptions struct { + Filter *string + Top *int64 +} + +func DefaultRemediationsListForResourceOperationOptions() RemediationsListForResourceOperationOptions { + return RemediationsListForResourceOperationOptions{} +} + +func (o RemediationsListForResourceOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o RemediationsListForResourceOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Filter != nil { + out["$filter"] = *o.Filter + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// RemediationsListForResource ... +func (c PolicyInsightsClient) RemediationsListForResource(ctx context.Context, id commonids.ScopeId, options RemediationsListForResourceOperationOptions) (resp RemediationsListForResourceOperationResponse, err error) { + req, err := c.preparerForRemediationsListForResource(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResource", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResource", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForRemediationsListForResource(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResource", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// RemediationsListForResourceComplete retrieves all of the results into a single object +func (c PolicyInsightsClient) RemediationsListForResourceComplete(ctx context.Context, id commonids.ScopeId, options RemediationsListForResourceOperationOptions) (RemediationsListForResourceCompleteResult, error) { + return c.RemediationsListForResourceCompleteMatchingPredicate(ctx, id, options, RemediationOperationPredicate{}) +} + +// RemediationsListForResourceCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c PolicyInsightsClient) RemediationsListForResourceCompleteMatchingPredicate(ctx context.Context, id commonids.ScopeId, options RemediationsListForResourceOperationOptions, predicate RemediationOperationPredicate) (resp RemediationsListForResourceCompleteResult, err error) { + items := make([]Remediation, 0) + + page, err := c.RemediationsListForResource(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := RemediationsListForResourceCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForRemediationsListForResource prepares the RemediationsListForResource request. +func (c PolicyInsightsClient) preparerForRemediationsListForResource(ctx context.Context, id commonids.ScopeId, options RemediationsListForResourceOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.PolicyInsights/remediations", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForRemediationsListForResourceWithNextLink prepares the RemediationsListForResource request with the given nextLink token. +func (c PolicyInsightsClient) preparerForRemediationsListForResourceWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsListForResource handles the response to the RemediationsListForResource request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsListForResource(resp *http.Response) (result RemediationsListForResourceOperationResponse, err error) { + type page struct { + Values []Remediation `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result RemediationsListForResourceOperationResponse, err error) { + req, err := c.preparerForRemediationsListForResourceWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResource", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResource", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsListForResource(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResource", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforresourcegroup_autorest.go new file mode 100644 index 000000000000..dca11d5822b1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforresourcegroup_autorest.go @@ -0,0 +1,221 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsListForResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]Remediation + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (RemediationsListForResourceGroupOperationResponse, error) +} + +type RemediationsListForResourceGroupCompleteResult struct { + Items []Remediation +} + +func (r RemediationsListForResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r RemediationsListForResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp RemediationsListForResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type RemediationsListForResourceGroupOperationOptions struct { + Filter *string + Top *int64 +} + +func DefaultRemediationsListForResourceGroupOperationOptions() RemediationsListForResourceGroupOperationOptions { + return RemediationsListForResourceGroupOperationOptions{} +} + +func (o RemediationsListForResourceGroupOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o RemediationsListForResourceGroupOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Filter != nil { + out["$filter"] = *o.Filter + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// RemediationsListForResourceGroup ... +func (c PolicyInsightsClient) RemediationsListForResourceGroup(ctx context.Context, id commonids.ResourceGroupId, options RemediationsListForResourceGroupOperationOptions) (resp RemediationsListForResourceGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsListForResourceGroup(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForRemediationsListForResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// RemediationsListForResourceGroupComplete retrieves all of the results into a single object +func (c PolicyInsightsClient) RemediationsListForResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId, options RemediationsListForResourceGroupOperationOptions) (RemediationsListForResourceGroupCompleteResult, error) { + return c.RemediationsListForResourceGroupCompleteMatchingPredicate(ctx, id, options, RemediationOperationPredicate{}) +} + +// RemediationsListForResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c PolicyInsightsClient) RemediationsListForResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, options RemediationsListForResourceGroupOperationOptions, predicate RemediationOperationPredicate) (resp RemediationsListForResourceGroupCompleteResult, err error) { + items := make([]Remediation, 0) + + page, err := c.RemediationsListForResourceGroup(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := RemediationsListForResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForRemediationsListForResourceGroup prepares the RemediationsListForResourceGroup request. +func (c PolicyInsightsClient) preparerForRemediationsListForResourceGroup(ctx context.Context, id commonids.ResourceGroupId, options RemediationsListForResourceGroupOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.PolicyInsights/remediations", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForRemediationsListForResourceGroupWithNextLink prepares the RemediationsListForResourceGroup request with the given nextLink token. +func (c PolicyInsightsClient) preparerForRemediationsListForResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsListForResourceGroup handles the response to the RemediationsListForResourceGroup request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsListForResourceGroup(resp *http.Response) (result RemediationsListForResourceGroupOperationResponse, err error) { + type page struct { + Values []Remediation `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result RemediationsListForResourceGroupOperationResponse, err error) { + req, err := c.preparerForRemediationsListForResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsListForResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforsubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforsubscription_autorest.go new file mode 100644 index 000000000000..d40344c62fd7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/method_remediationslistforsubscription_autorest.go @@ -0,0 +1,221 @@ +package policyinsights + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationsListForSubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *[]Remediation + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (RemediationsListForSubscriptionOperationResponse, error) +} + +type RemediationsListForSubscriptionCompleteResult struct { + Items []Remediation +} + +func (r RemediationsListForSubscriptionOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r RemediationsListForSubscriptionOperationResponse) LoadMore(ctx context.Context) (resp RemediationsListForSubscriptionOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type RemediationsListForSubscriptionOperationOptions struct { + Filter *string + Top *int64 +} + +func DefaultRemediationsListForSubscriptionOperationOptions() RemediationsListForSubscriptionOperationOptions { + return RemediationsListForSubscriptionOperationOptions{} +} + +func (o RemediationsListForSubscriptionOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o RemediationsListForSubscriptionOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Filter != nil { + out["$filter"] = *o.Filter + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// RemediationsListForSubscription ... +func (c PolicyInsightsClient) RemediationsListForSubscription(ctx context.Context, id commonids.SubscriptionId, options RemediationsListForSubscriptionOperationOptions) (resp RemediationsListForSubscriptionOperationResponse, err error) { + req, err := c.preparerForRemediationsListForSubscription(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForSubscription", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForSubscription", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForRemediationsListForSubscription(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForSubscription", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// RemediationsListForSubscriptionComplete retrieves all of the results into a single object +func (c PolicyInsightsClient) RemediationsListForSubscriptionComplete(ctx context.Context, id commonids.SubscriptionId, options RemediationsListForSubscriptionOperationOptions) (RemediationsListForSubscriptionCompleteResult, error) { + return c.RemediationsListForSubscriptionCompleteMatchingPredicate(ctx, id, options, RemediationOperationPredicate{}) +} + +// RemediationsListForSubscriptionCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c PolicyInsightsClient) RemediationsListForSubscriptionCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, options RemediationsListForSubscriptionOperationOptions, predicate RemediationOperationPredicate) (resp RemediationsListForSubscriptionCompleteResult, err error) { + items := make([]Remediation, 0) + + page, err := c.RemediationsListForSubscription(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := RemediationsListForSubscriptionCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForRemediationsListForSubscription prepares the RemediationsListForSubscription request. +func (c PolicyInsightsClient) preparerForRemediationsListForSubscription(ctx context.Context, id commonids.SubscriptionId, options RemediationsListForSubscriptionOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.PolicyInsights/remediations", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForRemediationsListForSubscriptionWithNextLink prepares the RemediationsListForSubscription request with the given nextLink token. +func (c PolicyInsightsClient) preparerForRemediationsListForSubscriptionWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRemediationsListForSubscription handles the response to the RemediationsListForSubscription request. The method always +// closes the http.Response Body. +func (c PolicyInsightsClient) responderForRemediationsListForSubscription(resp *http.Response) (result RemediationsListForSubscriptionOperationResponse, err error) { + type page struct { + Values []Remediation `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result RemediationsListForSubscriptionOperationResponse, err error) { + req, err := c.preparerForRemediationsListForSubscriptionWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForSubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForSubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRemediationsListForSubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "policyinsights.PolicyInsightsClient", "RemediationsListForSubscription", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_errordefinition.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_errordefinition.go new file mode 100644 index 000000000000..73d281600885 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_errordefinition.go @@ -0,0 +1,12 @@ +package policyinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ErrorDefinition struct { + AdditionalInfo *[]TypedErrorInfo `json:"additionalInfo,omitempty"` + Code *string `json:"code,omitempty"` + Details *[]ErrorDefinition `json:"details,omitempty"` + Message *string `json:"message,omitempty"` + Target *string `json:"target,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediation.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediation.go new file mode 100644 index 000000000000..d9f3726df76b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediation.go @@ -0,0 +1,16 @@ +package policyinsights + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Remediation struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *RemediationProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationdeployment.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationdeployment.go new file mode 100644 index 000000000000..76cb6af039db --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationdeployment.go @@ -0,0 +1,44 @@ +package policyinsights + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationDeployment struct { + CreatedOn *string `json:"createdOn,omitempty"` + DeploymentId *string `json:"deploymentId,omitempty"` + Error *ErrorDefinition `json:"error,omitempty"` + LastUpdatedOn *string `json:"lastUpdatedOn,omitempty"` + RemediatedResourceId *string `json:"remediatedResourceId,omitempty"` + ResourceLocation *string `json:"resourceLocation,omitempty"` + Status *string `json:"status,omitempty"` +} + +func (o *RemediationDeployment) GetCreatedOnAsTime() (*time.Time, error) { + if o.CreatedOn == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedOn, "2006-01-02T15:04:05Z07:00") +} + +func (o *RemediationDeployment) SetCreatedOnAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedOn = &formatted +} + +func (o *RemediationDeployment) GetLastUpdatedOnAsTime() (*time.Time, error) { + if o.LastUpdatedOn == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastUpdatedOn, "2006-01-02T15:04:05Z07:00") +} + +func (o *RemediationDeployment) SetLastUpdatedOnAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastUpdatedOn = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationdeploymentsummary.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationdeploymentsummary.go new file mode 100644 index 000000000000..442bd3a52c29 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationdeploymentsummary.go @@ -0,0 +1,10 @@ +package policyinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationDeploymentSummary struct { + FailedDeployments *int64 `json:"failedDeployments,omitempty"` + SuccessfulDeployments *int64 `json:"successfulDeployments,omitempty"` + TotalDeployments *int64 `json:"totalDeployments,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationfilters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationfilters.go new file mode 100644 index 000000000000..af747350aa10 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationfilters.go @@ -0,0 +1,8 @@ +package policyinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationFilters struct { + Locations *[]string `json:"locations,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationproperties.go new file mode 100644 index 000000000000..df6a5980148f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationproperties.go @@ -0,0 +1,50 @@ +package policyinsights + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationProperties struct { + CorrelationId *string `json:"correlationId,omitempty"` + CreatedOn *string `json:"createdOn,omitempty"` + DeploymentStatus *RemediationDeploymentSummary `json:"deploymentStatus,omitempty"` + FailureThreshold *RemediationPropertiesFailureThreshold `json:"failureThreshold,omitempty"` + Filters *RemediationFilters `json:"filters,omitempty"` + LastUpdatedOn *string `json:"lastUpdatedOn,omitempty"` + ParallelDeployments *int64 `json:"parallelDeployments,omitempty"` + PolicyAssignmentId *string `json:"policyAssignmentId,omitempty"` + PolicyDefinitionReferenceId *string `json:"policyDefinitionReferenceId,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + ResourceCount *int64 `json:"resourceCount,omitempty"` + ResourceDiscoveryMode *ResourceDiscoveryMode `json:"resourceDiscoveryMode,omitempty"` + StatusMessage *string `json:"statusMessage,omitempty"` +} + +func (o *RemediationProperties) GetCreatedOnAsTime() (*time.Time, error) { + if o.CreatedOn == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedOn, "2006-01-02T15:04:05Z07:00") +} + +func (o *RemediationProperties) SetCreatedOnAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedOn = &formatted +} + +func (o *RemediationProperties) GetLastUpdatedOnAsTime() (*time.Time, error) { + if o.LastUpdatedOn == nil { + return nil, nil + } + return dates.ParseAsFormat(o.LastUpdatedOn, "2006-01-02T15:04:05Z07:00") +} + +func (o *RemediationProperties) SetLastUpdatedOnAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.LastUpdatedOn = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationpropertiesfailurethreshold.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationpropertiesfailurethreshold.go new file mode 100644 index 000000000000..2c193699940a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_remediationpropertiesfailurethreshold.go @@ -0,0 +1,8 @@ +package policyinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RemediationPropertiesFailureThreshold struct { + Percentage *float64 `json:"percentage,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_typederrorinfo.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_typederrorinfo.go new file mode 100644 index 000000000000..7315369e2712 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/model_typederrorinfo.go @@ -0,0 +1,9 @@ +package policyinsights + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type TypedErrorInfo struct { + Info *interface{} `json:"info,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/predicates.go new file mode 100644 index 000000000000..d96f35a073f0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/predicates.go @@ -0,0 +1,62 @@ +package policyinsights + +type RemediationOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p RemediationOperationPredicate) Matches(input Remediation) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} + +type RemediationDeploymentOperationPredicate struct { + CreatedOn *string + DeploymentId *string + LastUpdatedOn *string + RemediatedResourceId *string + ResourceLocation *string + Status *string +} + +func (p RemediationDeploymentOperationPredicate) Matches(input RemediationDeployment) bool { + + if p.CreatedOn != nil && (input.CreatedOn == nil && *p.CreatedOn != *input.CreatedOn) { + return false + } + + if p.DeploymentId != nil && (input.DeploymentId == nil && *p.DeploymentId != *input.DeploymentId) { + return false + } + + if p.LastUpdatedOn != nil && (input.LastUpdatedOn == nil && *p.LastUpdatedOn != *input.LastUpdatedOn) { + return false + } + + if p.RemediatedResourceId != nil && (input.RemediatedResourceId == nil && *p.RemediatedResourceId != *input.RemediatedResourceId) { + return false + } + + if p.ResourceLocation != nil && (input.ResourceLocation == nil && *p.ResourceLocation != *input.ResourceLocation) { + return false + } + + if p.Status != nil && (input.Status == nil && *p.Status != *input.Status) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/version.go new file mode 100644 index 000000000000..f70907012dee --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights/version.go @@ -0,0 +1,12 @@ +package policyinsights + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-10-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/policyinsights/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/README.md new file mode 100644 index 000000000000..266cf8709d2e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/README.md @@ -0,0 +1,197 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs` Documentation + +The `disasterrecoveryconfigs` SDK allows for interaction with the Azure Resource Manager Service `servicebus` (API Version `2021-06-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs" +``` + + +### Client Initialization + +```go +client := disasterrecoveryconfigs.NewDisasterRecoveryConfigsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.BreakPairing` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +read, err := client.BreakPairing(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.CheckNameAvailability` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +payload := disasterrecoveryconfigs.CheckNameAvailability{ + // ... +} + + +read, err := client.CheckNameAvailability(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +payload := disasterrecoveryconfigs.ArmDisasterRecovery{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.Delete` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.FailOver` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +payload := disasterrecoveryconfigs.FailoverProperties{ + // ... +} + + +read, err := client.FailOver(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.Get` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.GetAuthorizationRule` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +read, err := client.GetAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.List` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +// alternatively `client.List(ctx, id)` can be used to do batched pagination +items, err := client.ListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.ListAuthorizationRules` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewDisasterRecoveryConfigID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "aliasValue") + +// alternatively `client.ListAuthorizationRules(ctx, id)` can be used to do batched pagination +items, err := client.ListAuthorizationRulesComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `DisasterRecoveryConfigsClient.ListKeys` + +```go +ctx := context.TODO() +id := disasterrecoveryconfigs.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +read, err := client.ListKeys(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/client.go new file mode 100644 index 000000000000..92bd0f75168c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/client.go @@ -0,0 +1,18 @@ +package disasterrecoveryconfigs + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DisasterRecoveryConfigsClient struct { + Client autorest.Client + baseUri string +} + +func NewDisasterRecoveryConfigsClientWithBaseURI(endpoint string) DisasterRecoveryConfigsClient { + return DisasterRecoveryConfigsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/constants.go new file mode 100644 index 000000000000..06c06cd30fc1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/constants.go @@ -0,0 +1,139 @@ +package disasterrecoveryconfigs + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessRights string + +const ( + AccessRightsListen AccessRights = "Listen" + AccessRightsManage AccessRights = "Manage" + AccessRightsSend AccessRights = "Send" +) + +func PossibleValuesForAccessRights() []string { + return []string{ + string(AccessRightsListen), + string(AccessRightsManage), + string(AccessRightsSend), + } +} + +func parseAccessRights(input string) (*AccessRights, error) { + vals := map[string]AccessRights{ + "listen": AccessRightsListen, + "manage": AccessRightsManage, + "send": AccessRightsSend, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AccessRights(input) + return &out, nil +} + +type ProvisioningStateDR string + +const ( + ProvisioningStateDRAccepted ProvisioningStateDR = "Accepted" + ProvisioningStateDRFailed ProvisioningStateDR = "Failed" + ProvisioningStateDRSucceeded ProvisioningStateDR = "Succeeded" +) + +func PossibleValuesForProvisioningStateDR() []string { + return []string{ + string(ProvisioningStateDRAccepted), + string(ProvisioningStateDRFailed), + string(ProvisioningStateDRSucceeded), + } +} + +func parseProvisioningStateDR(input string) (*ProvisioningStateDR, error) { + vals := map[string]ProvisioningStateDR{ + "accepted": ProvisioningStateDRAccepted, + "failed": ProvisioningStateDRFailed, + "succeeded": ProvisioningStateDRSucceeded, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ProvisioningStateDR(input) + return &out, nil +} + +type RoleDisasterRecovery string + +const ( + RoleDisasterRecoveryPrimary RoleDisasterRecovery = "Primary" + RoleDisasterRecoveryPrimaryNotReplicating RoleDisasterRecovery = "PrimaryNotReplicating" + RoleDisasterRecoverySecondary RoleDisasterRecovery = "Secondary" +) + +func PossibleValuesForRoleDisasterRecovery() []string { + return []string{ + string(RoleDisasterRecoveryPrimary), + string(RoleDisasterRecoveryPrimaryNotReplicating), + string(RoleDisasterRecoverySecondary), + } +} + +func parseRoleDisasterRecovery(input string) (*RoleDisasterRecovery, error) { + vals := map[string]RoleDisasterRecovery{ + "primary": RoleDisasterRecoveryPrimary, + "primarynotreplicating": RoleDisasterRecoveryPrimaryNotReplicating, + "secondary": RoleDisasterRecoverySecondary, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := RoleDisasterRecovery(input) + return &out, nil +} + +type UnavailableReason string + +const ( + UnavailableReasonInvalidName UnavailableReason = "InvalidName" + UnavailableReasonNameInLockdown UnavailableReason = "NameInLockdown" + UnavailableReasonNameInUse UnavailableReason = "NameInUse" + UnavailableReasonNone UnavailableReason = "None" + UnavailableReasonSubscriptionIsDisabled UnavailableReason = "SubscriptionIsDisabled" + UnavailableReasonTooManyNamespaceInCurrentSubscription UnavailableReason = "TooManyNamespaceInCurrentSubscription" +) + +func PossibleValuesForUnavailableReason() []string { + return []string{ + string(UnavailableReasonInvalidName), + string(UnavailableReasonNameInLockdown), + string(UnavailableReasonNameInUse), + string(UnavailableReasonNone), + string(UnavailableReasonSubscriptionIsDisabled), + string(UnavailableReasonTooManyNamespaceInCurrentSubscription), + } +} + +func parseUnavailableReason(input string) (*UnavailableReason, error) { + vals := map[string]UnavailableReason{ + "invalidname": UnavailableReasonInvalidName, + "nameinlockdown": UnavailableReasonNameInLockdown, + "nameinuse": UnavailableReasonNameInUse, + "none": UnavailableReasonNone, + "subscriptionisdisabled": UnavailableReasonSubscriptionIsDisabled, + "toomanynamespaceincurrentsubscription": UnavailableReasonTooManyNamespaceInCurrentSubscription, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := UnavailableReason(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_authorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_authorizationrule.go new file mode 100644 index 000000000000..31f8873ab15d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_authorizationrule.go @@ -0,0 +1,137 @@ +package disasterrecoveryconfigs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = AuthorizationRuleId{} + +// AuthorizationRuleId is a struct representing the Resource ID for a Authorization Rule +type AuthorizationRuleId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + AuthorizationRuleName string +} + +// NewAuthorizationRuleID returns a new AuthorizationRuleId struct +func NewAuthorizationRuleID(subscriptionId string, resourceGroupName string, namespaceName string, authorizationRuleName string) AuthorizationRuleId { + return AuthorizationRuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + AuthorizationRuleName: authorizationRuleName, + } +} + +// ParseAuthorizationRuleID parses 'input' into a AuthorizationRuleId +func ParseAuthorizationRuleID(input string) (*AuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(AuthorizationRuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseAuthorizationRuleIDInsensitively parses 'input' case-insensitively into a AuthorizationRuleId +// note: this method should only be used for API response data and not user input +func ParseAuthorizationRuleIDInsensitively(input string) (*AuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(AuthorizationRuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateAuthorizationRuleID checks that 'input' can be parsed as a Authorization Rule ID +func ValidateAuthorizationRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseAuthorizationRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Authorization Rule ID +func (id AuthorizationRuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/authorizationRules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.AuthorizationRuleName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Authorization Rule ID +func (id AuthorizationRuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticAuthorizationRules", "authorizationRules", "authorizationRules"), + resourceids.UserSpecifiedSegment("authorizationRuleName", "authorizationRuleValue"), + } +} + +// String returns a human-readable description of this Authorization Rule ID +func (id AuthorizationRuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Authorization Rule Name: %q", id.AuthorizationRuleName), + } + return fmt.Sprintf("Authorization Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_disasterrecoveryconfig.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_disasterrecoveryconfig.go new file mode 100644 index 000000000000..71d68d16ba30 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_disasterrecoveryconfig.go @@ -0,0 +1,137 @@ +package disasterrecoveryconfigs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = DisasterRecoveryConfigId{} + +// DisasterRecoveryConfigId is a struct representing the Resource ID for a Disaster Recovery Config +type DisasterRecoveryConfigId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + Alias string +} + +// NewDisasterRecoveryConfigID returns a new DisasterRecoveryConfigId struct +func NewDisasterRecoveryConfigID(subscriptionId string, resourceGroupName string, namespaceName string, alias string) DisasterRecoveryConfigId { + return DisasterRecoveryConfigId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + Alias: alias, + } +} + +// ParseDisasterRecoveryConfigID parses 'input' into a DisasterRecoveryConfigId +func ParseDisasterRecoveryConfigID(input string) (*DisasterRecoveryConfigId, error) { + parser := resourceids.NewParserFromResourceIdType(DisasterRecoveryConfigId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := DisasterRecoveryConfigId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.Alias, ok = parsed.Parsed["alias"]; !ok { + return nil, fmt.Errorf("the segment 'alias' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseDisasterRecoveryConfigIDInsensitively parses 'input' case-insensitively into a DisasterRecoveryConfigId +// note: this method should only be used for API response data and not user input +func ParseDisasterRecoveryConfigIDInsensitively(input string) (*DisasterRecoveryConfigId, error) { + parser := resourceids.NewParserFromResourceIdType(DisasterRecoveryConfigId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := DisasterRecoveryConfigId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.Alias, ok = parsed.Parsed["alias"]; !ok { + return nil, fmt.Errorf("the segment 'alias' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateDisasterRecoveryConfigID checks that 'input' can be parsed as a Disaster Recovery Config ID +func ValidateDisasterRecoveryConfigID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseDisasterRecoveryConfigID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Disaster Recovery Config ID +func (id DisasterRecoveryConfigId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/disasterRecoveryConfigs/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.Alias) +} + +// Segments returns a slice of Resource ID Segments which comprise this Disaster Recovery Config ID +func (id DisasterRecoveryConfigId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticDisasterRecoveryConfigs", "disasterRecoveryConfigs", "disasterRecoveryConfigs"), + resourceids.UserSpecifiedSegment("alias", "aliasValue"), + } +} + +// String returns a human-readable description of this Disaster Recovery Config ID +func (id DisasterRecoveryConfigId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Alias: %q", id.Alias), + } + return fmt.Sprintf("Disaster Recovery Config (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_namespace.go new file mode 100644 index 000000000000..2b4c2f953466 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/id_namespace.go @@ -0,0 +1,124 @@ +package disasterrecoveryconfigs + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_breakpairing_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_breakpairing_autorest.go new file mode 100644 index 000000000000..144131ab3e57 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_breakpairing_autorest.go @@ -0,0 +1,66 @@ +package disasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type BreakPairingOperationResponse struct { + HttpResponse *http.Response +} + +// BreakPairing ... +func (c DisasterRecoveryConfigsClient) BreakPairing(ctx context.Context, id DisasterRecoveryConfigId) (result BreakPairingOperationResponse, err error) { + req, err := c.preparerForBreakPairing(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "BreakPairing", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "BreakPairing", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForBreakPairing(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "BreakPairing", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForBreakPairing prepares the BreakPairing request. +func (c DisasterRecoveryConfigsClient) preparerForBreakPairing(ctx context.Context, id DisasterRecoveryConfigId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/breakPairing", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForBreakPairing handles the response to the BreakPairing request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForBreakPairing(resp *http.Response) (result BreakPairingOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_checknameavailability_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_checknameavailability_autorest.go new file mode 100644 index 000000000000..29d5af69ca5f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_checknameavailability_autorest.go @@ -0,0 +1,69 @@ +package disasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailabilityOperationResponse struct { + HttpResponse *http.Response + Model *CheckNameAvailabilityResult +} + +// CheckNameAvailability ... +func (c DisasterRecoveryConfigsClient) CheckNameAvailability(ctx context.Context, id NamespaceId, input CheckNameAvailability) (result CheckNameAvailabilityOperationResponse, err error) { + req, err := c.preparerForCheckNameAvailability(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "CheckNameAvailability", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCheckNameAvailability(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "CheckNameAvailability", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCheckNameAvailability prepares the CheckNameAvailability request. +func (c DisasterRecoveryConfigsClient) preparerForCheckNameAvailability(ctx context.Context, id NamespaceId, input CheckNameAvailability) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/disasterRecoveryConfigs/checkNameAvailability", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCheckNameAvailability handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForCheckNameAvailability(resp *http.Response) (result CheckNameAvailabilityOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_createorupdate_autorest.go new file mode 100644 index 000000000000..f6ed48aef31d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package disasterrecoveryconfigs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *ArmDisasterRecovery +} + +// CreateOrUpdate ... +func (c DisasterRecoveryConfigsClient) CreateOrUpdate(ctx context.Context, id DisasterRecoveryConfigId, input ArmDisasterRecovery) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c DisasterRecoveryConfigsClient) preparerForCreateOrUpdate(ctx context.Context, id DisasterRecoveryConfigId, input ArmDisasterRecovery) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_delete_autorest.go new file mode 100644 index 000000000000..b98d8635ee1e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_delete_autorest.go @@ -0,0 +1,65 @@ +package disasterrecoveryconfigs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c DisasterRecoveryConfigsClient) Delete(ctx context.Context, id DisasterRecoveryConfigId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c DisasterRecoveryConfigsClient) preparerForDelete(ctx context.Context, id DisasterRecoveryConfigId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_failover_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_failover_autorest.go new file mode 100644 index 000000000000..a7a8f71ea7e0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_failover_autorest.go @@ -0,0 +1,67 @@ +package disasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FailOverOperationResponse struct { + HttpResponse *http.Response +} + +// FailOver ... +func (c DisasterRecoveryConfigsClient) FailOver(ctx context.Context, id DisasterRecoveryConfigId, input FailoverProperties) (result FailOverOperationResponse, err error) { + req, err := c.preparerForFailOver(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "FailOver", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "FailOver", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForFailOver(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "FailOver", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForFailOver prepares the FailOver request. +func (c DisasterRecoveryConfigsClient) preparerForFailOver(ctx context.Context, id DisasterRecoveryConfigId, input FailoverProperties) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/failover", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForFailOver handles the response to the FailOver request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForFailOver(resp *http.Response) (result FailOverOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_get_autorest.go new file mode 100644 index 000000000000..da5493fb0272 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_get_autorest.go @@ -0,0 +1,67 @@ +package disasterrecoveryconfigs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *ArmDisasterRecovery +} + +// Get ... +func (c DisasterRecoveryConfigsClient) Get(ctx context.Context, id DisasterRecoveryConfigId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c DisasterRecoveryConfigsClient) preparerForGet(ctx context.Context, id DisasterRecoveryConfigId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_getauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_getauthorizationrule_autorest.go new file mode 100644 index 000000000000..a4eea395979f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_getauthorizationrule_autorest.go @@ -0,0 +1,67 @@ +package disasterrecoveryconfigs + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *SBAuthorizationRule +} + +// GetAuthorizationRule ... +func (c DisasterRecoveryConfigsClient) GetAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (result GetAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForGetAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "GetAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "GetAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGetAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "GetAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGetAuthorizationRule prepares the GetAuthorizationRule request. +func (c DisasterRecoveryConfigsClient) preparerForGetAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGetAuthorizationRule handles the response to the GetAuthorizationRule request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForGetAuthorizationRule(resp *http.Response) (result GetAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_list_autorest.go new file mode 100644 index 000000000000..abd321a27394 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_list_autorest.go @@ -0,0 +1,186 @@ +package disasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *[]ArmDisasterRecovery + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) +} + +type ListCompleteResult struct { + Items []ArmDisasterRecovery +} + +func (r ListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// List ... +func (c DisasterRecoveryConfigsClient) List(ctx context.Context, id NamespaceId) (resp ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListComplete retrieves all of the results into a single object +func (c DisasterRecoveryConfigsClient) ListComplete(ctx context.Context, id NamespaceId) (ListCompleteResult, error) { + return c.ListCompleteMatchingPredicate(ctx, id, ArmDisasterRecoveryOperationPredicate{}) +} + +// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c DisasterRecoveryConfigsClient) ListCompleteMatchingPredicate(ctx context.Context, id NamespaceId, predicate ArmDisasterRecoveryOperationPredicate) (resp ListCompleteResult, err error) { + items := make([]ArmDisasterRecovery, 0) + + page, err := c.List(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForList prepares the List request. +func (c DisasterRecoveryConfigsClient) preparerForList(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/disasterRecoveryConfigs", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListWithNextLink prepares the List request with the given nextLink token. +func (c DisasterRecoveryConfigsClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + type page struct { + Values []ArmDisasterRecovery `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { + req, err := c.preparerForListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_listauthorizationrules_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_listauthorizationrules_autorest.go new file mode 100644 index 000000000000..e6bdeaccb281 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_listauthorizationrules_autorest.go @@ -0,0 +1,186 @@ +package disasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListAuthorizationRulesOperationResponse struct { + HttpResponse *http.Response + Model *[]SBAuthorizationRule + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListAuthorizationRulesOperationResponse, error) +} + +type ListAuthorizationRulesCompleteResult struct { + Items []SBAuthorizationRule +} + +func (r ListAuthorizationRulesOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListAuthorizationRulesOperationResponse) LoadMore(ctx context.Context) (resp ListAuthorizationRulesOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListAuthorizationRules ... +func (c DisasterRecoveryConfigsClient) ListAuthorizationRules(ctx context.Context, id DisasterRecoveryConfigId) (resp ListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForListAuthorizationRules(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "ListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "ListAuthorizationRules", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListAuthorizationRules(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "ListAuthorizationRules", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListAuthorizationRulesComplete retrieves all of the results into a single object +func (c DisasterRecoveryConfigsClient) ListAuthorizationRulesComplete(ctx context.Context, id DisasterRecoveryConfigId) (ListAuthorizationRulesCompleteResult, error) { + return c.ListAuthorizationRulesCompleteMatchingPredicate(ctx, id, SBAuthorizationRuleOperationPredicate{}) +} + +// ListAuthorizationRulesCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c DisasterRecoveryConfigsClient) ListAuthorizationRulesCompleteMatchingPredicate(ctx context.Context, id DisasterRecoveryConfigId, predicate SBAuthorizationRuleOperationPredicate) (resp ListAuthorizationRulesCompleteResult, err error) { + items := make([]SBAuthorizationRule, 0) + + page, err := c.ListAuthorizationRules(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListAuthorizationRulesCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListAuthorizationRules prepares the ListAuthorizationRules request. +func (c DisasterRecoveryConfigsClient) preparerForListAuthorizationRules(ctx context.Context, id DisasterRecoveryConfigId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/authorizationRules", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListAuthorizationRulesWithNextLink prepares the ListAuthorizationRules request with the given nextLink token. +func (c DisasterRecoveryConfigsClient) preparerForListAuthorizationRulesWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListAuthorizationRules handles the response to the ListAuthorizationRules request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForListAuthorizationRules(resp *http.Response) (result ListAuthorizationRulesOperationResponse, err error) { + type page struct { + Values []SBAuthorizationRule `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForListAuthorizationRulesWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "ListAuthorizationRules", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "ListAuthorizationRules", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListAuthorizationRules(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "ListAuthorizationRules", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_listkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_listkeys_autorest.go new file mode 100644 index 000000000000..1a26d3f29538 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/method_listkeys_autorest.go @@ -0,0 +1,68 @@ +package disasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// ListKeys ... +func (c DisasterRecoveryConfigsClient) ListKeys(ctx context.Context, id AuthorizationRuleId) (result ListKeysOperationResponse, err error) { + req, err := c.preparerForListKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "ListKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "ListKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "disasterrecoveryconfigs.DisasterRecoveryConfigsClient", "ListKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForListKeys prepares the ListKeys request. +func (c DisasterRecoveryConfigsClient) preparerForListKeys(ctx context.Context, id AuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListKeys handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (c DisasterRecoveryConfigsClient) responderForListKeys(resp *http.Response) (result ListKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_accesskeys.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_accesskeys.go new file mode 100644 index 000000000000..b3e1e8186bf3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_accesskeys.go @@ -0,0 +1,14 @@ +package disasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessKeys struct { + AliasPrimaryConnectionString *string `json:"aliasPrimaryConnectionString,omitempty"` + AliasSecondaryConnectionString *string `json:"aliasSecondaryConnectionString,omitempty"` + KeyName *string `json:"keyName,omitempty"` + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + PrimaryKey *string `json:"primaryKey,omitempty"` + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + SecondaryKey *string `json:"secondaryKey,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_armdisasterrecovery.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_armdisasterrecovery.go new file mode 100644 index 000000000000..1300a4b02e91 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_armdisasterrecovery.go @@ -0,0 +1,16 @@ +package disasterrecoveryconfigs + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ArmDisasterRecovery struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *ArmDisasterRecoveryProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_armdisasterrecoveryproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_armdisasterrecoveryproperties.go new file mode 100644 index 000000000000..233aac5a3e81 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_armdisasterrecoveryproperties.go @@ -0,0 +1,12 @@ +package disasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ArmDisasterRecoveryProperties struct { + AlternateName *string `json:"alternateName,omitempty"` + PartnerNamespace *string `json:"partnerNamespace,omitempty"` + PendingReplicationOperationsCount *int64 `json:"pendingReplicationOperationsCount,omitempty"` + ProvisioningState *ProvisioningStateDR `json:"provisioningState,omitempty"` + Role *RoleDisasterRecovery `json:"role,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_checknameavailability.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_checknameavailability.go new file mode 100644 index 000000000000..ce3efaa22e31 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_checknameavailability.go @@ -0,0 +1,8 @@ +package disasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailability struct { + Name string `json:"name"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_checknameavailabilityresult.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_checknameavailabilityresult.go new file mode 100644 index 000000000000..5704fc33d00d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_checknameavailabilityresult.go @@ -0,0 +1,10 @@ +package disasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailabilityResult struct { + Message *string `json:"message,omitempty"` + NameAvailable *bool `json:"nameAvailable,omitempty"` + Reason *UnavailableReason `json:"reason,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_failoverproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_failoverproperties.go new file mode 100644 index 000000000000..b9f9dc735b73 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_failoverproperties.go @@ -0,0 +1,8 @@ +package disasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FailoverProperties struct { + Properties *FailoverPropertiesProperties `json:"properties,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_failoverpropertiesproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_failoverpropertiesproperties.go new file mode 100644 index 000000000000..1d6aa6a722af --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_failoverpropertiesproperties.go @@ -0,0 +1,8 @@ +package disasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FailoverPropertiesProperties struct { + IsSafeFailover *bool `json:"IsSafeFailover,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_sbauthorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_sbauthorizationrule.go new file mode 100644 index 000000000000..71eeb750ccb9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_sbauthorizationrule.go @@ -0,0 +1,16 @@ +package disasterrecoveryconfigs + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBAuthorizationRule struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SBAuthorizationRuleProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_sbauthorizationruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_sbauthorizationruleproperties.go new file mode 100644 index 000000000000..eb27b8c1a6cb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/model_sbauthorizationruleproperties.go @@ -0,0 +1,8 @@ +package disasterrecoveryconfigs + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBAuthorizationRuleProperties struct { + Rights []AccessRights `json:"rights"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/predicates.go new file mode 100644 index 000000000000..b8bdab69f2b7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/predicates.go @@ -0,0 +1,47 @@ +package disasterrecoveryconfigs + +type ArmDisasterRecoveryOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p ArmDisasterRecoveryOperationPredicate) Matches(input ArmDisasterRecovery) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} + +type SBAuthorizationRuleOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p SBAuthorizationRuleOperationPredicate) Matches(input SBAuthorizationRule) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/version.go new file mode 100644 index 000000000000..36f568cd68c9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs/version.go @@ -0,0 +1,12 @@ +package disasterrecoveryconfigs + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-06-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/disasterrecoveryconfigs/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/README.md new file mode 100644 index 000000000000..98b1a661301a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/README.md @@ -0,0 +1,195 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces` Documentation + +The `namespaces` SDK allows for interaction with the Azure Resource Manager Service `servicebus` (API Version `2021-06-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces" +``` + + +### Client Initialization + +```go +client := namespaces.NewNamespacesClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `NamespacesClient.CheckNameAvailability` + +```go +ctx := context.TODO() +id := namespaces.NewSubscriptionID() + +payload := namespaces.CheckNameAvailability{ + // ... +} + + +read, err := client.CheckNameAvailability(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NamespacesClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +payload := namespaces.SBNamespace{ + // ... +} + + +if err := client.CreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `NamespacesClient.CreateOrUpdateNetworkRuleSet` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +payload := namespaces.NetworkRuleSet{ + // ... +} + + +read, err := client.CreateOrUpdateNetworkRuleSet(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NamespacesClient.Delete` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +if err := client.DeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `NamespacesClient.Get` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NamespacesClient.GetNetworkRuleSet` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +read, err := client.GetNetworkRuleSet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NamespacesClient.List` + +```go +ctx := context.TODO() +id := namespaces.NewSubscriptionID() + +// alternatively `client.List(ctx, id)` can be used to do batched pagination +items, err := client.ListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `NamespacesClient.ListByResourceGroup` + +```go +ctx := context.TODO() +id := namespaces.NewResourceGroupID() + +// alternatively `client.ListByResourceGroup(ctx, id)` can be used to do batched pagination +items, err := client.ListByResourceGroupComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `NamespacesClient.ListNetworkRuleSets` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +// alternatively `client.ListNetworkRuleSets(ctx, id)` can be used to do batched pagination +items, err := client.ListNetworkRuleSetsComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `NamespacesClient.Update` + +```go +ctx := context.TODO() +id := namespaces.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +payload := namespaces.SBNamespaceUpdateParameters{ + // ... +} + + +read, err := client.Update(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/client.go new file mode 100644 index 000000000000..bf25155c4194 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/client.go @@ -0,0 +1,18 @@ +package namespaces + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesClient struct { + Client autorest.Client + baseUri string +} + +func NewNamespacesClientWithBaseURI(endpoint string) NamespacesClient { + return NamespacesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/constants.go new file mode 100644 index 000000000000..20327b00897b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/constants.go @@ -0,0 +1,288 @@ +package namespaces + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DefaultAction string + +const ( + DefaultActionAllow DefaultAction = "Allow" + DefaultActionDeny DefaultAction = "Deny" +) + +func PossibleValuesForDefaultAction() []string { + return []string{ + string(DefaultActionAllow), + string(DefaultActionDeny), + } +} + +func parseDefaultAction(input string) (*DefaultAction, error) { + vals := map[string]DefaultAction{ + "allow": DefaultActionAllow, + "deny": DefaultActionDeny, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := DefaultAction(input) + return &out, nil +} + +type EndPointProvisioningState string + +const ( + EndPointProvisioningStateCanceled EndPointProvisioningState = "Canceled" + EndPointProvisioningStateCreating EndPointProvisioningState = "Creating" + EndPointProvisioningStateDeleting EndPointProvisioningState = "Deleting" + EndPointProvisioningStateFailed EndPointProvisioningState = "Failed" + EndPointProvisioningStateSucceeded EndPointProvisioningState = "Succeeded" + EndPointProvisioningStateUpdating EndPointProvisioningState = "Updating" +) + +func PossibleValuesForEndPointProvisioningState() []string { + return []string{ + string(EndPointProvisioningStateCanceled), + string(EndPointProvisioningStateCreating), + string(EndPointProvisioningStateDeleting), + string(EndPointProvisioningStateFailed), + string(EndPointProvisioningStateSucceeded), + string(EndPointProvisioningStateUpdating), + } +} + +func parseEndPointProvisioningState(input string) (*EndPointProvisioningState, error) { + vals := map[string]EndPointProvisioningState{ + "canceled": EndPointProvisioningStateCanceled, + "creating": EndPointProvisioningStateCreating, + "deleting": EndPointProvisioningStateDeleting, + "failed": EndPointProvisioningStateFailed, + "succeeded": EndPointProvisioningStateSucceeded, + "updating": EndPointProvisioningStateUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EndPointProvisioningState(input) + return &out, nil +} + +type KeySource string + +const ( + KeySourceMicrosoftPointKeyVault KeySource = "Microsoft.KeyVault" +) + +func PossibleValuesForKeySource() []string { + return []string{ + string(KeySourceMicrosoftPointKeyVault), + } +} + +func parseKeySource(input string) (*KeySource, error) { + vals := map[string]KeySource{ + "microsoft.keyvault": KeySourceMicrosoftPointKeyVault, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeySource(input) + return &out, nil +} + +type NetworkRuleIPAction string + +const ( + NetworkRuleIPActionAllow NetworkRuleIPAction = "Allow" +) + +func PossibleValuesForNetworkRuleIPAction() []string { + return []string{ + string(NetworkRuleIPActionAllow), + } +} + +func parseNetworkRuleIPAction(input string) (*NetworkRuleIPAction, error) { + vals := map[string]NetworkRuleIPAction{ + "allow": NetworkRuleIPActionAllow, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := NetworkRuleIPAction(input) + return &out, nil +} + +type PrivateLinkConnectionStatus string + +const ( + PrivateLinkConnectionStatusApproved PrivateLinkConnectionStatus = "Approved" + PrivateLinkConnectionStatusDisconnected PrivateLinkConnectionStatus = "Disconnected" + PrivateLinkConnectionStatusPending PrivateLinkConnectionStatus = "Pending" + PrivateLinkConnectionStatusRejected PrivateLinkConnectionStatus = "Rejected" +) + +func PossibleValuesForPrivateLinkConnectionStatus() []string { + return []string{ + string(PrivateLinkConnectionStatusApproved), + string(PrivateLinkConnectionStatusDisconnected), + string(PrivateLinkConnectionStatusPending), + string(PrivateLinkConnectionStatusRejected), + } +} + +func parsePrivateLinkConnectionStatus(input string) (*PrivateLinkConnectionStatus, error) { + vals := map[string]PrivateLinkConnectionStatus{ + "approved": PrivateLinkConnectionStatusApproved, + "disconnected": PrivateLinkConnectionStatusDisconnected, + "pending": PrivateLinkConnectionStatusPending, + "rejected": PrivateLinkConnectionStatusRejected, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := PrivateLinkConnectionStatus(input) + return &out, nil +} + +type PublicNetworkAccessFlag string + +const ( + PublicNetworkAccessFlagDisabled PublicNetworkAccessFlag = "Disabled" + PublicNetworkAccessFlagEnabled PublicNetworkAccessFlag = "Enabled" +) + +func PossibleValuesForPublicNetworkAccessFlag() []string { + return []string{ + string(PublicNetworkAccessFlagDisabled), + string(PublicNetworkAccessFlagEnabled), + } +} + +func parsePublicNetworkAccessFlag(input string) (*PublicNetworkAccessFlag, error) { + vals := map[string]PublicNetworkAccessFlag{ + "disabled": PublicNetworkAccessFlagDisabled, + "enabled": PublicNetworkAccessFlagEnabled, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := PublicNetworkAccessFlag(input) + return &out, nil +} + +type SkuName string + +const ( + SkuNameBasic SkuName = "Basic" + SkuNamePremium SkuName = "Premium" + SkuNameStandard SkuName = "Standard" +) + +func PossibleValuesForSkuName() []string { + return []string{ + string(SkuNameBasic), + string(SkuNamePremium), + string(SkuNameStandard), + } +} + +func parseSkuName(input string) (*SkuName, error) { + vals := map[string]SkuName{ + "basic": SkuNameBasic, + "premium": SkuNamePremium, + "standard": SkuNameStandard, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := SkuName(input) + return &out, nil +} + +type SkuTier string + +const ( + SkuTierBasic SkuTier = "Basic" + SkuTierPremium SkuTier = "Premium" + SkuTierStandard SkuTier = "Standard" +) + +func PossibleValuesForSkuTier() []string { + return []string{ + string(SkuTierBasic), + string(SkuTierPremium), + string(SkuTierStandard), + } +} + +func parseSkuTier(input string) (*SkuTier, error) { + vals := map[string]SkuTier{ + "basic": SkuTierBasic, + "premium": SkuTierPremium, + "standard": SkuTierStandard, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := SkuTier(input) + return &out, nil +} + +type UnavailableReason string + +const ( + UnavailableReasonInvalidName UnavailableReason = "InvalidName" + UnavailableReasonNameInLockdown UnavailableReason = "NameInLockdown" + UnavailableReasonNameInUse UnavailableReason = "NameInUse" + UnavailableReasonNone UnavailableReason = "None" + UnavailableReasonSubscriptionIsDisabled UnavailableReason = "SubscriptionIsDisabled" + UnavailableReasonTooManyNamespaceInCurrentSubscription UnavailableReason = "TooManyNamespaceInCurrentSubscription" +) + +func PossibleValuesForUnavailableReason() []string { + return []string{ + string(UnavailableReasonInvalidName), + string(UnavailableReasonNameInLockdown), + string(UnavailableReasonNameInUse), + string(UnavailableReasonNone), + string(UnavailableReasonSubscriptionIsDisabled), + string(UnavailableReasonTooManyNamespaceInCurrentSubscription), + } +} + +func parseUnavailableReason(input string) (*UnavailableReason, error) { + vals := map[string]UnavailableReason{ + "invalidname": UnavailableReasonInvalidName, + "nameinlockdown": UnavailableReasonNameInLockdown, + "nameinuse": UnavailableReasonNameInUse, + "none": UnavailableReasonNone, + "subscriptionisdisabled": UnavailableReasonSubscriptionIsDisabled, + "toomanynamespaceincurrentsubscription": UnavailableReasonTooManyNamespaceInCurrentSubscription, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := UnavailableReason(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/id_namespace.go new file mode 100644 index 000000000000..5157c14e1975 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/id_namespace.go @@ -0,0 +1,124 @@ +package namespaces + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_checknameavailability_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_checknameavailability_autorest.go new file mode 100644 index 000000000000..15a555f0713e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_checknameavailability_autorest.go @@ -0,0 +1,70 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailabilityOperationResponse struct { + HttpResponse *http.Response + Model *CheckNameAvailabilityResult +} + +// CheckNameAvailability ... +func (c NamespacesClient) CheckNameAvailability(ctx context.Context, id commonids.SubscriptionId, input CheckNameAvailability) (result CheckNameAvailabilityOperationResponse, err error) { + req, err := c.preparerForCheckNameAvailability(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CheckNameAvailability", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCheckNameAvailability(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CheckNameAvailability", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCheckNameAvailability prepares the CheckNameAvailability request. +func (c NamespacesClient) preparerForCheckNameAvailability(ctx context.Context, id commonids.SubscriptionId, input CheckNameAvailability) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.ServiceBus/checkNameAvailability", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCheckNameAvailability handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForCheckNameAvailability(resp *http.Response) (result CheckNameAvailabilityOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_createorupdate_autorest.go new file mode 100644 index 000000000000..dd5c74b4b2fd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_createorupdate_autorest.go @@ -0,0 +1,79 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CreateOrUpdate ... +func (c NamespacesClient) CreateOrUpdate(ctx context.Context, id NamespaceId, input SBNamespace) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CreateOrUpdateThenPoll performs CreateOrUpdate then polls until it's completed +func (c NamespacesClient) CreateOrUpdateThenPoll(ctx context.Context, id NamespaceId, input SBNamespace) error { + result, err := c.CreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing CreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c NamespacesClient) preparerForCreateOrUpdate(ctx context.Context, id NamespaceId, input SBNamespace) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCreateOrUpdate sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c NamespacesClient) senderForCreateOrUpdate(ctx context.Context, req *http.Request) (future CreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_createorupdatenetworkruleset_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_createorupdatenetworkruleset_autorest.go new file mode 100644 index 000000000000..47ba03628477 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_createorupdatenetworkruleset_autorest.go @@ -0,0 +1,69 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateNetworkRuleSetOperationResponse struct { + HttpResponse *http.Response + Model *NetworkRuleSet +} + +// CreateOrUpdateNetworkRuleSet ... +func (c NamespacesClient) CreateOrUpdateNetworkRuleSet(ctx context.Context, id NamespaceId, input NetworkRuleSet) (result CreateOrUpdateNetworkRuleSetOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdateNetworkRuleSet(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CreateOrUpdateNetworkRuleSet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CreateOrUpdateNetworkRuleSet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdateNetworkRuleSet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "CreateOrUpdateNetworkRuleSet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdateNetworkRuleSet prepares the CreateOrUpdateNetworkRuleSet request. +func (c NamespacesClient) preparerForCreateOrUpdateNetworkRuleSet(ctx context.Context, id NamespaceId, input NetworkRuleSet) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/networkRuleSets/default", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdateNetworkRuleSet handles the response to the CreateOrUpdateNetworkRuleSet request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForCreateOrUpdateNetworkRuleSet(resp *http.Response) (result CreateOrUpdateNetworkRuleSetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_delete_autorest.go new file mode 100644 index 000000000000..968dfe754f22 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_delete_autorest.go @@ -0,0 +1,78 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Delete ... +func (c NamespacesClient) Delete(ctx context.Context, id NamespaceId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = c.senderForDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// DeleteThenPoll performs Delete then polls until it's completed +func (c NamespacesClient) DeleteThenPoll(ctx context.Context, id NamespaceId) error { + result, err := c.Delete(ctx, id) + if err != nil { + return fmt.Errorf("performing Delete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Delete: %+v", err) + } + + return nil +} + +// preparerForDelete prepares the Delete request. +func (c NamespacesClient) preparerForDelete(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForDelete sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (c NamespacesClient) senderForDelete(ctx context.Context, req *http.Request) (future DeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_get_autorest.go new file mode 100644 index 000000000000..403daa159d33 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_get_autorest.go @@ -0,0 +1,67 @@ +package namespaces + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *SBNamespace +} + +// Get ... +func (c NamespacesClient) Get(ctx context.Context, id NamespaceId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c NamespacesClient) preparerForGet(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_getnetworkruleset_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_getnetworkruleset_autorest.go new file mode 100644 index 000000000000..929737999ebf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_getnetworkruleset_autorest.go @@ -0,0 +1,68 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetNetworkRuleSetOperationResponse struct { + HttpResponse *http.Response + Model *NetworkRuleSet +} + +// GetNetworkRuleSet ... +func (c NamespacesClient) GetNetworkRuleSet(ctx context.Context, id NamespaceId) (result GetNetworkRuleSetOperationResponse, err error) { + req, err := c.preparerForGetNetworkRuleSet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "GetNetworkRuleSet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "GetNetworkRuleSet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGetNetworkRuleSet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "GetNetworkRuleSet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGetNetworkRuleSet prepares the GetNetworkRuleSet request. +func (c NamespacesClient) preparerForGetNetworkRuleSet(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/networkRuleSets/default", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGetNetworkRuleSet handles the response to the GetNetworkRuleSet request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForGetNetworkRuleSet(resp *http.Response) (result GetNetworkRuleSetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_list_autorest.go new file mode 100644 index 000000000000..462132445705 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_list_autorest.go @@ -0,0 +1,187 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *[]SBNamespace + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) +} + +type ListCompleteResult struct { + Items []SBNamespace +} + +func (r ListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// List ... +func (c NamespacesClient) List(ctx context.Context, id commonids.SubscriptionId) (resp ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListComplete retrieves all of the results into a single object +func (c NamespacesClient) ListComplete(ctx context.Context, id commonids.SubscriptionId) (ListCompleteResult, error) { + return c.ListCompleteMatchingPredicate(ctx, id, SBNamespaceOperationPredicate{}) +} + +// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c NamespacesClient) ListCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate SBNamespaceOperationPredicate) (resp ListCompleteResult, err error) { + items := make([]SBNamespace, 0) + + page, err := c.List(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForList prepares the List request. +func (c NamespacesClient) preparerForList(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.ServiceBus/namespaces", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListWithNextLink prepares the List request with the given nextLink token. +func (c NamespacesClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + type page struct { + Values []SBNamespace `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { + req, err := c.preparerForListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_listbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_listbyresourcegroup_autorest.go new file mode 100644 index 000000000000..3fd7cc3216d1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_listbyresourcegroup_autorest.go @@ -0,0 +1,187 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]SBNamespace + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByResourceGroupOperationResponse, error) +} + +type ListByResourceGroupCompleteResult struct { + Items []SBNamespace +} + +func (r ListByResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ListByResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListByResourceGroup ... +func (c NamespacesClient) ListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByResourceGroupComplete retrieves all of the results into a single object +func (c NamespacesClient) ListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ListByResourceGroupCompleteResult, error) { + return c.ListByResourceGroupCompleteMatchingPredicate(ctx, id, SBNamespaceOperationPredicate{}) +} + +// ListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c NamespacesClient) ListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate SBNamespaceOperationPredicate) (resp ListByResourceGroupCompleteResult, err error) { + items := make([]SBNamespace, 0) + + page, err := c.ListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByResourceGroup prepares the ListByResourceGroup request. +func (c NamespacesClient) preparerForListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.ServiceBus/namespaces", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByResourceGroupWithNextLink prepares the ListByResourceGroup request with the given nextLink token. +func (c NamespacesClient) preparerForListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByResourceGroup handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForListByResourceGroup(resp *http.Response) (result ListByResourceGroupOperationResponse, err error) { + type page struct { + Values []SBNamespace `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_listnetworkrulesets_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_listnetworkrulesets_autorest.go new file mode 100644 index 000000000000..3993bb002402 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_listnetworkrulesets_autorest.go @@ -0,0 +1,186 @@ +package namespaces + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListNetworkRuleSetsOperationResponse struct { + HttpResponse *http.Response + Model *[]NetworkRuleSet + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListNetworkRuleSetsOperationResponse, error) +} + +type ListNetworkRuleSetsCompleteResult struct { + Items []NetworkRuleSet +} + +func (r ListNetworkRuleSetsOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListNetworkRuleSetsOperationResponse) LoadMore(ctx context.Context) (resp ListNetworkRuleSetsOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListNetworkRuleSets ... +func (c NamespacesClient) ListNetworkRuleSets(ctx context.Context, id NamespaceId) (resp ListNetworkRuleSetsOperationResponse, err error) { + req, err := c.preparerForListNetworkRuleSets(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListNetworkRuleSets", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListNetworkRuleSets", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListNetworkRuleSets(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListNetworkRuleSets", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListNetworkRuleSetsComplete retrieves all of the results into a single object +func (c NamespacesClient) ListNetworkRuleSetsComplete(ctx context.Context, id NamespaceId) (ListNetworkRuleSetsCompleteResult, error) { + return c.ListNetworkRuleSetsCompleteMatchingPredicate(ctx, id, NetworkRuleSetOperationPredicate{}) +} + +// ListNetworkRuleSetsCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c NamespacesClient) ListNetworkRuleSetsCompleteMatchingPredicate(ctx context.Context, id NamespaceId, predicate NetworkRuleSetOperationPredicate) (resp ListNetworkRuleSetsCompleteResult, err error) { + items := make([]NetworkRuleSet, 0) + + page, err := c.ListNetworkRuleSets(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListNetworkRuleSetsCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListNetworkRuleSets prepares the ListNetworkRuleSets request. +func (c NamespacesClient) preparerForListNetworkRuleSets(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/networkRuleSets", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListNetworkRuleSetsWithNextLink prepares the ListNetworkRuleSets request with the given nextLink token. +func (c NamespacesClient) preparerForListNetworkRuleSetsWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListNetworkRuleSets handles the response to the ListNetworkRuleSets request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForListNetworkRuleSets(resp *http.Response) (result ListNetworkRuleSetsOperationResponse, err error) { + type page struct { + Values []NetworkRuleSet `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListNetworkRuleSetsOperationResponse, err error) { + req, err := c.preparerForListNetworkRuleSetsWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListNetworkRuleSets", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListNetworkRuleSets", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListNetworkRuleSets(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "ListNetworkRuleSets", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_update_autorest.go new file mode 100644 index 000000000000..09f620ced474 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/method_update_autorest.go @@ -0,0 +1,68 @@ +package namespaces + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + HttpResponse *http.Response + Model *SBNamespace +} + +// Update ... +func (c NamespacesClient) Update(ctx context.Context, id NamespaceId, input SBNamespaceUpdateParameters) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Update", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespaces.NamespacesClient", "Update", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForUpdate prepares the Update request. +func (c NamespacesClient) preparerForUpdate(ctx context.Context, id NamespaceId, input SBNamespaceUpdateParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForUpdate handles the response to the Update request. The method always +// closes the http.Response Body. +func (c NamespacesClient) responderForUpdate(resp *http.Response) (result UpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_checknameavailability.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_checknameavailability.go new file mode 100644 index 000000000000..611253e0b836 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_checknameavailability.go @@ -0,0 +1,8 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailability struct { + Name string `json:"name"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_checknameavailabilityresult.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_checknameavailabilityresult.go new file mode 100644 index 000000000000..9d301c5d67a8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_checknameavailabilityresult.go @@ -0,0 +1,10 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailabilityResult struct { + Message *string `json:"message,omitempty"` + NameAvailable *bool `json:"nameAvailable,omitempty"` + Reason *UnavailableReason `json:"reason,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_connectionstate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_connectionstate.go new file mode 100644 index 000000000000..022aa980debf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_connectionstate.go @@ -0,0 +1,9 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ConnectionState struct { + Description *string `json:"description,omitempty"` + Status *PrivateLinkConnectionStatus `json:"status,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_encryption.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_encryption.go new file mode 100644 index 000000000000..c33fdbc6fad2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_encryption.go @@ -0,0 +1,10 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Encryption struct { + KeySource *KeySource `json:"keySource,omitempty"` + KeyVaultProperties *[]KeyVaultProperties `json:"keyVaultProperties,omitempty"` + RequireInfrastructureEncryption *bool `json:"requireInfrastructureEncryption,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_keyvaultproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_keyvaultproperties.go new file mode 100644 index 000000000000..b0dfb9a4e063 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_keyvaultproperties.go @@ -0,0 +1,11 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type KeyVaultProperties struct { + Identity *UserAssignedIdentityProperties `json:"identity,omitempty"` + KeyName *string `json:"keyName,omitempty"` + KeyVaultUri *string `json:"keyVaultUri,omitempty"` + KeyVersion *string `json:"keyVersion,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_networkruleset.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_networkruleset.go new file mode 100644 index 000000000000..de435f2efd13 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_networkruleset.go @@ -0,0 +1,16 @@ +package namespaces + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NetworkRuleSet struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *NetworkRuleSetProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_networkrulesetproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_networkrulesetproperties.go new file mode 100644 index 000000000000..b7de4f3f9e31 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_networkrulesetproperties.go @@ -0,0 +1,12 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NetworkRuleSetProperties struct { + DefaultAction *DefaultAction `json:"defaultAction,omitempty"` + IpRules *[]NWRuleSetIpRules `json:"ipRules,omitempty"` + PublicNetworkAccess *PublicNetworkAccessFlag `json:"publicNetworkAccess,omitempty"` + TrustedServiceAccessEnabled *bool `json:"trustedServiceAccessEnabled,omitempty"` + VirtualNetworkRules *[]NWRuleSetVirtualNetworkRules `json:"virtualNetworkRules,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_nwrulesetiprules.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_nwrulesetiprules.go new file mode 100644 index 000000000000..311b4eed0bf5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_nwrulesetiprules.go @@ -0,0 +1,9 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NWRuleSetIpRules struct { + Action *NetworkRuleIPAction `json:"action,omitempty"` + IpMask *string `json:"ipMask,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_nwrulesetvirtualnetworkrules.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_nwrulesetvirtualnetworkrules.go new file mode 100644 index 000000000000..284f1c7eaba1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_nwrulesetvirtualnetworkrules.go @@ -0,0 +1,9 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NWRuleSetVirtualNetworkRules struct { + IgnoreMissingVnetServiceEndpoint *bool `json:"ignoreMissingVnetServiceEndpoint,omitempty"` + Subnet *Subnet `json:"subnet,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpoint.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpoint.go new file mode 100644 index 000000000000..3dec0387e5f1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpoint.go @@ -0,0 +1,8 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpoint struct { + Id *string `json:"id,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpointconnection.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpointconnection.go new file mode 100644 index 000000000000..d60671cf999e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpointconnection.go @@ -0,0 +1,16 @@ +package namespaces + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnection struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *PrivateEndpointConnectionProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpointconnectionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpointconnectionproperties.go new file mode 100644 index 000000000000..e0aa15c59571 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_privateendpointconnectionproperties.go @@ -0,0 +1,10 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionProperties struct { + PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` + PrivateLinkServiceConnectionState *ConnectionState `json:"privateLinkServiceConnectionState,omitempty"` + ProvisioningState *EndPointProvisioningState `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespace.go new file mode 100644 index 000000000000..396988a40b8d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespace.go @@ -0,0 +1,21 @@ +package namespaces + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBNamespace struct { + Id *string `json:"id,omitempty"` + Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` + Location string `json:"location"` + Name *string `json:"name,omitempty"` + Properties *SBNamespaceProperties `json:"properties,omitempty"` + Sku *SBSku `json:"sku,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespaceproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespaceproperties.go new file mode 100644 index 000000000000..8d542149d699 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespaceproperties.go @@ -0,0 +1,47 @@ +package namespaces + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBNamespaceProperties struct { + CreatedAt *string `json:"createdAt,omitempty"` + DisableLocalAuth *bool `json:"disableLocalAuth,omitempty"` + Encryption *Encryption `json:"encryption,omitempty"` + MetricId *string `json:"metricId,omitempty"` + PrivateEndpointConnections *[]PrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + ServiceBusEndpoint *string `json:"serviceBusEndpoint,omitempty"` + Status *string `json:"status,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` + ZoneRedundant *bool `json:"zoneRedundant,omitempty"` +} + +func (o *SBNamespaceProperties) GetCreatedAtAsTime() (*time.Time, error) { + if o.CreatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBNamespaceProperties) SetCreatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedAt = &formatted +} + +func (o *SBNamespaceProperties) GetUpdatedAtAsTime() (*time.Time, error) { + if o.UpdatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.UpdatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBNamespaceProperties) SetUpdatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.UpdatedAt = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespaceupdateparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespaceupdateparameters.go new file mode 100644 index 000000000000..777d5348737b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbnamespaceupdateparameters.go @@ -0,0 +1,19 @@ +package namespaces + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBNamespaceUpdateParameters struct { + Id *string `json:"id,omitempty"` + Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SBNamespaceProperties `json:"properties,omitempty"` + Sku *SBSku `json:"sku,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbsku.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbsku.go new file mode 100644 index 000000000000..669994013767 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_sbsku.go @@ -0,0 +1,10 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBSku struct { + Capacity *int64 `json:"capacity,omitempty"` + Name SkuName `json:"name"` + Tier *SkuTier `json:"tier,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_subnet.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_subnet.go new file mode 100644 index 000000000000..418829480082 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_subnet.go @@ -0,0 +1,8 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Subnet struct { + Id string `json:"id"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_userassignedidentityproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_userassignedidentityproperties.go new file mode 100644 index 000000000000..0685aa3ea141 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/model_userassignedidentityproperties.go @@ -0,0 +1,8 @@ +package namespaces + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UserAssignedIdentityProperties struct { + UserAssignedIdentity *string `json:"userAssignedIdentity,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/predicates.go new file mode 100644 index 000000000000..b944fa7149b5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/predicates.go @@ -0,0 +1,52 @@ +package namespaces + +type NetworkRuleSetOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p NetworkRuleSetOperationPredicate) Matches(input NetworkRuleSet) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} + +type SBNamespaceOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p SBNamespaceOperationPredicate) Matches(input SBNamespace) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && *p.Location != input.Location { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/version.go new file mode 100644 index 000000000000..90d6cc833546 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces/version.go @@ -0,0 +1,12 @@ +package namespaces + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-06-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/namespaces/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/README.md new file mode 100644 index 000000000000..d0b6b63a6237 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/README.md @@ -0,0 +1,127 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule` Documentation + +The `namespacesauthorizationrule` SDK allows for interaction with the Azure Resource Manager Service `servicebus` (API Version `2021-06-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule" +``` + + +### Client Initialization + +```go +client := namespacesauthorizationrule.NewNamespacesAuthorizationRuleClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `NamespacesAuthorizationRuleClient.NamespacesCreateOrUpdateAuthorizationRule` + +```go +ctx := context.TODO() +id := namespacesauthorizationrule.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +payload := namespacesauthorizationrule.SBAuthorizationRule{ + // ... +} + + +read, err := client.NamespacesCreateOrUpdateAuthorizationRule(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NamespacesAuthorizationRuleClient.NamespacesDeleteAuthorizationRule` + +```go +ctx := context.TODO() +id := namespacesauthorizationrule.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +read, err := client.NamespacesDeleteAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NamespacesAuthorizationRuleClient.NamespacesGetAuthorizationRule` + +```go +ctx := context.TODO() +id := namespacesauthorizationrule.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +read, err := client.NamespacesGetAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NamespacesAuthorizationRuleClient.NamespacesListAuthorizationRules` + +```go +ctx := context.TODO() +id := namespacesauthorizationrule.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +// alternatively `client.NamespacesListAuthorizationRules(ctx, id)` can be used to do batched pagination +items, err := client.NamespacesListAuthorizationRulesComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `NamespacesAuthorizationRuleClient.NamespacesListKeys` + +```go +ctx := context.TODO() +id := namespacesauthorizationrule.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +read, err := client.NamespacesListKeys(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `NamespacesAuthorizationRuleClient.NamespacesRegenerateKeys` + +```go +ctx := context.TODO() +id := namespacesauthorizationrule.NewAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "authorizationRuleValue") + +payload := namespacesauthorizationrule.RegenerateAccessKeyParameters{ + // ... +} + + +read, err := client.NamespacesRegenerateKeys(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/client.go new file mode 100644 index 000000000000..e4aacfdfcd63 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/client.go @@ -0,0 +1,18 @@ +package namespacesauthorizationrule + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesAuthorizationRuleClient struct { + Client autorest.Client + baseUri string +} + +func NewNamespacesAuthorizationRuleClientWithBaseURI(endpoint string) NamespacesAuthorizationRuleClient { + return NamespacesAuthorizationRuleClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/constants.go new file mode 100644 index 000000000000..9e833425f0bd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/constants.go @@ -0,0 +1,65 @@ +package namespacesauthorizationrule + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessRights string + +const ( + AccessRightsListen AccessRights = "Listen" + AccessRightsManage AccessRights = "Manage" + AccessRightsSend AccessRights = "Send" +) + +func PossibleValuesForAccessRights() []string { + return []string{ + string(AccessRightsListen), + string(AccessRightsManage), + string(AccessRightsSend), + } +} + +func parseAccessRights(input string) (*AccessRights, error) { + vals := map[string]AccessRights{ + "listen": AccessRightsListen, + "manage": AccessRightsManage, + "send": AccessRightsSend, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AccessRights(input) + return &out, nil +} + +type KeyType string + +const ( + KeyTypePrimaryKey KeyType = "PrimaryKey" + KeyTypeSecondaryKey KeyType = "SecondaryKey" +) + +func PossibleValuesForKeyType() []string { + return []string{ + string(KeyTypePrimaryKey), + string(KeyTypeSecondaryKey), + } +} + +func parseKeyType(input string) (*KeyType, error) { + vals := map[string]KeyType{ + "primarykey": KeyTypePrimaryKey, + "secondarykey": KeyTypeSecondaryKey, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeyType(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/id_authorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/id_authorizationrule.go new file mode 100644 index 000000000000..efd5e0b02d9d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/id_authorizationrule.go @@ -0,0 +1,137 @@ +package namespacesauthorizationrule + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = AuthorizationRuleId{} + +// AuthorizationRuleId is a struct representing the Resource ID for a Authorization Rule +type AuthorizationRuleId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + AuthorizationRuleName string +} + +// NewAuthorizationRuleID returns a new AuthorizationRuleId struct +func NewAuthorizationRuleID(subscriptionId string, resourceGroupName string, namespaceName string, authorizationRuleName string) AuthorizationRuleId { + return AuthorizationRuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + AuthorizationRuleName: authorizationRuleName, + } +} + +// ParseAuthorizationRuleID parses 'input' into a AuthorizationRuleId +func ParseAuthorizationRuleID(input string) (*AuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(AuthorizationRuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseAuthorizationRuleIDInsensitively parses 'input' case-insensitively into a AuthorizationRuleId +// note: this method should only be used for API response data and not user input +func ParseAuthorizationRuleIDInsensitively(input string) (*AuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(AuthorizationRuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := AuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateAuthorizationRuleID checks that 'input' can be parsed as a Authorization Rule ID +func ValidateAuthorizationRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseAuthorizationRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Authorization Rule ID +func (id AuthorizationRuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/authorizationRules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.AuthorizationRuleName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Authorization Rule ID +func (id AuthorizationRuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticAuthorizationRules", "authorizationRules", "authorizationRules"), + resourceids.UserSpecifiedSegment("authorizationRuleName", "authorizationRuleValue"), + } +} + +// String returns a human-readable description of this Authorization Rule ID +func (id AuthorizationRuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Authorization Rule Name: %q", id.AuthorizationRuleName), + } + return fmt.Sprintf("Authorization Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/id_namespace.go new file mode 100644 index 000000000000..f0bc18d1dbb4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/id_namespace.go @@ -0,0 +1,124 @@ +package namespacesauthorizationrule + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacescreateorupdateauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacescreateorupdateauthorizationrule_autorest.go new file mode 100644 index 000000000000..da678cb00879 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacescreateorupdateauthorizationrule_autorest.go @@ -0,0 +1,68 @@ +package namespacesauthorizationrule + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesCreateOrUpdateAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *SBAuthorizationRule +} + +// NamespacesCreateOrUpdateAuthorizationRule ... +func (c NamespacesAuthorizationRuleClient) NamespacesCreateOrUpdateAuthorizationRule(ctx context.Context, id AuthorizationRuleId, input SBAuthorizationRule) (result NamespacesCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForNamespacesCreateOrUpdateAuthorizationRule(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesCreateOrUpdateAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesCreateOrUpdateAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesCreateOrUpdateAuthorizationRule prepares the NamespacesCreateOrUpdateAuthorizationRule request. +func (c NamespacesAuthorizationRuleClient) preparerForNamespacesCreateOrUpdateAuthorizationRule(ctx context.Context, id AuthorizationRuleId, input SBAuthorizationRule) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesCreateOrUpdateAuthorizationRule handles the response to the NamespacesCreateOrUpdateAuthorizationRule request. The method always +// closes the http.Response Body. +func (c NamespacesAuthorizationRuleClient) responderForNamespacesCreateOrUpdateAuthorizationRule(resp *http.Response) (result NamespacesCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesdeleteauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesdeleteauthorizationrule_autorest.go new file mode 100644 index 000000000000..12b549e99e4a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesdeleteauthorizationrule_autorest.go @@ -0,0 +1,65 @@ +package namespacesauthorizationrule + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesDeleteAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response +} + +// NamespacesDeleteAuthorizationRule ... +func (c NamespacesAuthorizationRuleClient) NamespacesDeleteAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (result NamespacesDeleteAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForNamespacesDeleteAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesDeleteAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesDeleteAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesDeleteAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesDeleteAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesDeleteAuthorizationRule prepares the NamespacesDeleteAuthorizationRule request. +func (c NamespacesAuthorizationRuleClient) preparerForNamespacesDeleteAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesDeleteAuthorizationRule handles the response to the NamespacesDeleteAuthorizationRule request. The method always +// closes the http.Response Body. +func (c NamespacesAuthorizationRuleClient) responderForNamespacesDeleteAuthorizationRule(resp *http.Response) (result NamespacesDeleteAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesgetauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesgetauthorizationrule_autorest.go new file mode 100644 index 000000000000..91f182aa4553 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesgetauthorizationrule_autorest.go @@ -0,0 +1,67 @@ +package namespacesauthorizationrule + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesGetAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *SBAuthorizationRule +} + +// NamespacesGetAuthorizationRule ... +func (c NamespacesAuthorizationRuleClient) NamespacesGetAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (result NamespacesGetAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForNamespacesGetAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesGetAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesGetAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesGetAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesGetAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesGetAuthorizationRule prepares the NamespacesGetAuthorizationRule request. +func (c NamespacesAuthorizationRuleClient) preparerForNamespacesGetAuthorizationRule(ctx context.Context, id AuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesGetAuthorizationRule handles the response to the NamespacesGetAuthorizationRule request. The method always +// closes the http.Response Body. +func (c NamespacesAuthorizationRuleClient) responderForNamespacesGetAuthorizationRule(resp *http.Response) (result NamespacesGetAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespaceslistauthorizationrules_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespaceslistauthorizationrules_autorest.go new file mode 100644 index 000000000000..d1b97182d315 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespaceslistauthorizationrules_autorest.go @@ -0,0 +1,186 @@ +package namespacesauthorizationrule + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesListAuthorizationRulesOperationResponse struct { + HttpResponse *http.Response + Model *[]SBAuthorizationRule + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (NamespacesListAuthorizationRulesOperationResponse, error) +} + +type NamespacesListAuthorizationRulesCompleteResult struct { + Items []SBAuthorizationRule +} + +func (r NamespacesListAuthorizationRulesOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r NamespacesListAuthorizationRulesOperationResponse) LoadMore(ctx context.Context) (resp NamespacesListAuthorizationRulesOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// NamespacesListAuthorizationRules ... +func (c NamespacesAuthorizationRuleClient) NamespacesListAuthorizationRules(ctx context.Context, id NamespaceId) (resp NamespacesListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForNamespacesListAuthorizationRules(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesListAuthorizationRules", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForNamespacesListAuthorizationRules(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesListAuthorizationRules", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// NamespacesListAuthorizationRulesComplete retrieves all of the results into a single object +func (c NamespacesAuthorizationRuleClient) NamespacesListAuthorizationRulesComplete(ctx context.Context, id NamespaceId) (NamespacesListAuthorizationRulesCompleteResult, error) { + return c.NamespacesListAuthorizationRulesCompleteMatchingPredicate(ctx, id, SBAuthorizationRuleOperationPredicate{}) +} + +// NamespacesListAuthorizationRulesCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c NamespacesAuthorizationRuleClient) NamespacesListAuthorizationRulesCompleteMatchingPredicate(ctx context.Context, id NamespaceId, predicate SBAuthorizationRuleOperationPredicate) (resp NamespacesListAuthorizationRulesCompleteResult, err error) { + items := make([]SBAuthorizationRule, 0) + + page, err := c.NamespacesListAuthorizationRules(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := NamespacesListAuthorizationRulesCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForNamespacesListAuthorizationRules prepares the NamespacesListAuthorizationRules request. +func (c NamespacesAuthorizationRuleClient) preparerForNamespacesListAuthorizationRules(ctx context.Context, id NamespaceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/authorizationRules", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForNamespacesListAuthorizationRulesWithNextLink prepares the NamespacesListAuthorizationRules request with the given nextLink token. +func (c NamespacesAuthorizationRuleClient) preparerForNamespacesListAuthorizationRulesWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesListAuthorizationRules handles the response to the NamespacesListAuthorizationRules request. The method always +// closes the http.Response Body. +func (c NamespacesAuthorizationRuleClient) responderForNamespacesListAuthorizationRules(resp *http.Response) (result NamespacesListAuthorizationRulesOperationResponse, err error) { + type page struct { + Values []SBAuthorizationRule `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result NamespacesListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForNamespacesListAuthorizationRulesWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesListAuthorizationRules", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesListAuthorizationRules", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesListAuthorizationRules(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesListAuthorizationRules", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespaceslistkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespaceslistkeys_autorest.go new file mode 100644 index 000000000000..29d9575e85fa --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespaceslistkeys_autorest.go @@ -0,0 +1,68 @@ +package namespacesauthorizationrule + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesListKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// NamespacesListKeys ... +func (c NamespacesAuthorizationRuleClient) NamespacesListKeys(ctx context.Context, id AuthorizationRuleId) (result NamespacesListKeysOperationResponse, err error) { + req, err := c.preparerForNamespacesListKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesListKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesListKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesListKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesListKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesListKeys prepares the NamespacesListKeys request. +func (c NamespacesAuthorizationRuleClient) preparerForNamespacesListKeys(ctx context.Context, id AuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesListKeys handles the response to the NamespacesListKeys request. The method always +// closes the http.Response Body. +func (c NamespacesAuthorizationRuleClient) responderForNamespacesListKeys(resp *http.Response) (result NamespacesListKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesregeneratekeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesregeneratekeys_autorest.go new file mode 100644 index 000000000000..93d0753f72bb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/method_namespacesregeneratekeys_autorest.go @@ -0,0 +1,69 @@ +package namespacesauthorizationrule + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NamespacesRegenerateKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// NamespacesRegenerateKeys ... +func (c NamespacesAuthorizationRuleClient) NamespacesRegenerateKeys(ctx context.Context, id AuthorizationRuleId, input RegenerateAccessKeyParameters) (result NamespacesRegenerateKeysOperationResponse, err error) { + req, err := c.preparerForNamespacesRegenerateKeys(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesRegenerateKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesRegenerateKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForNamespacesRegenerateKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "namespacesauthorizationrule.NamespacesAuthorizationRuleClient", "NamespacesRegenerateKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForNamespacesRegenerateKeys prepares the NamespacesRegenerateKeys request. +func (c NamespacesAuthorizationRuleClient) preparerForNamespacesRegenerateKeys(ctx context.Context, id AuthorizationRuleId, input RegenerateAccessKeyParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/regenerateKeys", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForNamespacesRegenerateKeys handles the response to the NamespacesRegenerateKeys request. The method always +// closes the http.Response Body. +func (c NamespacesAuthorizationRuleClient) responderForNamespacesRegenerateKeys(resp *http.Response) (result NamespacesRegenerateKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_accesskeys.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_accesskeys.go new file mode 100644 index 000000000000..7c9ec1504776 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_accesskeys.go @@ -0,0 +1,14 @@ +package namespacesauthorizationrule + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessKeys struct { + AliasPrimaryConnectionString *string `json:"aliasPrimaryConnectionString,omitempty"` + AliasSecondaryConnectionString *string `json:"aliasSecondaryConnectionString,omitempty"` + KeyName *string `json:"keyName,omitempty"` + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + PrimaryKey *string `json:"primaryKey,omitempty"` + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + SecondaryKey *string `json:"secondaryKey,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_regenerateaccesskeyparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_regenerateaccesskeyparameters.go new file mode 100644 index 000000000000..ec4bc454a57a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_regenerateaccesskeyparameters.go @@ -0,0 +1,9 @@ +package namespacesauthorizationrule + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateAccessKeyParameters struct { + Key *string `json:"key,omitempty"` + KeyType KeyType `json:"keyType"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_sbauthorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_sbauthorizationrule.go new file mode 100644 index 000000000000..dc46cb0f367e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_sbauthorizationrule.go @@ -0,0 +1,16 @@ +package namespacesauthorizationrule + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBAuthorizationRule struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SBAuthorizationRuleProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_sbauthorizationruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_sbauthorizationruleproperties.go new file mode 100644 index 000000000000..ef02ce304561 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/model_sbauthorizationruleproperties.go @@ -0,0 +1,8 @@ +package namespacesauthorizationrule + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBAuthorizationRuleProperties struct { + Rights []AccessRights `json:"rights"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/predicates.go new file mode 100644 index 000000000000..a9141050f2a6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/predicates.go @@ -0,0 +1,24 @@ +package namespacesauthorizationrule + +type SBAuthorizationRuleOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p SBAuthorizationRuleOperationPredicate) Matches(input SBAuthorizationRule) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/version.go new file mode 100644 index 000000000000..885c529038e1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule/version.go @@ -0,0 +1,12 @@ +package namespacesauthorizationrule + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-06-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/namespacesauthorizationrule/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/README.md new file mode 100644 index 000000000000..0e4e9288f7e9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/README.md @@ -0,0 +1,90 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues` Documentation + +The `queues` SDK allows for interaction with the Azure Resource Manager Service `servicebus` (API Version `2021-06-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues" +``` + + +### Client Initialization + +```go +client := queues.NewQueuesClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `QueuesClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := queues.NewQueueID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "queueValue") + +payload := queues.SBQueue{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `QueuesClient.Delete` + +```go +ctx := context.TODO() +id := queues.NewQueueID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "queueValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `QueuesClient.Get` + +```go +ctx := context.TODO() +id := queues.NewQueueID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "queueValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `QueuesClient.ListByNamespace` + +```go +ctx := context.TODO() +id := queues.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +// alternatively `client.ListByNamespace(ctx, id, queues.DefaultListByNamespaceOperationOptions())` can be used to do batched pagination +items, err := client.ListByNamespaceComplete(ctx, id, queues.DefaultListByNamespaceOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/client.go new file mode 100644 index 000000000000..9f002f842f12 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/client.go @@ -0,0 +1,18 @@ +package queues + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type QueuesClient struct { + Client autorest.Client + baseUri string +} + +func NewQueuesClientWithBaseURI(endpoint string) QueuesClient { + return QueuesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/constants.go new file mode 100644 index 000000000000..a7102ca2f172 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/constants.go @@ -0,0 +1,55 @@ +package queues + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EntityStatus string + +const ( + EntityStatusActive EntityStatus = "Active" + EntityStatusCreating EntityStatus = "Creating" + EntityStatusDeleting EntityStatus = "Deleting" + EntityStatusDisabled EntityStatus = "Disabled" + EntityStatusReceiveDisabled EntityStatus = "ReceiveDisabled" + EntityStatusRenaming EntityStatus = "Renaming" + EntityStatusRestoring EntityStatus = "Restoring" + EntityStatusSendDisabled EntityStatus = "SendDisabled" + EntityStatusUnknown EntityStatus = "Unknown" +) + +func PossibleValuesForEntityStatus() []string { + return []string{ + string(EntityStatusActive), + string(EntityStatusCreating), + string(EntityStatusDeleting), + string(EntityStatusDisabled), + string(EntityStatusReceiveDisabled), + string(EntityStatusRenaming), + string(EntityStatusRestoring), + string(EntityStatusSendDisabled), + string(EntityStatusUnknown), + } +} + +func parseEntityStatus(input string) (*EntityStatus, error) { + vals := map[string]EntityStatus{ + "active": EntityStatusActive, + "creating": EntityStatusCreating, + "deleting": EntityStatusDeleting, + "disabled": EntityStatusDisabled, + "receivedisabled": EntityStatusReceiveDisabled, + "renaming": EntityStatusRenaming, + "restoring": EntityStatusRestoring, + "senddisabled": EntityStatusSendDisabled, + "unknown": EntityStatusUnknown, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EntityStatus(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/id_namespace.go new file mode 100644 index 000000000000..03c340b86d41 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/id_namespace.go @@ -0,0 +1,124 @@ +package queues + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/id_queue.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/id_queue.go new file mode 100644 index 000000000000..db105521f86f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/id_queue.go @@ -0,0 +1,137 @@ +package queues + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = QueueId{} + +// QueueId is a struct representing the Resource ID for a Queue +type QueueId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + QueueName string +} + +// NewQueueID returns a new QueueId struct +func NewQueueID(subscriptionId string, resourceGroupName string, namespaceName string, queueName string) QueueId { + return QueueId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + QueueName: queueName, + } +} + +// ParseQueueID parses 'input' into a QueueId +func ParseQueueID(input string) (*QueueId, error) { + parser := resourceids.NewParserFromResourceIdType(QueueId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := QueueId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.QueueName, ok = parsed.Parsed["queueName"]; !ok { + return nil, fmt.Errorf("the segment 'queueName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseQueueIDInsensitively parses 'input' case-insensitively into a QueueId +// note: this method should only be used for API response data and not user input +func ParseQueueIDInsensitively(input string) (*QueueId, error) { + parser := resourceids.NewParserFromResourceIdType(QueueId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := QueueId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.QueueName, ok = parsed.Parsed["queueName"]; !ok { + return nil, fmt.Errorf("the segment 'queueName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateQueueID checks that 'input' can be parsed as a Queue ID +func ValidateQueueID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseQueueID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Queue ID +func (id QueueId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/queues/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.QueueName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Queue ID +func (id QueueId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticQueues", "queues", "queues"), + resourceids.UserSpecifiedSegment("queueName", "queueValue"), + } +} + +// String returns a human-readable description of this Queue ID +func (id QueueId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Queue Name: %q", id.QueueName), + } + return fmt.Sprintf("Queue (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_createorupdate_autorest.go new file mode 100644 index 000000000000..7503be89cbd9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package queues + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *SBQueue +} + +// CreateOrUpdate ... +func (c QueuesClient) CreateOrUpdate(ctx context.Context, id QueueId, input SBQueue) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c QueuesClient) preparerForCreateOrUpdate(ctx context.Context, id QueueId, input SBQueue) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c QueuesClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_delete_autorest.go new file mode 100644 index 000000000000..ba7742cf4101 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_delete_autorest.go @@ -0,0 +1,65 @@ +package queues + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c QueuesClient) Delete(ctx context.Context, id QueueId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c QueuesClient) preparerForDelete(ctx context.Context, id QueueId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c QueuesClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_get_autorest.go new file mode 100644 index 000000000000..5f4b20ea427e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_get_autorest.go @@ -0,0 +1,67 @@ +package queues + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *SBQueue +} + +// Get ... +func (c QueuesClient) Get(ctx context.Context, id QueueId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c QueuesClient) preparerForGet(ctx context.Context, id QueueId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c QueuesClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_listbynamespace_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_listbynamespace_autorest.go new file mode 100644 index 000000000000..53be58663414 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/method_listbynamespace_autorest.go @@ -0,0 +1,220 @@ +package queues + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByNamespaceOperationResponse struct { + HttpResponse *http.Response + Model *[]SBQueue + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByNamespaceOperationResponse, error) +} + +type ListByNamespaceCompleteResult struct { + Items []SBQueue +} + +func (r ListByNamespaceOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByNamespaceOperationResponse) LoadMore(ctx context.Context) (resp ListByNamespaceOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type ListByNamespaceOperationOptions struct { + Skip *int64 + Top *int64 +} + +func DefaultListByNamespaceOperationOptions() ListByNamespaceOperationOptions { + return ListByNamespaceOperationOptions{} +} + +func (o ListByNamespaceOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o ListByNamespaceOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Skip != nil { + out["$skip"] = *o.Skip + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// ListByNamespace ... +func (c QueuesClient) ListByNamespace(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions) (resp ListByNamespaceOperationResponse, err error) { + req, err := c.preparerForListByNamespace(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "ListByNamespace", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "ListByNamespace", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByNamespace(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "ListByNamespace", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByNamespaceComplete retrieves all of the results into a single object +func (c QueuesClient) ListByNamespaceComplete(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions) (ListByNamespaceCompleteResult, error) { + return c.ListByNamespaceCompleteMatchingPredicate(ctx, id, options, SBQueueOperationPredicate{}) +} + +// ListByNamespaceCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c QueuesClient) ListByNamespaceCompleteMatchingPredicate(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions, predicate SBQueueOperationPredicate) (resp ListByNamespaceCompleteResult, err error) { + items := make([]SBQueue, 0) + + page, err := c.ListByNamespace(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByNamespaceCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByNamespace prepares the ListByNamespace request. +func (c QueuesClient) preparerForListByNamespace(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/queues", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByNamespaceWithNextLink prepares the ListByNamespace request with the given nextLink token. +func (c QueuesClient) preparerForListByNamespaceWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByNamespace handles the response to the ListByNamespace request. The method always +// closes the http.Response Body. +func (c QueuesClient) responderForListByNamespace(resp *http.Response) (result ListByNamespaceOperationResponse, err error) { + type page struct { + Values []SBQueue `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByNamespaceOperationResponse, err error) { + req, err := c.preparerForListByNamespaceWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "ListByNamespace", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "ListByNamespace", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByNamespace(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queues.QueuesClient", "ListByNamespace", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_messagecountdetails.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_messagecountdetails.go new file mode 100644 index 000000000000..9bd16f13f687 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_messagecountdetails.go @@ -0,0 +1,12 @@ +package queues + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type MessageCountDetails struct { + ActiveMessageCount *int64 `json:"activeMessageCount,omitempty"` + DeadLetterMessageCount *int64 `json:"deadLetterMessageCount,omitempty"` + ScheduledMessageCount *int64 `json:"scheduledMessageCount,omitempty"` + TransferDeadLetterMessageCount *int64 `json:"transferDeadLetterMessageCount,omitempty"` + TransferMessageCount *int64 `json:"transferMessageCount,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_sbqueue.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_sbqueue.go new file mode 100644 index 000000000000..9a8f302b7e8f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_sbqueue.go @@ -0,0 +1,16 @@ +package queues + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBQueue struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SBQueueProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_sbqueueproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_sbqueueproperties.go new file mode 100644 index 000000000000..ed1ff71a7fc8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/model_sbqueueproperties.go @@ -0,0 +1,71 @@ +package queues + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBQueueProperties struct { + AccessedAt *string `json:"accessedAt,omitempty"` + AutoDeleteOnIdle *string `json:"autoDeleteOnIdle,omitempty"` + CountDetails *MessageCountDetails `json:"countDetails,omitempty"` + CreatedAt *string `json:"createdAt,omitempty"` + DeadLetteringOnMessageExpiration *bool `json:"deadLetteringOnMessageExpiration,omitempty"` + DefaultMessageTimeToLive *string `json:"defaultMessageTimeToLive,omitempty"` + DuplicateDetectionHistoryTimeWindow *string `json:"duplicateDetectionHistoryTimeWindow,omitempty"` + EnableBatchedOperations *bool `json:"enableBatchedOperations,omitempty"` + EnableExpress *bool `json:"enableExpress,omitempty"` + EnablePartitioning *bool `json:"enablePartitioning,omitempty"` + ForwardDeadLetteredMessagesTo *string `json:"forwardDeadLetteredMessagesTo,omitempty"` + ForwardTo *string `json:"forwardTo,omitempty"` + LockDuration *string `json:"lockDuration,omitempty"` + MaxDeliveryCount *int64 `json:"maxDeliveryCount,omitempty"` + MaxMessageSizeInKilobytes *int64 `json:"maxMessageSizeInKilobytes,omitempty"` + MaxSizeInMegabytes *int64 `json:"maxSizeInMegabytes,omitempty"` + MessageCount *int64 `json:"messageCount,omitempty"` + RequiresDuplicateDetection *bool `json:"requiresDuplicateDetection,omitempty"` + RequiresSession *bool `json:"requiresSession,omitempty"` + SizeInBytes *int64 `json:"sizeInBytes,omitempty"` + Status *EntityStatus `json:"status,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` +} + +func (o *SBQueueProperties) GetAccessedAtAsTime() (*time.Time, error) { + if o.AccessedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.AccessedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBQueueProperties) SetAccessedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.AccessedAt = &formatted +} + +func (o *SBQueueProperties) GetCreatedAtAsTime() (*time.Time, error) { + if o.CreatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBQueueProperties) SetCreatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedAt = &formatted +} + +func (o *SBQueueProperties) GetUpdatedAtAsTime() (*time.Time, error) { + if o.UpdatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.UpdatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBQueueProperties) SetUpdatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.UpdatedAt = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/predicates.go new file mode 100644 index 000000000000..0a1854098288 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/predicates.go @@ -0,0 +1,24 @@ +package queues + +type SBQueueOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p SBQueueOperationPredicate) Matches(input SBQueue) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/version.go new file mode 100644 index 000000000000..49e5f391bc33 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues/version.go @@ -0,0 +1,12 @@ +package queues + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-06-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/queues/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/README.md new file mode 100644 index 000000000000..5f09a842c30d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/README.md @@ -0,0 +1,127 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule` Documentation + +The `queuesauthorizationrule` SDK allows for interaction with the Azure Resource Manager Service `servicebus` (API Version `2021-06-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule" +``` + + +### Client Initialization + +```go +client := queuesauthorizationrule.NewQueuesAuthorizationRuleClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `QueuesAuthorizationRuleClient.QueuesCreateOrUpdateAuthorizationRule` + +```go +ctx := context.TODO() +id := queuesauthorizationrule.NewQueueAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "queueValue", "authorizationRuleValue") + +payload := queuesauthorizationrule.SBAuthorizationRule{ + // ... +} + + +read, err := client.QueuesCreateOrUpdateAuthorizationRule(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `QueuesAuthorizationRuleClient.QueuesDeleteAuthorizationRule` + +```go +ctx := context.TODO() +id := queuesauthorizationrule.NewQueueAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "queueValue", "authorizationRuleValue") + +read, err := client.QueuesDeleteAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `QueuesAuthorizationRuleClient.QueuesGetAuthorizationRule` + +```go +ctx := context.TODO() +id := queuesauthorizationrule.NewQueueAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "queueValue", "authorizationRuleValue") + +read, err := client.QueuesGetAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `QueuesAuthorizationRuleClient.QueuesListAuthorizationRules` + +```go +ctx := context.TODO() +id := queuesauthorizationrule.NewQueueID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "queueValue") + +// alternatively `client.QueuesListAuthorizationRules(ctx, id)` can be used to do batched pagination +items, err := client.QueuesListAuthorizationRulesComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `QueuesAuthorizationRuleClient.QueuesListKeys` + +```go +ctx := context.TODO() +id := queuesauthorizationrule.NewQueueAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "queueValue", "authorizationRuleValue") + +read, err := client.QueuesListKeys(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `QueuesAuthorizationRuleClient.QueuesRegenerateKeys` + +```go +ctx := context.TODO() +id := queuesauthorizationrule.NewQueueAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "queueValue", "authorizationRuleValue") + +payload := queuesauthorizationrule.RegenerateAccessKeyParameters{ + // ... +} + + +read, err := client.QueuesRegenerateKeys(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/client.go new file mode 100644 index 000000000000..2f12c809683b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/client.go @@ -0,0 +1,18 @@ +package queuesauthorizationrule + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type QueuesAuthorizationRuleClient struct { + Client autorest.Client + baseUri string +} + +func NewQueuesAuthorizationRuleClientWithBaseURI(endpoint string) QueuesAuthorizationRuleClient { + return QueuesAuthorizationRuleClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/constants.go new file mode 100644 index 000000000000..376d0d9c7719 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/constants.go @@ -0,0 +1,65 @@ +package queuesauthorizationrule + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessRights string + +const ( + AccessRightsListen AccessRights = "Listen" + AccessRightsManage AccessRights = "Manage" + AccessRightsSend AccessRights = "Send" +) + +func PossibleValuesForAccessRights() []string { + return []string{ + string(AccessRightsListen), + string(AccessRightsManage), + string(AccessRightsSend), + } +} + +func parseAccessRights(input string) (*AccessRights, error) { + vals := map[string]AccessRights{ + "listen": AccessRightsListen, + "manage": AccessRightsManage, + "send": AccessRightsSend, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AccessRights(input) + return &out, nil +} + +type KeyType string + +const ( + KeyTypePrimaryKey KeyType = "PrimaryKey" + KeyTypeSecondaryKey KeyType = "SecondaryKey" +) + +func PossibleValuesForKeyType() []string { + return []string{ + string(KeyTypePrimaryKey), + string(KeyTypeSecondaryKey), + } +} + +func parseKeyType(input string) (*KeyType, error) { + vals := map[string]KeyType{ + "primarykey": KeyTypePrimaryKey, + "secondarykey": KeyTypeSecondaryKey, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeyType(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/id_queue.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/id_queue.go new file mode 100644 index 000000000000..349e72ef938a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/id_queue.go @@ -0,0 +1,137 @@ +package queuesauthorizationrule + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = QueueId{} + +// QueueId is a struct representing the Resource ID for a Queue +type QueueId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + QueueName string +} + +// NewQueueID returns a new QueueId struct +func NewQueueID(subscriptionId string, resourceGroupName string, namespaceName string, queueName string) QueueId { + return QueueId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + QueueName: queueName, + } +} + +// ParseQueueID parses 'input' into a QueueId +func ParseQueueID(input string) (*QueueId, error) { + parser := resourceids.NewParserFromResourceIdType(QueueId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := QueueId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.QueueName, ok = parsed.Parsed["queueName"]; !ok { + return nil, fmt.Errorf("the segment 'queueName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseQueueIDInsensitively parses 'input' case-insensitively into a QueueId +// note: this method should only be used for API response data and not user input +func ParseQueueIDInsensitively(input string) (*QueueId, error) { + parser := resourceids.NewParserFromResourceIdType(QueueId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := QueueId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.QueueName, ok = parsed.Parsed["queueName"]; !ok { + return nil, fmt.Errorf("the segment 'queueName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateQueueID checks that 'input' can be parsed as a Queue ID +func ValidateQueueID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseQueueID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Queue ID +func (id QueueId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/queues/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.QueueName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Queue ID +func (id QueueId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticQueues", "queues", "queues"), + resourceids.UserSpecifiedSegment("queueName", "queueValue"), + } +} + +// String returns a human-readable description of this Queue ID +func (id QueueId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Queue Name: %q", id.QueueName), + } + return fmt.Sprintf("Queue (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/id_queueauthorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/id_queueauthorizationrule.go new file mode 100644 index 000000000000..34fc91ea4a63 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/id_queueauthorizationrule.go @@ -0,0 +1,150 @@ +package queuesauthorizationrule + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = QueueAuthorizationRuleId{} + +// QueueAuthorizationRuleId is a struct representing the Resource ID for a Queue Authorization Rule +type QueueAuthorizationRuleId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + QueueName string + AuthorizationRuleName string +} + +// NewQueueAuthorizationRuleID returns a new QueueAuthorizationRuleId struct +func NewQueueAuthorizationRuleID(subscriptionId string, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) QueueAuthorizationRuleId { + return QueueAuthorizationRuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + QueueName: queueName, + AuthorizationRuleName: authorizationRuleName, + } +} + +// ParseQueueAuthorizationRuleID parses 'input' into a QueueAuthorizationRuleId +func ParseQueueAuthorizationRuleID(input string) (*QueueAuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(QueueAuthorizationRuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := QueueAuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.QueueName, ok = parsed.Parsed["queueName"]; !ok { + return nil, fmt.Errorf("the segment 'queueName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseQueueAuthorizationRuleIDInsensitively parses 'input' case-insensitively into a QueueAuthorizationRuleId +// note: this method should only be used for API response data and not user input +func ParseQueueAuthorizationRuleIDInsensitively(input string) (*QueueAuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(QueueAuthorizationRuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := QueueAuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.QueueName, ok = parsed.Parsed["queueName"]; !ok { + return nil, fmt.Errorf("the segment 'queueName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateQueueAuthorizationRuleID checks that 'input' can be parsed as a Queue Authorization Rule ID +func ValidateQueueAuthorizationRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseQueueAuthorizationRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Queue Authorization Rule ID +func (id QueueAuthorizationRuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/queues/%s/authorizationRules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.QueueName, id.AuthorizationRuleName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Queue Authorization Rule ID +func (id QueueAuthorizationRuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticQueues", "queues", "queues"), + resourceids.UserSpecifiedSegment("queueName", "queueValue"), + resourceids.StaticSegment("staticAuthorizationRules", "authorizationRules", "authorizationRules"), + resourceids.UserSpecifiedSegment("authorizationRuleName", "authorizationRuleValue"), + } +} + +// String returns a human-readable description of this Queue Authorization Rule ID +func (id QueueAuthorizationRuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Queue Name: %q", id.QueueName), + fmt.Sprintf("Authorization Rule Name: %q", id.AuthorizationRuleName), + } + return fmt.Sprintf("Queue Authorization Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuescreateorupdateauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuescreateorupdateauthorizationrule_autorest.go new file mode 100644 index 000000000000..a76a6e5ba0bf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuescreateorupdateauthorizationrule_autorest.go @@ -0,0 +1,68 @@ +package queuesauthorizationrule + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type QueuesCreateOrUpdateAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *SBAuthorizationRule +} + +// QueuesCreateOrUpdateAuthorizationRule ... +func (c QueuesAuthorizationRuleClient) QueuesCreateOrUpdateAuthorizationRule(ctx context.Context, id QueueAuthorizationRuleId, input SBAuthorizationRule) (result QueuesCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForQueuesCreateOrUpdateAuthorizationRule(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesCreateOrUpdateAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForQueuesCreateOrUpdateAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForQueuesCreateOrUpdateAuthorizationRule prepares the QueuesCreateOrUpdateAuthorizationRule request. +func (c QueuesAuthorizationRuleClient) preparerForQueuesCreateOrUpdateAuthorizationRule(ctx context.Context, id QueueAuthorizationRuleId, input SBAuthorizationRule) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForQueuesCreateOrUpdateAuthorizationRule handles the response to the QueuesCreateOrUpdateAuthorizationRule request. The method always +// closes the http.Response Body. +func (c QueuesAuthorizationRuleClient) responderForQueuesCreateOrUpdateAuthorizationRule(resp *http.Response) (result QueuesCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesdeleteauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesdeleteauthorizationrule_autorest.go new file mode 100644 index 000000000000..46cbf6b6d0ce --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesdeleteauthorizationrule_autorest.go @@ -0,0 +1,65 @@ +package queuesauthorizationrule + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type QueuesDeleteAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response +} + +// QueuesDeleteAuthorizationRule ... +func (c QueuesAuthorizationRuleClient) QueuesDeleteAuthorizationRule(ctx context.Context, id QueueAuthorizationRuleId) (result QueuesDeleteAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForQueuesDeleteAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesDeleteAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesDeleteAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForQueuesDeleteAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesDeleteAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForQueuesDeleteAuthorizationRule prepares the QueuesDeleteAuthorizationRule request. +func (c QueuesAuthorizationRuleClient) preparerForQueuesDeleteAuthorizationRule(ctx context.Context, id QueueAuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForQueuesDeleteAuthorizationRule handles the response to the QueuesDeleteAuthorizationRule request. The method always +// closes the http.Response Body. +func (c QueuesAuthorizationRuleClient) responderForQueuesDeleteAuthorizationRule(resp *http.Response) (result QueuesDeleteAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesgetauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesgetauthorizationrule_autorest.go new file mode 100644 index 000000000000..a5af12fc8df3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesgetauthorizationrule_autorest.go @@ -0,0 +1,67 @@ +package queuesauthorizationrule + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type QueuesGetAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *SBAuthorizationRule +} + +// QueuesGetAuthorizationRule ... +func (c QueuesAuthorizationRuleClient) QueuesGetAuthorizationRule(ctx context.Context, id QueueAuthorizationRuleId) (result QueuesGetAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForQueuesGetAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesGetAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesGetAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForQueuesGetAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesGetAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForQueuesGetAuthorizationRule prepares the QueuesGetAuthorizationRule request. +func (c QueuesAuthorizationRuleClient) preparerForQueuesGetAuthorizationRule(ctx context.Context, id QueueAuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForQueuesGetAuthorizationRule handles the response to the QueuesGetAuthorizationRule request. The method always +// closes the http.Response Body. +func (c QueuesAuthorizationRuleClient) responderForQueuesGetAuthorizationRule(resp *http.Response) (result QueuesGetAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queueslistauthorizationrules_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queueslistauthorizationrules_autorest.go new file mode 100644 index 000000000000..82e7db8815eb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queueslistauthorizationrules_autorest.go @@ -0,0 +1,186 @@ +package queuesauthorizationrule + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type QueuesListAuthorizationRulesOperationResponse struct { + HttpResponse *http.Response + Model *[]SBAuthorizationRule + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (QueuesListAuthorizationRulesOperationResponse, error) +} + +type QueuesListAuthorizationRulesCompleteResult struct { + Items []SBAuthorizationRule +} + +func (r QueuesListAuthorizationRulesOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r QueuesListAuthorizationRulesOperationResponse) LoadMore(ctx context.Context) (resp QueuesListAuthorizationRulesOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// QueuesListAuthorizationRules ... +func (c QueuesAuthorizationRuleClient) QueuesListAuthorizationRules(ctx context.Context, id QueueId) (resp QueuesListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForQueuesListAuthorizationRules(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesListAuthorizationRules", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForQueuesListAuthorizationRules(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesListAuthorizationRules", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// QueuesListAuthorizationRulesComplete retrieves all of the results into a single object +func (c QueuesAuthorizationRuleClient) QueuesListAuthorizationRulesComplete(ctx context.Context, id QueueId) (QueuesListAuthorizationRulesCompleteResult, error) { + return c.QueuesListAuthorizationRulesCompleteMatchingPredicate(ctx, id, SBAuthorizationRuleOperationPredicate{}) +} + +// QueuesListAuthorizationRulesCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c QueuesAuthorizationRuleClient) QueuesListAuthorizationRulesCompleteMatchingPredicate(ctx context.Context, id QueueId, predicate SBAuthorizationRuleOperationPredicate) (resp QueuesListAuthorizationRulesCompleteResult, err error) { + items := make([]SBAuthorizationRule, 0) + + page, err := c.QueuesListAuthorizationRules(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := QueuesListAuthorizationRulesCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForQueuesListAuthorizationRules prepares the QueuesListAuthorizationRules request. +func (c QueuesAuthorizationRuleClient) preparerForQueuesListAuthorizationRules(ctx context.Context, id QueueId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/authorizationRules", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForQueuesListAuthorizationRulesWithNextLink prepares the QueuesListAuthorizationRules request with the given nextLink token. +func (c QueuesAuthorizationRuleClient) preparerForQueuesListAuthorizationRulesWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForQueuesListAuthorizationRules handles the response to the QueuesListAuthorizationRules request. The method always +// closes the http.Response Body. +func (c QueuesAuthorizationRuleClient) responderForQueuesListAuthorizationRules(resp *http.Response) (result QueuesListAuthorizationRulesOperationResponse, err error) { + type page struct { + Values []SBAuthorizationRule `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result QueuesListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForQueuesListAuthorizationRulesWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesListAuthorizationRules", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesListAuthorizationRules", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForQueuesListAuthorizationRules(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesListAuthorizationRules", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queueslistkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queueslistkeys_autorest.go new file mode 100644 index 000000000000..511eafdbdbe4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queueslistkeys_autorest.go @@ -0,0 +1,68 @@ +package queuesauthorizationrule + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type QueuesListKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// QueuesListKeys ... +func (c QueuesAuthorizationRuleClient) QueuesListKeys(ctx context.Context, id QueueAuthorizationRuleId) (result QueuesListKeysOperationResponse, err error) { + req, err := c.preparerForQueuesListKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesListKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesListKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForQueuesListKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesListKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForQueuesListKeys prepares the QueuesListKeys request. +func (c QueuesAuthorizationRuleClient) preparerForQueuesListKeys(ctx context.Context, id QueueAuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForQueuesListKeys handles the response to the QueuesListKeys request. The method always +// closes the http.Response Body. +func (c QueuesAuthorizationRuleClient) responderForQueuesListKeys(resp *http.Response) (result QueuesListKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesregeneratekeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesregeneratekeys_autorest.go new file mode 100644 index 000000000000..4bea7e0efe4b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/method_queuesregeneratekeys_autorest.go @@ -0,0 +1,69 @@ +package queuesauthorizationrule + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type QueuesRegenerateKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// QueuesRegenerateKeys ... +func (c QueuesAuthorizationRuleClient) QueuesRegenerateKeys(ctx context.Context, id QueueAuthorizationRuleId, input RegenerateAccessKeyParameters) (result QueuesRegenerateKeysOperationResponse, err error) { + req, err := c.preparerForQueuesRegenerateKeys(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesRegenerateKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesRegenerateKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForQueuesRegenerateKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "queuesauthorizationrule.QueuesAuthorizationRuleClient", "QueuesRegenerateKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForQueuesRegenerateKeys prepares the QueuesRegenerateKeys request. +func (c QueuesAuthorizationRuleClient) preparerForQueuesRegenerateKeys(ctx context.Context, id QueueAuthorizationRuleId, input RegenerateAccessKeyParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/regenerateKeys", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForQueuesRegenerateKeys handles the response to the QueuesRegenerateKeys request. The method always +// closes the http.Response Body. +func (c QueuesAuthorizationRuleClient) responderForQueuesRegenerateKeys(resp *http.Response) (result QueuesRegenerateKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_accesskeys.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_accesskeys.go new file mode 100644 index 000000000000..6483a26ef744 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_accesskeys.go @@ -0,0 +1,14 @@ +package queuesauthorizationrule + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessKeys struct { + AliasPrimaryConnectionString *string `json:"aliasPrimaryConnectionString,omitempty"` + AliasSecondaryConnectionString *string `json:"aliasSecondaryConnectionString,omitempty"` + KeyName *string `json:"keyName,omitempty"` + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + PrimaryKey *string `json:"primaryKey,omitempty"` + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + SecondaryKey *string `json:"secondaryKey,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_regenerateaccesskeyparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_regenerateaccesskeyparameters.go new file mode 100644 index 000000000000..b6a32491737c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_regenerateaccesskeyparameters.go @@ -0,0 +1,9 @@ +package queuesauthorizationrule + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateAccessKeyParameters struct { + Key *string `json:"key,omitempty"` + KeyType KeyType `json:"keyType"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_sbauthorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_sbauthorizationrule.go new file mode 100644 index 000000000000..13f457c78149 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_sbauthorizationrule.go @@ -0,0 +1,16 @@ +package queuesauthorizationrule + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBAuthorizationRule struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SBAuthorizationRuleProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_sbauthorizationruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_sbauthorizationruleproperties.go new file mode 100644 index 000000000000..c4ccb568d3fd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/model_sbauthorizationruleproperties.go @@ -0,0 +1,8 @@ +package queuesauthorizationrule + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBAuthorizationRuleProperties struct { + Rights []AccessRights `json:"rights"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/predicates.go new file mode 100644 index 000000000000..721dce865ede --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/predicates.go @@ -0,0 +1,24 @@ +package queuesauthorizationrule + +type SBAuthorizationRuleOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p SBAuthorizationRuleOperationPredicate) Matches(input SBAuthorizationRule) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/version.go new file mode 100644 index 000000000000..65270c408ffb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule/version.go @@ -0,0 +1,12 @@ +package queuesauthorizationrule + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-06-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/queuesauthorizationrule/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/README.md new file mode 100644 index 000000000000..80162617b4fe --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/README.md @@ -0,0 +1,74 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules` Documentation + +The `rules` SDK allows for interaction with the Azure Resource Manager Service `servicebus` (API Version `2021-06-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules" +``` + + +### Client Initialization + +```go +client := rules.NewRulesClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `RulesClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := rules.NewRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "subscriptionValue", "ruleValue") + +payload := rules.Rule{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `RulesClient.Delete` + +```go +ctx := context.TODO() +id := rules.NewRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "subscriptionValue", "ruleValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `RulesClient.ListBySubscriptions` + +```go +ctx := context.TODO() +id := rules.NewSubscriptions2ID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "subscriptionValue") + +// alternatively `client.ListBySubscriptions(ctx, id, rules.DefaultListBySubscriptionsOperationOptions())` can be used to do batched pagination +items, err := client.ListBySubscriptionsComplete(ctx, id, rules.DefaultListBySubscriptionsOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/client.go new file mode 100644 index 000000000000..7e1e300eef3c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/client.go @@ -0,0 +1,18 @@ +package rules + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RulesClient struct { + Client autorest.Client + baseUri string +} + +func NewRulesClientWithBaseURI(endpoint string) RulesClient { + return RulesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/constants.go new file mode 100644 index 000000000000..06236708fc2d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/constants.go @@ -0,0 +1,34 @@ +package rules + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type FilterType string + +const ( + FilterTypeCorrelationFilter FilterType = "CorrelationFilter" + FilterTypeSqlFilter FilterType = "SqlFilter" +) + +func PossibleValuesForFilterType() []string { + return []string{ + string(FilterTypeCorrelationFilter), + string(FilterTypeSqlFilter), + } +} + +func parseFilterType(input string) (*FilterType, error) { + vals := map[string]FilterType{ + "correlationfilter": FilterTypeCorrelationFilter, + "sqlfilter": FilterTypeSqlFilter, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := FilterType(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/id_rule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/id_rule.go new file mode 100644 index 000000000000..0b106b550949 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/id_rule.go @@ -0,0 +1,163 @@ +package rules + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = RuleId{} + +// RuleId is a struct representing the Resource ID for a Rule +type RuleId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + TopicName string + SubscriptionName string + RuleName string +} + +// NewRuleID returns a new RuleId struct +func NewRuleID(subscriptionId string, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, ruleName string) RuleId { + return RuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + TopicName: topicName, + SubscriptionName: subscriptionName, + RuleName: ruleName, + } +} + +// ParseRuleID parses 'input' into a RuleId +func ParseRuleID(input string) (*RuleId, error) { + parser := resourceids.NewParserFromResourceIdType(RuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := RuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.SubscriptionName, ok = parsed.Parsed["subscriptionName"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionName' was not found in the resource id %q", input) + } + + if id.RuleName, ok = parsed.Parsed["ruleName"]; !ok { + return nil, fmt.Errorf("the segment 'ruleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseRuleIDInsensitively parses 'input' case-insensitively into a RuleId +// note: this method should only be used for API response data and not user input +func ParseRuleIDInsensitively(input string) (*RuleId, error) { + parser := resourceids.NewParserFromResourceIdType(RuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := RuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.SubscriptionName, ok = parsed.Parsed["subscriptionName"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionName' was not found in the resource id %q", input) + } + + if id.RuleName, ok = parsed.Parsed["ruleName"]; !ok { + return nil, fmt.Errorf("the segment 'ruleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateRuleID checks that 'input' can be parsed as a Rule ID +func ValidateRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Rule ID +func (id RuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/topics/%s/subscriptions/%s/rules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName, id.SubscriptionName, id.RuleName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Rule ID +func (id RuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticTopics", "topics", "topics"), + resourceids.UserSpecifiedSegment("topicName", "topicValue"), + resourceids.StaticSegment("staticSubscriptions2", "subscriptions", "subscriptions"), + resourceids.UserSpecifiedSegment("subscriptionName", "subscriptionValue"), + resourceids.StaticSegment("staticRules", "rules", "rules"), + resourceids.UserSpecifiedSegment("ruleName", "ruleValue"), + } +} + +// String returns a human-readable description of this Rule ID +func (id RuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Topic Name: %q", id.TopicName), + fmt.Sprintf("Subscription Name: %q", id.SubscriptionName), + fmt.Sprintf("Rule Name: %q", id.RuleName), + } + return fmt.Sprintf("Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/id_subscriptions2.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/id_subscriptions2.go new file mode 100644 index 000000000000..827ea8781694 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/id_subscriptions2.go @@ -0,0 +1,150 @@ +package rules + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = Subscriptions2Id{} + +// Subscriptions2Id is a struct representing the Resource ID for a Subscriptions 2 +type Subscriptions2Id struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + TopicName string + SubscriptionName string +} + +// NewSubscriptions2ID returns a new Subscriptions2Id struct +func NewSubscriptions2ID(subscriptionId string, resourceGroupName string, namespaceName string, topicName string, subscriptionName string) Subscriptions2Id { + return Subscriptions2Id{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + TopicName: topicName, + SubscriptionName: subscriptionName, + } +} + +// ParseSubscriptions2ID parses 'input' into a Subscriptions2Id +func ParseSubscriptions2ID(input string) (*Subscriptions2Id, error) { + parser := resourceids.NewParserFromResourceIdType(Subscriptions2Id{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := Subscriptions2Id{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.SubscriptionName, ok = parsed.Parsed["subscriptionName"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseSubscriptions2IDInsensitively parses 'input' case-insensitively into a Subscriptions2Id +// note: this method should only be used for API response data and not user input +func ParseSubscriptions2IDInsensitively(input string) (*Subscriptions2Id, error) { + parser := resourceids.NewParserFromResourceIdType(Subscriptions2Id{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := Subscriptions2Id{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.SubscriptionName, ok = parsed.Parsed["subscriptionName"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateSubscriptions2ID checks that 'input' can be parsed as a Subscriptions 2 ID +func ValidateSubscriptions2ID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseSubscriptions2ID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Subscriptions 2 ID +func (id Subscriptions2Id) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/topics/%s/subscriptions/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName, id.SubscriptionName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Subscriptions 2 ID +func (id Subscriptions2Id) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticTopics", "topics", "topics"), + resourceids.UserSpecifiedSegment("topicName", "topicValue"), + resourceids.StaticSegment("staticSubscriptions2", "subscriptions", "subscriptions"), + resourceids.UserSpecifiedSegment("subscriptionName", "subscriptionValue"), + } +} + +// String returns a human-readable description of this Subscriptions 2 ID +func (id Subscriptions2Id) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Topic Name: %q", id.TopicName), + fmt.Sprintf("Subscription Name: %q", id.SubscriptionName), + } + return fmt.Sprintf("Subscriptions 2 (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_createorupdate_autorest.go new file mode 100644 index 000000000000..7e69a145d81e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package rules + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *Rule +} + +// CreateOrUpdate ... +func (c RulesClient) CreateOrUpdate(ctx context.Context, id RuleId, input Rule) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c RulesClient) preparerForCreateOrUpdate(ctx context.Context, id RuleId, input Rule) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c RulesClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_delete_autorest.go new file mode 100644 index 000000000000..cd3d2426af6f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_delete_autorest.go @@ -0,0 +1,65 @@ +package rules + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c RulesClient) Delete(ctx context.Context, id RuleId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c RulesClient) preparerForDelete(ctx context.Context, id RuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c RulesClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_listbysubscriptions_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_listbysubscriptions_autorest.go new file mode 100644 index 000000000000..57c918acc5f7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/method_listbysubscriptions_autorest.go @@ -0,0 +1,220 @@ +package rules + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListBySubscriptionsOperationResponse struct { + HttpResponse *http.Response + Model *[]Rule + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListBySubscriptionsOperationResponse, error) +} + +type ListBySubscriptionsCompleteResult struct { + Items []Rule +} + +func (r ListBySubscriptionsOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListBySubscriptionsOperationResponse) LoadMore(ctx context.Context) (resp ListBySubscriptionsOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type ListBySubscriptionsOperationOptions struct { + Skip *int64 + Top *int64 +} + +func DefaultListBySubscriptionsOperationOptions() ListBySubscriptionsOperationOptions { + return ListBySubscriptionsOperationOptions{} +} + +func (o ListBySubscriptionsOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o ListBySubscriptionsOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Skip != nil { + out["$skip"] = *o.Skip + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// ListBySubscriptions ... +func (c RulesClient) ListBySubscriptions(ctx context.Context, id Subscriptions2Id, options ListBySubscriptionsOperationOptions) (resp ListBySubscriptionsOperationResponse, err error) { + req, err := c.preparerForListBySubscriptions(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "ListBySubscriptions", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "ListBySubscriptions", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListBySubscriptions(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "ListBySubscriptions", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListBySubscriptionsComplete retrieves all of the results into a single object +func (c RulesClient) ListBySubscriptionsComplete(ctx context.Context, id Subscriptions2Id, options ListBySubscriptionsOperationOptions) (ListBySubscriptionsCompleteResult, error) { + return c.ListBySubscriptionsCompleteMatchingPredicate(ctx, id, options, RuleOperationPredicate{}) +} + +// ListBySubscriptionsCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c RulesClient) ListBySubscriptionsCompleteMatchingPredicate(ctx context.Context, id Subscriptions2Id, options ListBySubscriptionsOperationOptions, predicate RuleOperationPredicate) (resp ListBySubscriptionsCompleteResult, err error) { + items := make([]Rule, 0) + + page, err := c.ListBySubscriptions(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListBySubscriptionsCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListBySubscriptions prepares the ListBySubscriptions request. +func (c RulesClient) preparerForListBySubscriptions(ctx context.Context, id Subscriptions2Id, options ListBySubscriptionsOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/rules", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListBySubscriptionsWithNextLink prepares the ListBySubscriptions request with the given nextLink token. +func (c RulesClient) preparerForListBySubscriptionsWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListBySubscriptions handles the response to the ListBySubscriptions request. The method always +// closes the http.Response Body. +func (c RulesClient) responderForListBySubscriptions(resp *http.Response) (result ListBySubscriptionsOperationResponse, err error) { + type page struct { + Values []Rule `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListBySubscriptionsOperationResponse, err error) { + req, err := c.preparerForListBySubscriptionsWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "ListBySubscriptions", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "ListBySubscriptions", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListBySubscriptions(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "rules.RulesClient", "ListBySubscriptions", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_action.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_action.go new file mode 100644 index 000000000000..5583dfbfe784 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_action.go @@ -0,0 +1,10 @@ +package rules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Action struct { + CompatibilityLevel *int64 `json:"compatibilityLevel,omitempty"` + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` + SqlExpression *string `json:"sqlExpression,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_correlationfilter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_correlationfilter.go new file mode 100644 index 000000000000..a2daf0699687 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_correlationfilter.go @@ -0,0 +1,17 @@ +package rules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CorrelationFilter struct { + ContentType *string `json:"contentType,omitempty"` + CorrelationId *string `json:"correlationId,omitempty"` + Label *string `json:"label,omitempty"` + MessageId *string `json:"messageId,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` + ReplyTo *string `json:"replyTo,omitempty"` + ReplyToSessionId *string `json:"replyToSessionId,omitempty"` + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` + SessionId *string `json:"sessionId,omitempty"` + To *string `json:"to,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_rule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_rule.go new file mode 100644 index 000000000000..7c81240b66ea --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_rule.go @@ -0,0 +1,16 @@ +package rules + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Rule struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *Ruleproperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_ruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_ruleproperties.go new file mode 100644 index 000000000000..96bf533f35fb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_ruleproperties.go @@ -0,0 +1,11 @@ +package rules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Ruleproperties struct { + Action *Action `json:"action,omitempty"` + CorrelationFilter *CorrelationFilter `json:"correlationFilter,omitempty"` + FilterType *FilterType `json:"filterType,omitempty"` + SqlFilter *SqlFilter `json:"sqlFilter,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_sqlfilter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_sqlfilter.go new file mode 100644 index 000000000000..fc16bab7c6ae --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/model_sqlfilter.go @@ -0,0 +1,10 @@ +package rules + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SqlFilter struct { + CompatibilityLevel *int64 `json:"compatibilityLevel,omitempty"` + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` + SqlExpression *string `json:"sqlExpression,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/predicates.go new file mode 100644 index 000000000000..c9b9b4dc5d6f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/predicates.go @@ -0,0 +1,24 @@ +package rules + +type RuleOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p RuleOperationPredicate) Matches(input Rule) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/version.go new file mode 100644 index 000000000000..e9a07c4c0584 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules/version.go @@ -0,0 +1,12 @@ +package rules + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-06-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/rules/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/README.md new file mode 100644 index 000000000000..08287c5e5dc4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/README.md @@ -0,0 +1,106 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions` Documentation + +The `subscriptions` SDK allows for interaction with the Azure Resource Manager Service `servicebus` (API Version `2021-06-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions" +``` + + +### Client Initialization + +```go +client := subscriptions.NewSubscriptionsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `SubscriptionsClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := subscriptions.NewSubscriptions2ID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "subscriptionValue") + +payload := subscriptions.SBSubscription{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SubscriptionsClient.Delete` + +```go +ctx := context.TODO() +id := subscriptions.NewSubscriptions2ID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "subscriptionValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SubscriptionsClient.Get` + +```go +ctx := context.TODO() +id := subscriptions.NewSubscriptions2ID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "subscriptionValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SubscriptionsClient.ListByTopic` + +```go +ctx := context.TODO() +id := subscriptions.NewTopicID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue") + +// alternatively `client.ListByTopic(ctx, id, subscriptions.DefaultListByTopicOperationOptions())` can be used to do batched pagination +items, err := client.ListByTopicComplete(ctx, id, subscriptions.DefaultListByTopicOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SubscriptionsClient.RulesGet` + +```go +ctx := context.TODO() +id := subscriptions.NewRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "subscriptionValue", "ruleValue") + +read, err := client.RulesGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/client.go new file mode 100644 index 000000000000..da1257d5d970 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/client.go @@ -0,0 +1,18 @@ +package subscriptions + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SubscriptionsClient struct { + Client autorest.Client + baseUri string +} + +func NewSubscriptionsClientWithBaseURI(endpoint string) SubscriptionsClient { + return SubscriptionsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/constants.go new file mode 100644 index 000000000000..971bb325a5f8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/constants.go @@ -0,0 +1,83 @@ +package subscriptions + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EntityStatus string + +const ( + EntityStatusActive EntityStatus = "Active" + EntityStatusCreating EntityStatus = "Creating" + EntityStatusDeleting EntityStatus = "Deleting" + EntityStatusDisabled EntityStatus = "Disabled" + EntityStatusReceiveDisabled EntityStatus = "ReceiveDisabled" + EntityStatusRenaming EntityStatus = "Renaming" + EntityStatusRestoring EntityStatus = "Restoring" + EntityStatusSendDisabled EntityStatus = "SendDisabled" + EntityStatusUnknown EntityStatus = "Unknown" +) + +func PossibleValuesForEntityStatus() []string { + return []string{ + string(EntityStatusActive), + string(EntityStatusCreating), + string(EntityStatusDeleting), + string(EntityStatusDisabled), + string(EntityStatusReceiveDisabled), + string(EntityStatusRenaming), + string(EntityStatusRestoring), + string(EntityStatusSendDisabled), + string(EntityStatusUnknown), + } +} + +func parseEntityStatus(input string) (*EntityStatus, error) { + vals := map[string]EntityStatus{ + "active": EntityStatusActive, + "creating": EntityStatusCreating, + "deleting": EntityStatusDeleting, + "disabled": EntityStatusDisabled, + "receivedisabled": EntityStatusReceiveDisabled, + "renaming": EntityStatusRenaming, + "restoring": EntityStatusRestoring, + "senddisabled": EntityStatusSendDisabled, + "unknown": EntityStatusUnknown, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EntityStatus(input) + return &out, nil +} + +type FilterType string + +const ( + FilterTypeCorrelationFilter FilterType = "CorrelationFilter" + FilterTypeSqlFilter FilterType = "SqlFilter" +) + +func PossibleValuesForFilterType() []string { + return []string{ + string(FilterTypeCorrelationFilter), + string(FilterTypeSqlFilter), + } +} + +func parseFilterType(input string) (*FilterType, error) { + vals := map[string]FilterType{ + "correlationfilter": FilterTypeCorrelationFilter, + "sqlfilter": FilterTypeSqlFilter, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := FilterType(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_rule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_rule.go new file mode 100644 index 000000000000..ad54fab384d2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_rule.go @@ -0,0 +1,163 @@ +package subscriptions + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = RuleId{} + +// RuleId is a struct representing the Resource ID for a Rule +type RuleId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + TopicName string + SubscriptionName string + RuleName string +} + +// NewRuleID returns a new RuleId struct +func NewRuleID(subscriptionId string, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, ruleName string) RuleId { + return RuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + TopicName: topicName, + SubscriptionName: subscriptionName, + RuleName: ruleName, + } +} + +// ParseRuleID parses 'input' into a RuleId +func ParseRuleID(input string) (*RuleId, error) { + parser := resourceids.NewParserFromResourceIdType(RuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := RuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.SubscriptionName, ok = parsed.Parsed["subscriptionName"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionName' was not found in the resource id %q", input) + } + + if id.RuleName, ok = parsed.Parsed["ruleName"]; !ok { + return nil, fmt.Errorf("the segment 'ruleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseRuleIDInsensitively parses 'input' case-insensitively into a RuleId +// note: this method should only be used for API response data and not user input +func ParseRuleIDInsensitively(input string) (*RuleId, error) { + parser := resourceids.NewParserFromResourceIdType(RuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := RuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.SubscriptionName, ok = parsed.Parsed["subscriptionName"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionName' was not found in the resource id %q", input) + } + + if id.RuleName, ok = parsed.Parsed["ruleName"]; !ok { + return nil, fmt.Errorf("the segment 'ruleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateRuleID checks that 'input' can be parsed as a Rule ID +func ValidateRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Rule ID +func (id RuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/topics/%s/subscriptions/%s/rules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName, id.SubscriptionName, id.RuleName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Rule ID +func (id RuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticTopics", "topics", "topics"), + resourceids.UserSpecifiedSegment("topicName", "topicValue"), + resourceids.StaticSegment("staticSubscriptions2", "subscriptions", "subscriptions"), + resourceids.UserSpecifiedSegment("subscriptionName", "subscriptionValue"), + resourceids.StaticSegment("staticRules", "rules", "rules"), + resourceids.UserSpecifiedSegment("ruleName", "ruleValue"), + } +} + +// String returns a human-readable description of this Rule ID +func (id RuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Topic Name: %q", id.TopicName), + fmt.Sprintf("Subscription Name: %q", id.SubscriptionName), + fmt.Sprintf("Rule Name: %q", id.RuleName), + } + return fmt.Sprintf("Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_subscriptions2.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_subscriptions2.go new file mode 100644 index 000000000000..a29559cdc8ae --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_subscriptions2.go @@ -0,0 +1,150 @@ +package subscriptions + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = Subscriptions2Id{} + +// Subscriptions2Id is a struct representing the Resource ID for a Subscriptions 2 +type Subscriptions2Id struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + TopicName string + SubscriptionName string +} + +// NewSubscriptions2ID returns a new Subscriptions2Id struct +func NewSubscriptions2ID(subscriptionId string, resourceGroupName string, namespaceName string, topicName string, subscriptionName string) Subscriptions2Id { + return Subscriptions2Id{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + TopicName: topicName, + SubscriptionName: subscriptionName, + } +} + +// ParseSubscriptions2ID parses 'input' into a Subscriptions2Id +func ParseSubscriptions2ID(input string) (*Subscriptions2Id, error) { + parser := resourceids.NewParserFromResourceIdType(Subscriptions2Id{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := Subscriptions2Id{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.SubscriptionName, ok = parsed.Parsed["subscriptionName"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseSubscriptions2IDInsensitively parses 'input' case-insensitively into a Subscriptions2Id +// note: this method should only be used for API response data and not user input +func ParseSubscriptions2IDInsensitively(input string) (*Subscriptions2Id, error) { + parser := resourceids.NewParserFromResourceIdType(Subscriptions2Id{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := Subscriptions2Id{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.SubscriptionName, ok = parsed.Parsed["subscriptionName"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateSubscriptions2ID checks that 'input' can be parsed as a Subscriptions 2 ID +func ValidateSubscriptions2ID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseSubscriptions2ID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Subscriptions 2 ID +func (id Subscriptions2Id) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/topics/%s/subscriptions/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName, id.SubscriptionName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Subscriptions 2 ID +func (id Subscriptions2Id) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticTopics", "topics", "topics"), + resourceids.UserSpecifiedSegment("topicName", "topicValue"), + resourceids.StaticSegment("staticSubscriptions2", "subscriptions", "subscriptions"), + resourceids.UserSpecifiedSegment("subscriptionName", "subscriptionValue"), + } +} + +// String returns a human-readable description of this Subscriptions 2 ID +func (id Subscriptions2Id) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Topic Name: %q", id.TopicName), + fmt.Sprintf("Subscription Name: %q", id.SubscriptionName), + } + return fmt.Sprintf("Subscriptions 2 (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_topic.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_topic.go new file mode 100644 index 000000000000..3c57014bca0d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/id_topic.go @@ -0,0 +1,137 @@ +package subscriptions + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = TopicId{} + +// TopicId is a struct representing the Resource ID for a Topic +type TopicId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + TopicName string +} + +// NewTopicID returns a new TopicId struct +func NewTopicID(subscriptionId string, resourceGroupName string, namespaceName string, topicName string) TopicId { + return TopicId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + TopicName: topicName, + } +} + +// ParseTopicID parses 'input' into a TopicId +func ParseTopicID(input string) (*TopicId, error) { + parser := resourceids.NewParserFromResourceIdType(TopicId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := TopicId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseTopicIDInsensitively parses 'input' case-insensitively into a TopicId +// note: this method should only be used for API response data and not user input +func ParseTopicIDInsensitively(input string) (*TopicId, error) { + parser := resourceids.NewParserFromResourceIdType(TopicId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := TopicId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateTopicID checks that 'input' can be parsed as a Topic ID +func ValidateTopicID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseTopicID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Topic ID +func (id TopicId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/topics/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Topic ID +func (id TopicId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticTopics", "topics", "topics"), + resourceids.UserSpecifiedSegment("topicName", "topicValue"), + } +} + +// String returns a human-readable description of this Topic ID +func (id TopicId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Topic Name: %q", id.TopicName), + } + return fmt.Sprintf("Topic (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_createorupdate_autorest.go new file mode 100644 index 000000000000..2cc752f083cd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package subscriptions + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *SBSubscription +} + +// CreateOrUpdate ... +func (c SubscriptionsClient) CreateOrUpdate(ctx context.Context, id Subscriptions2Id, input SBSubscription) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c SubscriptionsClient) preparerForCreateOrUpdate(ctx context.Context, id Subscriptions2Id, input SBSubscription) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c SubscriptionsClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_delete_autorest.go new file mode 100644 index 000000000000..8a96fdd572fe --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_delete_autorest.go @@ -0,0 +1,65 @@ +package subscriptions + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c SubscriptionsClient) Delete(ctx context.Context, id Subscriptions2Id) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c SubscriptionsClient) preparerForDelete(ctx context.Context, id Subscriptions2Id) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c SubscriptionsClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_get_autorest.go new file mode 100644 index 000000000000..c8aabc90096a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_get_autorest.go @@ -0,0 +1,67 @@ +package subscriptions + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *SBSubscription +} + +// Get ... +func (c SubscriptionsClient) Get(ctx context.Context, id Subscriptions2Id) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c SubscriptionsClient) preparerForGet(ctx context.Context, id Subscriptions2Id) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c SubscriptionsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_listbytopic_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_listbytopic_autorest.go new file mode 100644 index 000000000000..42884bed6c53 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_listbytopic_autorest.go @@ -0,0 +1,220 @@ +package subscriptions + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByTopicOperationResponse struct { + HttpResponse *http.Response + Model *[]SBSubscription + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByTopicOperationResponse, error) +} + +type ListByTopicCompleteResult struct { + Items []SBSubscription +} + +func (r ListByTopicOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByTopicOperationResponse) LoadMore(ctx context.Context) (resp ListByTopicOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type ListByTopicOperationOptions struct { + Skip *int64 + Top *int64 +} + +func DefaultListByTopicOperationOptions() ListByTopicOperationOptions { + return ListByTopicOperationOptions{} +} + +func (o ListByTopicOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o ListByTopicOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Skip != nil { + out["$skip"] = *o.Skip + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// ListByTopic ... +func (c SubscriptionsClient) ListByTopic(ctx context.Context, id TopicId, options ListByTopicOperationOptions) (resp ListByTopicOperationResponse, err error) { + req, err := c.preparerForListByTopic(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "ListByTopic", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "ListByTopic", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByTopic(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "ListByTopic", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByTopicComplete retrieves all of the results into a single object +func (c SubscriptionsClient) ListByTopicComplete(ctx context.Context, id TopicId, options ListByTopicOperationOptions) (ListByTopicCompleteResult, error) { + return c.ListByTopicCompleteMatchingPredicate(ctx, id, options, SBSubscriptionOperationPredicate{}) +} + +// ListByTopicCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SubscriptionsClient) ListByTopicCompleteMatchingPredicate(ctx context.Context, id TopicId, options ListByTopicOperationOptions, predicate SBSubscriptionOperationPredicate) (resp ListByTopicCompleteResult, err error) { + items := make([]SBSubscription, 0) + + page, err := c.ListByTopic(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByTopicCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByTopic prepares the ListByTopic request. +func (c SubscriptionsClient) preparerForListByTopic(ctx context.Context, id TopicId, options ListByTopicOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/subscriptions", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByTopicWithNextLink prepares the ListByTopic request with the given nextLink token. +func (c SubscriptionsClient) preparerForListByTopicWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByTopic handles the response to the ListByTopic request. The method always +// closes the http.Response Body. +func (c SubscriptionsClient) responderForListByTopic(resp *http.Response) (result ListByTopicOperationResponse, err error) { + type page struct { + Values []SBSubscription `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByTopicOperationResponse, err error) { + req, err := c.preparerForListByTopicWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "ListByTopic", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "ListByTopic", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByTopic(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "ListByTopic", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_rulesget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_rulesget_autorest.go new file mode 100644 index 000000000000..07c4d322e1e7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/method_rulesget_autorest.go @@ -0,0 +1,67 @@ +package subscriptions + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RulesGetOperationResponse struct { + HttpResponse *http.Response + Model *Rule +} + +// RulesGet ... +func (c SubscriptionsClient) RulesGet(ctx context.Context, id RuleId) (result RulesGetOperationResponse, err error) { + req, err := c.preparerForRulesGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "RulesGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "RulesGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForRulesGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "subscriptions.SubscriptionsClient", "RulesGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForRulesGet prepares the RulesGet request. +func (c SubscriptionsClient) preparerForRulesGet(ctx context.Context, id RuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForRulesGet handles the response to the RulesGet request. The method always +// closes the http.Response Body. +func (c SubscriptionsClient) responderForRulesGet(resp *http.Response) (result RulesGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_action.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_action.go new file mode 100644 index 000000000000..305f58fb92c5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_action.go @@ -0,0 +1,10 @@ +package subscriptions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Action struct { + CompatibilityLevel *int64 `json:"compatibilityLevel,omitempty"` + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` + SqlExpression *string `json:"sqlExpression,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_correlationfilter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_correlationfilter.go new file mode 100644 index 000000000000..7caba4aa70d7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_correlationfilter.go @@ -0,0 +1,17 @@ +package subscriptions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CorrelationFilter struct { + ContentType *string `json:"contentType,omitempty"` + CorrelationId *string `json:"correlationId,omitempty"` + Label *string `json:"label,omitempty"` + MessageId *string `json:"messageId,omitempty"` + Properties *map[string]string `json:"properties,omitempty"` + ReplyTo *string `json:"replyTo,omitempty"` + ReplyToSessionId *string `json:"replyToSessionId,omitempty"` + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` + SessionId *string `json:"sessionId,omitempty"` + To *string `json:"to,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_messagecountdetails.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_messagecountdetails.go new file mode 100644 index 000000000000..72c8d97e6af8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_messagecountdetails.go @@ -0,0 +1,12 @@ +package subscriptions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type MessageCountDetails struct { + ActiveMessageCount *int64 `json:"activeMessageCount,omitempty"` + DeadLetterMessageCount *int64 `json:"deadLetterMessageCount,omitempty"` + ScheduledMessageCount *int64 `json:"scheduledMessageCount,omitempty"` + TransferDeadLetterMessageCount *int64 `json:"transferDeadLetterMessageCount,omitempty"` + TransferMessageCount *int64 `json:"transferMessageCount,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_rule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_rule.go new file mode 100644 index 000000000000..f4af4e85a276 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_rule.go @@ -0,0 +1,16 @@ +package subscriptions + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Rule struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *Ruleproperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_ruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_ruleproperties.go new file mode 100644 index 000000000000..05dd1c71de3b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_ruleproperties.go @@ -0,0 +1,11 @@ +package subscriptions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Ruleproperties struct { + Action *Action `json:"action,omitempty"` + CorrelationFilter *CorrelationFilter `json:"correlationFilter,omitempty"` + FilterType *FilterType `json:"filterType,omitempty"` + SqlFilter *SqlFilter `json:"sqlFilter,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbclientaffineproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbclientaffineproperties.go new file mode 100644 index 000000000000..8a8832d705a5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbclientaffineproperties.go @@ -0,0 +1,10 @@ +package subscriptions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBClientAffineProperties struct { + ClientId *string `json:"clientId,omitempty"` + IsDurable *bool `json:"isDurable,omitempty"` + IsShared *bool `json:"isShared,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbsubscription.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbsubscription.go new file mode 100644 index 000000000000..7079232703ee --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbsubscription.go @@ -0,0 +1,16 @@ +package subscriptions + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBSubscription struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SBSubscriptionProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbsubscriptionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbsubscriptionproperties.go new file mode 100644 index 000000000000..fae0f41f9b7a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sbsubscriptionproperties.go @@ -0,0 +1,68 @@ +package subscriptions + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBSubscriptionProperties struct { + AccessedAt *string `json:"accessedAt,omitempty"` + AutoDeleteOnIdle *string `json:"autoDeleteOnIdle,omitempty"` + ClientAffineProperties *SBClientAffineProperties `json:"clientAffineProperties,omitempty"` + CountDetails *MessageCountDetails `json:"countDetails,omitempty"` + CreatedAt *string `json:"createdAt,omitempty"` + DeadLetteringOnFilterEvaluationExceptions *bool `json:"deadLetteringOnFilterEvaluationExceptions,omitempty"` + DeadLetteringOnMessageExpiration *bool `json:"deadLetteringOnMessageExpiration,omitempty"` + DefaultMessageTimeToLive *string `json:"defaultMessageTimeToLive,omitempty"` + DuplicateDetectionHistoryTimeWindow *string `json:"duplicateDetectionHistoryTimeWindow,omitempty"` + EnableBatchedOperations *bool `json:"enableBatchedOperations,omitempty"` + ForwardDeadLetteredMessagesTo *string `json:"forwardDeadLetteredMessagesTo,omitempty"` + ForwardTo *string `json:"forwardTo,omitempty"` + IsClientAffine *bool `json:"isClientAffine,omitempty"` + LockDuration *string `json:"lockDuration,omitempty"` + MaxDeliveryCount *int64 `json:"maxDeliveryCount,omitempty"` + MessageCount *int64 `json:"messageCount,omitempty"` + RequiresSession *bool `json:"requiresSession,omitempty"` + Status *EntityStatus `json:"status,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` +} + +func (o *SBSubscriptionProperties) GetAccessedAtAsTime() (*time.Time, error) { + if o.AccessedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.AccessedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBSubscriptionProperties) SetAccessedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.AccessedAt = &formatted +} + +func (o *SBSubscriptionProperties) GetCreatedAtAsTime() (*time.Time, error) { + if o.CreatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBSubscriptionProperties) SetCreatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedAt = &formatted +} + +func (o *SBSubscriptionProperties) GetUpdatedAtAsTime() (*time.Time, error) { + if o.UpdatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.UpdatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBSubscriptionProperties) SetUpdatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.UpdatedAt = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sqlfilter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sqlfilter.go new file mode 100644 index 000000000000..2980ee7e2ad9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/model_sqlfilter.go @@ -0,0 +1,10 @@ +package subscriptions + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SqlFilter struct { + CompatibilityLevel *int64 `json:"compatibilityLevel,omitempty"` + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` + SqlExpression *string `json:"sqlExpression,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/predicates.go new file mode 100644 index 000000000000..755e5d7fc260 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/predicates.go @@ -0,0 +1,24 @@ +package subscriptions + +type SBSubscriptionOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p SBSubscriptionOperationPredicate) Matches(input SBSubscription) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/version.go new file mode 100644 index 000000000000..0ee9e9513ad2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions/version.go @@ -0,0 +1,12 @@ +package subscriptions + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-06-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/subscriptions/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/README.md new file mode 100644 index 000000000000..bff215cc2ccd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/README.md @@ -0,0 +1,90 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics` Documentation + +The `topics` SDK allows for interaction with the Azure Resource Manager Service `servicebus` (API Version `2021-06-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics" +``` + + +### Client Initialization + +```go +client := topics.NewTopicsClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `TopicsClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := topics.NewTopicID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue") + +payload := topics.SBTopic{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `TopicsClient.Delete` + +```go +ctx := context.TODO() +id := topics.NewTopicID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `TopicsClient.Get` + +```go +ctx := context.TODO() +id := topics.NewTopicID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `TopicsClient.ListByNamespace` + +```go +ctx := context.TODO() +id := topics.NewNamespaceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue") + +// alternatively `client.ListByNamespace(ctx, id, topics.DefaultListByNamespaceOperationOptions())` can be used to do batched pagination +items, err := client.ListByNamespaceComplete(ctx, id, topics.DefaultListByNamespaceOperationOptions()) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/client.go new file mode 100644 index 000000000000..d5c9fa358795 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/client.go @@ -0,0 +1,18 @@ +package topics + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type TopicsClient struct { + Client autorest.Client + baseUri string +} + +func NewTopicsClientWithBaseURI(endpoint string) TopicsClient { + return TopicsClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/constants.go new file mode 100644 index 000000000000..07f1029faba1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/constants.go @@ -0,0 +1,55 @@ +package topics + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type EntityStatus string + +const ( + EntityStatusActive EntityStatus = "Active" + EntityStatusCreating EntityStatus = "Creating" + EntityStatusDeleting EntityStatus = "Deleting" + EntityStatusDisabled EntityStatus = "Disabled" + EntityStatusReceiveDisabled EntityStatus = "ReceiveDisabled" + EntityStatusRenaming EntityStatus = "Renaming" + EntityStatusRestoring EntityStatus = "Restoring" + EntityStatusSendDisabled EntityStatus = "SendDisabled" + EntityStatusUnknown EntityStatus = "Unknown" +) + +func PossibleValuesForEntityStatus() []string { + return []string{ + string(EntityStatusActive), + string(EntityStatusCreating), + string(EntityStatusDeleting), + string(EntityStatusDisabled), + string(EntityStatusReceiveDisabled), + string(EntityStatusRenaming), + string(EntityStatusRestoring), + string(EntityStatusSendDisabled), + string(EntityStatusUnknown), + } +} + +func parseEntityStatus(input string) (*EntityStatus, error) { + vals := map[string]EntityStatus{ + "active": EntityStatusActive, + "creating": EntityStatusCreating, + "deleting": EntityStatusDeleting, + "disabled": EntityStatusDisabled, + "receivedisabled": EntityStatusReceiveDisabled, + "renaming": EntityStatusRenaming, + "restoring": EntityStatusRestoring, + "senddisabled": EntityStatusSendDisabled, + "unknown": EntityStatusUnknown, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := EntityStatus(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/id_namespace.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/id_namespace.go new file mode 100644 index 000000000000..dd4c6ad03273 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/id_namespace.go @@ -0,0 +1,124 @@ +package topics + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = NamespaceId{} + +// NamespaceId is a struct representing the Resource ID for a Namespace +type NamespaceId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string +} + +// NewNamespaceID returns a new NamespaceId struct +func NewNamespaceID(subscriptionId string, resourceGroupName string, namespaceName string) NamespaceId { + return NamespaceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + } +} + +// ParseNamespaceID parses 'input' into a NamespaceId +func ParseNamespaceID(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseNamespaceIDInsensitively parses 'input' case-insensitively into a NamespaceId +// note: this method should only be used for API response data and not user input +func ParseNamespaceIDInsensitively(input string) (*NamespaceId, error) { + parser := resourceids.NewParserFromResourceIdType(NamespaceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := NamespaceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateNamespaceID checks that 'input' can be parsed as a Namespace ID +func ValidateNamespaceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseNamespaceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Namespace ID +func (id NamespaceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Namespace ID +func (id NamespaceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + } +} + +// String returns a human-readable description of this Namespace ID +func (id NamespaceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + } + return fmt.Sprintf("Namespace (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/id_topic.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/id_topic.go new file mode 100644 index 000000000000..fd9ec22d0b4b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/id_topic.go @@ -0,0 +1,137 @@ +package topics + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = TopicId{} + +// TopicId is a struct representing the Resource ID for a Topic +type TopicId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + TopicName string +} + +// NewTopicID returns a new TopicId struct +func NewTopicID(subscriptionId string, resourceGroupName string, namespaceName string, topicName string) TopicId { + return TopicId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + TopicName: topicName, + } +} + +// ParseTopicID parses 'input' into a TopicId +func ParseTopicID(input string) (*TopicId, error) { + parser := resourceids.NewParserFromResourceIdType(TopicId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := TopicId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseTopicIDInsensitively parses 'input' case-insensitively into a TopicId +// note: this method should only be used for API response data and not user input +func ParseTopicIDInsensitively(input string) (*TopicId, error) { + parser := resourceids.NewParserFromResourceIdType(TopicId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := TopicId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateTopicID checks that 'input' can be parsed as a Topic ID +func ValidateTopicID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseTopicID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Topic ID +func (id TopicId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/topics/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Topic ID +func (id TopicId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticTopics", "topics", "topics"), + resourceids.UserSpecifiedSegment("topicName", "topicValue"), + } +} + +// String returns a human-readable description of this Topic ID +func (id TopicId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Topic Name: %q", id.TopicName), + } + return fmt.Sprintf("Topic (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_createorupdate_autorest.go new file mode 100644 index 000000000000..53df3d9cebc9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package topics + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *SBTopic +} + +// CreateOrUpdate ... +func (c TopicsClient) CreateOrUpdate(ctx context.Context, id TopicId, input SBTopic) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c TopicsClient) preparerForCreateOrUpdate(ctx context.Context, id TopicId, input SBTopic) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c TopicsClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_delete_autorest.go new file mode 100644 index 000000000000..1fc80a781ea8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_delete_autorest.go @@ -0,0 +1,65 @@ +package topics + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c TopicsClient) Delete(ctx context.Context, id TopicId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c TopicsClient) preparerForDelete(ctx context.Context, id TopicId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c TopicsClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_get_autorest.go new file mode 100644 index 000000000000..e5084f1628fe --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_get_autorest.go @@ -0,0 +1,67 @@ +package topics + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *SBTopic +} + +// Get ... +func (c TopicsClient) Get(ctx context.Context, id TopicId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c TopicsClient) preparerForGet(ctx context.Context, id TopicId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c TopicsClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_listbynamespace_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_listbynamespace_autorest.go new file mode 100644 index 000000000000..1f202d4aeef9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/method_listbynamespace_autorest.go @@ -0,0 +1,220 @@ +package topics + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByNamespaceOperationResponse struct { + HttpResponse *http.Response + Model *[]SBTopic + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByNamespaceOperationResponse, error) +} + +type ListByNamespaceCompleteResult struct { + Items []SBTopic +} + +func (r ListByNamespaceOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByNamespaceOperationResponse) LoadMore(ctx context.Context) (resp ListByNamespaceOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +type ListByNamespaceOperationOptions struct { + Skip *int64 + Top *int64 +} + +func DefaultListByNamespaceOperationOptions() ListByNamespaceOperationOptions { + return ListByNamespaceOperationOptions{} +} + +func (o ListByNamespaceOperationOptions) toHeaders() map[string]interface{} { + out := make(map[string]interface{}) + + return out +} + +func (o ListByNamespaceOperationOptions) toQueryString() map[string]interface{} { + out := make(map[string]interface{}) + + if o.Skip != nil { + out["$skip"] = *o.Skip + } + + if o.Top != nil { + out["$top"] = *o.Top + } + + return out +} + +// ListByNamespace ... +func (c TopicsClient) ListByNamespace(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions) (resp ListByNamespaceOperationResponse, err error) { + req, err := c.preparerForListByNamespace(ctx, id, options) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "ListByNamespace", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "ListByNamespace", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByNamespace(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "ListByNamespace", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByNamespaceComplete retrieves all of the results into a single object +func (c TopicsClient) ListByNamespaceComplete(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions) (ListByNamespaceCompleteResult, error) { + return c.ListByNamespaceCompleteMatchingPredicate(ctx, id, options, SBTopicOperationPredicate{}) +} + +// ListByNamespaceCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c TopicsClient) ListByNamespaceCompleteMatchingPredicate(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions, predicate SBTopicOperationPredicate) (resp ListByNamespaceCompleteResult, err error) { + items := make([]SBTopic, 0) + + page, err := c.ListByNamespace(ctx, id, options) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByNamespaceCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByNamespace prepares the ListByNamespace request. +func (c TopicsClient) preparerForListByNamespace(ctx context.Context, id NamespaceId, options ListByNamespaceOperationOptions) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + for k, v := range options.toQueryString() { + queryParameters[k] = autorest.Encode("query", v) + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithHeaders(options.toHeaders()), + autorest.WithPath(fmt.Sprintf("%s/topics", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByNamespaceWithNextLink prepares the ListByNamespace request with the given nextLink token. +func (c TopicsClient) preparerForListByNamespaceWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByNamespace handles the response to the ListByNamespace request. The method always +// closes the http.Response Body. +func (c TopicsClient) responderForListByNamespace(resp *http.Response) (result ListByNamespaceOperationResponse, err error) { + type page struct { + Values []SBTopic `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByNamespaceOperationResponse, err error) { + req, err := c.preparerForListByNamespaceWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "ListByNamespace", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "ListByNamespace", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByNamespace(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topics.TopicsClient", "ListByNamespace", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_messagecountdetails.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_messagecountdetails.go new file mode 100644 index 000000000000..4035d658e9c4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_messagecountdetails.go @@ -0,0 +1,12 @@ +package topics + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type MessageCountDetails struct { + ActiveMessageCount *int64 `json:"activeMessageCount,omitempty"` + DeadLetterMessageCount *int64 `json:"deadLetterMessageCount,omitempty"` + ScheduledMessageCount *int64 `json:"scheduledMessageCount,omitempty"` + TransferDeadLetterMessageCount *int64 `json:"transferDeadLetterMessageCount,omitempty"` + TransferMessageCount *int64 `json:"transferMessageCount,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_sbtopic.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_sbtopic.go new file mode 100644 index 000000000000..8143c623d4ec --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_sbtopic.go @@ -0,0 +1,16 @@ +package topics + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBTopic struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SBTopicProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_sbtopicproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_sbtopicproperties.go new file mode 100644 index 000000000000..ef51e8fe89f7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/model_sbtopicproperties.go @@ -0,0 +1,66 @@ +package topics + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBTopicProperties struct { + AccessedAt *string `json:"accessedAt,omitempty"` + AutoDeleteOnIdle *string `json:"autoDeleteOnIdle,omitempty"` + CountDetails *MessageCountDetails `json:"countDetails,omitempty"` + CreatedAt *string `json:"createdAt,omitempty"` + DefaultMessageTimeToLive *string `json:"defaultMessageTimeToLive,omitempty"` + DuplicateDetectionHistoryTimeWindow *string `json:"duplicateDetectionHistoryTimeWindow,omitempty"` + EnableBatchedOperations *bool `json:"enableBatchedOperations,omitempty"` + EnableExpress *bool `json:"enableExpress,omitempty"` + EnablePartitioning *bool `json:"enablePartitioning,omitempty"` + MaxMessageSizeInKilobytes *int64 `json:"maxMessageSizeInKilobytes,omitempty"` + MaxSizeInMegabytes *int64 `json:"maxSizeInMegabytes,omitempty"` + RequiresDuplicateDetection *bool `json:"requiresDuplicateDetection,omitempty"` + SizeInBytes *int64 `json:"sizeInBytes,omitempty"` + Status *EntityStatus `json:"status,omitempty"` + SubscriptionCount *int64 `json:"subscriptionCount,omitempty"` + SupportOrdering *bool `json:"supportOrdering,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` +} + +func (o *SBTopicProperties) GetAccessedAtAsTime() (*time.Time, error) { + if o.AccessedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.AccessedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBTopicProperties) SetAccessedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.AccessedAt = &formatted +} + +func (o *SBTopicProperties) GetCreatedAtAsTime() (*time.Time, error) { + if o.CreatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.CreatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBTopicProperties) SetCreatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.CreatedAt = &formatted +} + +func (o *SBTopicProperties) GetUpdatedAtAsTime() (*time.Time, error) { + if o.UpdatedAt == nil { + return nil, nil + } + return dates.ParseAsFormat(o.UpdatedAt, "2006-01-02T15:04:05Z07:00") +} + +func (o *SBTopicProperties) SetUpdatedAtAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.UpdatedAt = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/predicates.go new file mode 100644 index 000000000000..0a1a4cf85b27 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/predicates.go @@ -0,0 +1,24 @@ +package topics + +type SBTopicOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p SBTopicOperationPredicate) Matches(input SBTopic) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/version.go new file mode 100644 index 000000000000..f30136ef355c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics/version.go @@ -0,0 +1,12 @@ +package topics + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-06-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/topics/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/README.md new file mode 100644 index 000000000000..9f43c536d697 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/README.md @@ -0,0 +1,127 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule` Documentation + +The `topicsauthorizationrule` SDK allows for interaction with the Azure Resource Manager Service `servicebus` (API Version `2021-06-01-preview`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule" +``` + + +### Client Initialization + +```go +client := topicsauthorizationrule.NewTopicsAuthorizationRuleClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `TopicsAuthorizationRuleClient.TopicsCreateOrUpdateAuthorizationRule` + +```go +ctx := context.TODO() +id := topicsauthorizationrule.NewTopicAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "authorizationRuleValue") + +payload := topicsauthorizationrule.SBAuthorizationRule{ + // ... +} + + +read, err := client.TopicsCreateOrUpdateAuthorizationRule(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `TopicsAuthorizationRuleClient.TopicsDeleteAuthorizationRule` + +```go +ctx := context.TODO() +id := topicsauthorizationrule.NewTopicAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "authorizationRuleValue") + +read, err := client.TopicsDeleteAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `TopicsAuthorizationRuleClient.TopicsGetAuthorizationRule` + +```go +ctx := context.TODO() +id := topicsauthorizationrule.NewTopicAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "authorizationRuleValue") + +read, err := client.TopicsGetAuthorizationRule(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `TopicsAuthorizationRuleClient.TopicsListAuthorizationRules` + +```go +ctx := context.TODO() +id := topicsauthorizationrule.NewTopicID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue") + +// alternatively `client.TopicsListAuthorizationRules(ctx, id)` can be used to do batched pagination +items, err := client.TopicsListAuthorizationRulesComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `TopicsAuthorizationRuleClient.TopicsListKeys` + +```go +ctx := context.TODO() +id := topicsauthorizationrule.NewTopicAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "authorizationRuleValue") + +read, err := client.TopicsListKeys(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `TopicsAuthorizationRuleClient.TopicsRegenerateKeys` + +```go +ctx := context.TODO() +id := topicsauthorizationrule.NewTopicAuthorizationRuleID("12345678-1234-9876-4563-123456789012", "example-resource-group", "namespaceValue", "topicValue", "authorizationRuleValue") + +payload := topicsauthorizationrule.RegenerateAccessKeyParameters{ + // ... +} + + +read, err := client.TopicsRegenerateKeys(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/client.go new file mode 100644 index 000000000000..271398331b71 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/client.go @@ -0,0 +1,18 @@ +package topicsauthorizationrule + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type TopicsAuthorizationRuleClient struct { + Client autorest.Client + baseUri string +} + +func NewTopicsAuthorizationRuleClientWithBaseURI(endpoint string) TopicsAuthorizationRuleClient { + return TopicsAuthorizationRuleClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/constants.go new file mode 100644 index 000000000000..36f8229f8068 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/constants.go @@ -0,0 +1,65 @@ +package topicsauthorizationrule + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessRights string + +const ( + AccessRightsListen AccessRights = "Listen" + AccessRightsManage AccessRights = "Manage" + AccessRightsSend AccessRights = "Send" +) + +func PossibleValuesForAccessRights() []string { + return []string{ + string(AccessRightsListen), + string(AccessRightsManage), + string(AccessRightsSend), + } +} + +func parseAccessRights(input string) (*AccessRights, error) { + vals := map[string]AccessRights{ + "listen": AccessRightsListen, + "manage": AccessRightsManage, + "send": AccessRightsSend, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := AccessRights(input) + return &out, nil +} + +type KeyType string + +const ( + KeyTypePrimaryKey KeyType = "PrimaryKey" + KeyTypeSecondaryKey KeyType = "SecondaryKey" +) + +func PossibleValuesForKeyType() []string { + return []string{ + string(KeyTypePrimaryKey), + string(KeyTypeSecondaryKey), + } +} + +func parseKeyType(input string) (*KeyType, error) { + vals := map[string]KeyType{ + "primarykey": KeyTypePrimaryKey, + "secondarykey": KeyTypeSecondaryKey, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeyType(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/id_topic.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/id_topic.go new file mode 100644 index 000000000000..909935c8ca78 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/id_topic.go @@ -0,0 +1,137 @@ +package topicsauthorizationrule + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = TopicId{} + +// TopicId is a struct representing the Resource ID for a Topic +type TopicId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + TopicName string +} + +// NewTopicID returns a new TopicId struct +func NewTopicID(subscriptionId string, resourceGroupName string, namespaceName string, topicName string) TopicId { + return TopicId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + TopicName: topicName, + } +} + +// ParseTopicID parses 'input' into a TopicId +func ParseTopicID(input string) (*TopicId, error) { + parser := resourceids.NewParserFromResourceIdType(TopicId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := TopicId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseTopicIDInsensitively parses 'input' case-insensitively into a TopicId +// note: this method should only be used for API response data and not user input +func ParseTopicIDInsensitively(input string) (*TopicId, error) { + parser := resourceids.NewParserFromResourceIdType(TopicId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := TopicId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateTopicID checks that 'input' can be parsed as a Topic ID +func ValidateTopicID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseTopicID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Topic ID +func (id TopicId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/topics/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Topic ID +func (id TopicId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticTopics", "topics", "topics"), + resourceids.UserSpecifiedSegment("topicName", "topicValue"), + } +} + +// String returns a human-readable description of this Topic ID +func (id TopicId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Topic Name: %q", id.TopicName), + } + return fmt.Sprintf("Topic (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/id_topicauthorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/id_topicauthorizationrule.go new file mode 100644 index 000000000000..349c1a5a24a6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/id_topicauthorizationrule.go @@ -0,0 +1,150 @@ +package topicsauthorizationrule + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = TopicAuthorizationRuleId{} + +// TopicAuthorizationRuleId is a struct representing the Resource ID for a Topic Authorization Rule +type TopicAuthorizationRuleId struct { + SubscriptionId string + ResourceGroupName string + NamespaceName string + TopicName string + AuthorizationRuleName string +} + +// NewTopicAuthorizationRuleID returns a new TopicAuthorizationRuleId struct +func NewTopicAuthorizationRuleID(subscriptionId string, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) TopicAuthorizationRuleId { + return TopicAuthorizationRuleId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + NamespaceName: namespaceName, + TopicName: topicName, + AuthorizationRuleName: authorizationRuleName, + } +} + +// ParseTopicAuthorizationRuleID parses 'input' into a TopicAuthorizationRuleId +func ParseTopicAuthorizationRuleID(input string) (*TopicAuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(TopicAuthorizationRuleId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := TopicAuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseTopicAuthorizationRuleIDInsensitively parses 'input' case-insensitively into a TopicAuthorizationRuleId +// note: this method should only be used for API response data and not user input +func ParseTopicAuthorizationRuleIDInsensitively(input string) (*TopicAuthorizationRuleId, error) { + parser := resourceids.NewParserFromResourceIdType(TopicAuthorizationRuleId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := TopicAuthorizationRuleId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.NamespaceName, ok = parsed.Parsed["namespaceName"]; !ok { + return nil, fmt.Errorf("the segment 'namespaceName' was not found in the resource id %q", input) + } + + if id.TopicName, ok = parsed.Parsed["topicName"]; !ok { + return nil, fmt.Errorf("the segment 'topicName' was not found in the resource id %q", input) + } + + if id.AuthorizationRuleName, ok = parsed.Parsed["authorizationRuleName"]; !ok { + return nil, fmt.Errorf("the segment 'authorizationRuleName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateTopicAuthorizationRuleID checks that 'input' can be parsed as a Topic Authorization Rule ID +func ValidateTopicAuthorizationRuleID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseTopicAuthorizationRuleID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Topic Authorization Rule ID +func (id TopicAuthorizationRuleId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s/topics/%s/authorizationRules/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NamespaceName, id.TopicName, id.AuthorizationRuleName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Topic Authorization Rule ID +func (id TopicAuthorizationRuleId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftServiceBus", "Microsoft.ServiceBus", "Microsoft.ServiceBus"), + resourceids.StaticSegment("staticNamespaces", "namespaces", "namespaces"), + resourceids.UserSpecifiedSegment("namespaceName", "namespaceValue"), + resourceids.StaticSegment("staticTopics", "topics", "topics"), + resourceids.UserSpecifiedSegment("topicName", "topicValue"), + resourceids.StaticSegment("staticAuthorizationRules", "authorizationRules", "authorizationRules"), + resourceids.UserSpecifiedSegment("authorizationRuleName", "authorizationRuleValue"), + } +} + +// String returns a human-readable description of this Topic Authorization Rule ID +func (id TopicAuthorizationRuleId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Namespace Name: %q", id.NamespaceName), + fmt.Sprintf("Topic Name: %q", id.TopicName), + fmt.Sprintf("Authorization Rule Name: %q", id.AuthorizationRuleName), + } + return fmt.Sprintf("Topic Authorization Rule (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicscreateorupdateauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicscreateorupdateauthorizationrule_autorest.go new file mode 100644 index 000000000000..e3feda073643 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicscreateorupdateauthorizationrule_autorest.go @@ -0,0 +1,68 @@ +package topicsauthorizationrule + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type TopicsCreateOrUpdateAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *SBAuthorizationRule +} + +// TopicsCreateOrUpdateAuthorizationRule ... +func (c TopicsAuthorizationRuleClient) TopicsCreateOrUpdateAuthorizationRule(ctx context.Context, id TopicAuthorizationRuleId, input SBAuthorizationRule) (result TopicsCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForTopicsCreateOrUpdateAuthorizationRule(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsCreateOrUpdateAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForTopicsCreateOrUpdateAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsCreateOrUpdateAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForTopicsCreateOrUpdateAuthorizationRule prepares the TopicsCreateOrUpdateAuthorizationRule request. +func (c TopicsAuthorizationRuleClient) preparerForTopicsCreateOrUpdateAuthorizationRule(ctx context.Context, id TopicAuthorizationRuleId, input SBAuthorizationRule) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForTopicsCreateOrUpdateAuthorizationRule handles the response to the TopicsCreateOrUpdateAuthorizationRule request. The method always +// closes the http.Response Body. +func (c TopicsAuthorizationRuleClient) responderForTopicsCreateOrUpdateAuthorizationRule(resp *http.Response) (result TopicsCreateOrUpdateAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsdeleteauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsdeleteauthorizationrule_autorest.go new file mode 100644 index 000000000000..7368dc04b0b9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsdeleteauthorizationrule_autorest.go @@ -0,0 +1,65 @@ +package topicsauthorizationrule + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type TopicsDeleteAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response +} + +// TopicsDeleteAuthorizationRule ... +func (c TopicsAuthorizationRuleClient) TopicsDeleteAuthorizationRule(ctx context.Context, id TopicAuthorizationRuleId) (result TopicsDeleteAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForTopicsDeleteAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsDeleteAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsDeleteAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForTopicsDeleteAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsDeleteAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForTopicsDeleteAuthorizationRule prepares the TopicsDeleteAuthorizationRule request. +func (c TopicsAuthorizationRuleClient) preparerForTopicsDeleteAuthorizationRule(ctx context.Context, id TopicAuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForTopicsDeleteAuthorizationRule handles the response to the TopicsDeleteAuthorizationRule request. The method always +// closes the http.Response Body. +func (c TopicsAuthorizationRuleClient) responderForTopicsDeleteAuthorizationRule(resp *http.Response) (result TopicsDeleteAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsgetauthorizationrule_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsgetauthorizationrule_autorest.go new file mode 100644 index 000000000000..f55209f3388a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsgetauthorizationrule_autorest.go @@ -0,0 +1,67 @@ +package topicsauthorizationrule + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type TopicsGetAuthorizationRuleOperationResponse struct { + HttpResponse *http.Response + Model *SBAuthorizationRule +} + +// TopicsGetAuthorizationRule ... +func (c TopicsAuthorizationRuleClient) TopicsGetAuthorizationRule(ctx context.Context, id TopicAuthorizationRuleId) (result TopicsGetAuthorizationRuleOperationResponse, err error) { + req, err := c.preparerForTopicsGetAuthorizationRule(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsGetAuthorizationRule", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsGetAuthorizationRule", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForTopicsGetAuthorizationRule(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsGetAuthorizationRule", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForTopicsGetAuthorizationRule prepares the TopicsGetAuthorizationRule request. +func (c TopicsAuthorizationRuleClient) preparerForTopicsGetAuthorizationRule(ctx context.Context, id TopicAuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForTopicsGetAuthorizationRule handles the response to the TopicsGetAuthorizationRule request. The method always +// closes the http.Response Body. +func (c TopicsAuthorizationRuleClient) responderForTopicsGetAuthorizationRule(resp *http.Response) (result TopicsGetAuthorizationRuleOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicslistauthorizationrules_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicslistauthorizationrules_autorest.go new file mode 100644 index 000000000000..23dad36ef651 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicslistauthorizationrules_autorest.go @@ -0,0 +1,186 @@ +package topicsauthorizationrule + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type TopicsListAuthorizationRulesOperationResponse struct { + HttpResponse *http.Response + Model *[]SBAuthorizationRule + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (TopicsListAuthorizationRulesOperationResponse, error) +} + +type TopicsListAuthorizationRulesCompleteResult struct { + Items []SBAuthorizationRule +} + +func (r TopicsListAuthorizationRulesOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r TopicsListAuthorizationRulesOperationResponse) LoadMore(ctx context.Context) (resp TopicsListAuthorizationRulesOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// TopicsListAuthorizationRules ... +func (c TopicsAuthorizationRuleClient) TopicsListAuthorizationRules(ctx context.Context, id TopicId) (resp TopicsListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForTopicsListAuthorizationRules(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsListAuthorizationRules", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForTopicsListAuthorizationRules(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsListAuthorizationRules", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// TopicsListAuthorizationRulesComplete retrieves all of the results into a single object +func (c TopicsAuthorizationRuleClient) TopicsListAuthorizationRulesComplete(ctx context.Context, id TopicId) (TopicsListAuthorizationRulesCompleteResult, error) { + return c.TopicsListAuthorizationRulesCompleteMatchingPredicate(ctx, id, SBAuthorizationRuleOperationPredicate{}) +} + +// TopicsListAuthorizationRulesCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c TopicsAuthorizationRuleClient) TopicsListAuthorizationRulesCompleteMatchingPredicate(ctx context.Context, id TopicId, predicate SBAuthorizationRuleOperationPredicate) (resp TopicsListAuthorizationRulesCompleteResult, err error) { + items := make([]SBAuthorizationRule, 0) + + page, err := c.TopicsListAuthorizationRules(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := TopicsListAuthorizationRulesCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForTopicsListAuthorizationRules prepares the TopicsListAuthorizationRules request. +func (c TopicsAuthorizationRuleClient) preparerForTopicsListAuthorizationRules(ctx context.Context, id TopicId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/authorizationRules", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForTopicsListAuthorizationRulesWithNextLink prepares the TopicsListAuthorizationRules request with the given nextLink token. +func (c TopicsAuthorizationRuleClient) preparerForTopicsListAuthorizationRulesWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForTopicsListAuthorizationRules handles the response to the TopicsListAuthorizationRules request. The method always +// closes the http.Response Body. +func (c TopicsAuthorizationRuleClient) responderForTopicsListAuthorizationRules(resp *http.Response) (result TopicsListAuthorizationRulesOperationResponse, err error) { + type page struct { + Values []SBAuthorizationRule `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result TopicsListAuthorizationRulesOperationResponse, err error) { + req, err := c.preparerForTopicsListAuthorizationRulesWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsListAuthorizationRules", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsListAuthorizationRules", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForTopicsListAuthorizationRules(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsListAuthorizationRules", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicslistkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicslistkeys_autorest.go new file mode 100644 index 000000000000..3b9921636828 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicslistkeys_autorest.go @@ -0,0 +1,68 @@ +package topicsauthorizationrule + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type TopicsListKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// TopicsListKeys ... +func (c TopicsAuthorizationRuleClient) TopicsListKeys(ctx context.Context, id TopicAuthorizationRuleId) (result TopicsListKeysOperationResponse, err error) { + req, err := c.preparerForTopicsListKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsListKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsListKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForTopicsListKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsListKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForTopicsListKeys prepares the TopicsListKeys request. +func (c TopicsAuthorizationRuleClient) preparerForTopicsListKeys(ctx context.Context, id TopicAuthorizationRuleId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForTopicsListKeys handles the response to the TopicsListKeys request. The method always +// closes the http.Response Body. +func (c TopicsAuthorizationRuleClient) responderForTopicsListKeys(resp *http.Response) (result TopicsListKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsregeneratekeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsregeneratekeys_autorest.go new file mode 100644 index 000000000000..16508044d8bf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/method_topicsregeneratekeys_autorest.go @@ -0,0 +1,69 @@ +package topicsauthorizationrule + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type TopicsRegenerateKeysOperationResponse struct { + HttpResponse *http.Response + Model *AccessKeys +} + +// TopicsRegenerateKeys ... +func (c TopicsAuthorizationRuleClient) TopicsRegenerateKeys(ctx context.Context, id TopicAuthorizationRuleId, input RegenerateAccessKeyParameters) (result TopicsRegenerateKeysOperationResponse, err error) { + req, err := c.preparerForTopicsRegenerateKeys(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsRegenerateKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsRegenerateKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForTopicsRegenerateKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "topicsauthorizationrule.TopicsAuthorizationRuleClient", "TopicsRegenerateKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForTopicsRegenerateKeys prepares the TopicsRegenerateKeys request. +func (c TopicsAuthorizationRuleClient) preparerForTopicsRegenerateKeys(ctx context.Context, id TopicAuthorizationRuleId, input RegenerateAccessKeyParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/regenerateKeys", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForTopicsRegenerateKeys handles the response to the TopicsRegenerateKeys request. The method always +// closes the http.Response Body. +func (c TopicsAuthorizationRuleClient) responderForTopicsRegenerateKeys(resp *http.Response) (result TopicsRegenerateKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_accesskeys.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_accesskeys.go new file mode 100644 index 000000000000..88589044cc64 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_accesskeys.go @@ -0,0 +1,14 @@ +package topicsauthorizationrule + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type AccessKeys struct { + AliasPrimaryConnectionString *string `json:"aliasPrimaryConnectionString,omitempty"` + AliasSecondaryConnectionString *string `json:"aliasSecondaryConnectionString,omitempty"` + KeyName *string `json:"keyName,omitempty"` + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + PrimaryKey *string `json:"primaryKey,omitempty"` + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + SecondaryKey *string `json:"secondaryKey,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_regenerateaccesskeyparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_regenerateaccesskeyparameters.go new file mode 100644 index 000000000000..30ff1e93bdb3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_regenerateaccesskeyparameters.go @@ -0,0 +1,9 @@ +package topicsauthorizationrule + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateAccessKeyParameters struct { + Key *string `json:"key,omitempty"` + KeyType KeyType `json:"keyType"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_sbauthorizationrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_sbauthorizationrule.go new file mode 100644 index 000000000000..09528bbcee5d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_sbauthorizationrule.go @@ -0,0 +1,16 @@ +package topicsauthorizationrule + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBAuthorizationRule struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SBAuthorizationRuleProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_sbauthorizationruleproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_sbauthorizationruleproperties.go new file mode 100644 index 000000000000..eb1e1b6eeabb --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/model_sbauthorizationruleproperties.go @@ -0,0 +1,8 @@ +package topicsauthorizationrule + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SBAuthorizationRuleProperties struct { + Rights []AccessRights `json:"rights"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/predicates.go new file mode 100644 index 000000000000..0d5880d8427b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/predicates.go @@ -0,0 +1,24 @@ +package topicsauthorizationrule + +type SBAuthorizationRuleOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p SBAuthorizationRuleOperationPredicate) Matches(input SBAuthorizationRule) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/version.go new file mode 100644 index 000000000000..744b13fb7f30 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule/version.go @@ -0,0 +1,12 @@ +package topicsauthorizationrule + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-06-01-preview" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/topicsauthorizationrule/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/README.md new file mode 100644 index 000000000000..2056b1495efd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/README.md @@ -0,0 +1,488 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr` Documentation + +The `signalr` SDK allows for interaction with the Azure Resource Manager Service `signalr` (API Version `2022-02-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" +``` + + +### Client Initialization + +```go +client := signalr.NewSignalRClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `SignalRClient.CheckNameAvailability` + +```go +ctx := context.TODO() +id := signalr.NewLocationID("12345678-1234-9876-4563-123456789012", "locationValue") + +payload := signalr.NameAvailabilityParameters{ + // ... +} + + +read, err := client.CheckNameAvailability(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +payload := signalr.SignalRResource{ + // ... +} + + +if err := client.CreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.CustomCertificatesCreateOrUpdate` + +```go +ctx := context.TODO() +id := signalr.NewCustomCertificateID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "certificateValue") + +payload := signalr.CustomCertificate{ + // ... +} + + +if err := client.CustomCertificatesCreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.CustomCertificatesDelete` + +```go +ctx := context.TODO() +id := signalr.NewCustomCertificateID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "certificateValue") + +read, err := client.CustomCertificatesDelete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.CustomCertificatesGet` + +```go +ctx := context.TODO() +id := signalr.NewCustomCertificateID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "certificateValue") + +read, err := client.CustomCertificatesGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.CustomCertificatesList` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +// alternatively `client.CustomCertificatesList(ctx, id)` can be used to do batched pagination +items, err := client.CustomCertificatesListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SignalRClient.CustomDomainsCreateOrUpdate` + +```go +ctx := context.TODO() +id := signalr.NewCustomDomainID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "nameValue") + +payload := signalr.CustomDomain{ + // ... +} + + +if err := client.CustomDomainsCreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.CustomDomainsDelete` + +```go +ctx := context.TODO() +id := signalr.NewCustomDomainID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "nameValue") + +if err := client.CustomDomainsDeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.CustomDomainsGet` + +```go +ctx := context.TODO() +id := signalr.NewCustomDomainID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "nameValue") + +read, err := client.CustomDomainsGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.CustomDomainsList` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +// alternatively `client.CustomDomainsList(ctx, id)` can be used to do batched pagination +items, err := client.CustomDomainsListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SignalRClient.Delete` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +if err := client.DeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.Get` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.ListByResourceGroup` + +```go +ctx := context.TODO() +id := signalr.NewResourceGroupID() + +// alternatively `client.ListByResourceGroup(ctx, id)` can be used to do batched pagination +items, err := client.ListByResourceGroupComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SignalRClient.ListBySubscription` + +```go +ctx := context.TODO() +id := signalr.NewSubscriptionID() + +// alternatively `client.ListBySubscription(ctx, id)` can be used to do batched pagination +items, err := client.ListBySubscriptionComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SignalRClient.ListKeys` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +read, err := client.ListKeys(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.ListSkus` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +read, err := client.ListSkus(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.PrivateEndpointConnectionsDelete` + +```go +ctx := context.TODO() +id := signalr.NewPrivateEndpointConnectionID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "privateEndpointConnectionValue") + +if err := client.PrivateEndpointConnectionsDeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.PrivateEndpointConnectionsGet` + +```go +ctx := context.TODO() +id := signalr.NewPrivateEndpointConnectionID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "privateEndpointConnectionValue") + +read, err := client.PrivateEndpointConnectionsGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.PrivateEndpointConnectionsList` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +// alternatively `client.PrivateEndpointConnectionsList(ctx, id)` can be used to do batched pagination +items, err := client.PrivateEndpointConnectionsListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SignalRClient.PrivateEndpointConnectionsUpdate` + +```go +ctx := context.TODO() +id := signalr.NewPrivateEndpointConnectionID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "privateEndpointConnectionValue") + +payload := signalr.PrivateEndpointConnection{ + // ... +} + + +read, err := client.PrivateEndpointConnectionsUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.PrivateLinkResourcesList` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +// alternatively `client.PrivateLinkResourcesList(ctx, id)` can be used to do batched pagination +items, err := client.PrivateLinkResourcesListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SignalRClient.RegenerateKey` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +payload := signalr.RegenerateKeyParameters{ + // ... +} + + +if err := client.RegenerateKeyThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.Restart` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +if err := client.RestartThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.SharedPrivateLinkResourcesCreateOrUpdate` + +```go +ctx := context.TODO() +id := signalr.NewSharedPrivateLinkResourceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "sharedPrivateLinkResourceValue") + +payload := signalr.SharedPrivateLinkResource{ + // ... +} + + +if err := client.SharedPrivateLinkResourcesCreateOrUpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.SharedPrivateLinkResourcesDelete` + +```go +ctx := context.TODO() +id := signalr.NewSharedPrivateLinkResourceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "sharedPrivateLinkResourceValue") + +if err := client.SharedPrivateLinkResourcesDeleteThenPoll(ctx, id); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.SharedPrivateLinkResourcesGet` + +```go +ctx := context.TODO() +id := signalr.NewSharedPrivateLinkResourceID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue", "sharedPrivateLinkResourceValue") + +read, err := client.SharedPrivateLinkResourcesGet(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `SignalRClient.SharedPrivateLinkResourcesList` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +// alternatively `client.SharedPrivateLinkResourcesList(ctx, id)` can be used to do batched pagination +items, err := client.SharedPrivateLinkResourcesListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` + + +### Example Usage: `SignalRClient.Update` + +```go +ctx := context.TODO() +id := signalr.NewSignalRID("12345678-1234-9876-4563-123456789012", "example-resource-group", "resourceValue") + +payload := signalr.SignalRResource{ + // ... +} + + +if err := client.UpdateThenPoll(ctx, id, payload); err != nil { + // handle the error +} +``` + + +### Example Usage: `SignalRClient.UsagesList` + +```go +ctx := context.TODO() +id := signalr.NewLocationID("12345678-1234-9876-4563-123456789012", "locationValue") + +// alternatively `client.UsagesList(ctx, id)` can be used to do batched pagination +items, err := client.UsagesListComplete(ctx, id) +if err != nil { + // handle the error +} +for _, item := range items { + // do something +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/client.go new file mode 100644 index 000000000000..a0a2bfe8d75f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/client.go @@ -0,0 +1,18 @@ +package signalr + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRClient struct { + Client autorest.Client + baseUri string +} + +func NewSignalRClientWithBaseURI(endpoint string) SignalRClient { + return SignalRClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/constants.go new file mode 100644 index 000000000000..1319917bb216 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/constants.go @@ -0,0 +1,374 @@ +package signalr + +import "strings" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ACLAction string + +const ( + ACLActionAllow ACLAction = "Allow" + ACLActionDeny ACLAction = "Deny" +) + +func PossibleValuesForACLAction() []string { + return []string{ + string(ACLActionAllow), + string(ACLActionDeny), + } +} + +func parseACLAction(input string) (*ACLAction, error) { + vals := map[string]ACLAction{ + "allow": ACLActionAllow, + "deny": ACLActionDeny, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ACLAction(input) + return &out, nil +} + +type FeatureFlags string + +const ( + FeatureFlagsEnableConnectivityLogs FeatureFlags = "EnableConnectivityLogs" + FeatureFlagsEnableLiveTrace FeatureFlags = "EnableLiveTrace" + FeatureFlagsEnableMessagingLogs FeatureFlags = "EnableMessagingLogs" + FeatureFlagsServiceMode FeatureFlags = "ServiceMode" +) + +func PossibleValuesForFeatureFlags() []string { + return []string{ + string(FeatureFlagsEnableConnectivityLogs), + string(FeatureFlagsEnableLiveTrace), + string(FeatureFlagsEnableMessagingLogs), + string(FeatureFlagsServiceMode), + } +} + +func parseFeatureFlags(input string) (*FeatureFlags, error) { + vals := map[string]FeatureFlags{ + "enableconnectivitylogs": FeatureFlagsEnableConnectivityLogs, + "enablelivetrace": FeatureFlagsEnableLiveTrace, + "enablemessaginglogs": FeatureFlagsEnableMessagingLogs, + "servicemode": FeatureFlagsServiceMode, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := FeatureFlags(input) + return &out, nil +} + +type KeyType string + +const ( + KeyTypePrimary KeyType = "Primary" + KeyTypeSalt KeyType = "Salt" + KeyTypeSecondary KeyType = "Secondary" +) + +func PossibleValuesForKeyType() []string { + return []string{ + string(KeyTypePrimary), + string(KeyTypeSalt), + string(KeyTypeSecondary), + } +} + +func parseKeyType(input string) (*KeyType, error) { + vals := map[string]KeyType{ + "primary": KeyTypePrimary, + "salt": KeyTypeSalt, + "secondary": KeyTypeSecondary, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := KeyType(input) + return &out, nil +} + +type PrivateLinkServiceConnectionStatus string + +const ( + PrivateLinkServiceConnectionStatusApproved PrivateLinkServiceConnectionStatus = "Approved" + PrivateLinkServiceConnectionStatusDisconnected PrivateLinkServiceConnectionStatus = "Disconnected" + PrivateLinkServiceConnectionStatusPending PrivateLinkServiceConnectionStatus = "Pending" + PrivateLinkServiceConnectionStatusRejected PrivateLinkServiceConnectionStatus = "Rejected" +) + +func PossibleValuesForPrivateLinkServiceConnectionStatus() []string { + return []string{ + string(PrivateLinkServiceConnectionStatusApproved), + string(PrivateLinkServiceConnectionStatusDisconnected), + string(PrivateLinkServiceConnectionStatusPending), + string(PrivateLinkServiceConnectionStatusRejected), + } +} + +func parsePrivateLinkServiceConnectionStatus(input string) (*PrivateLinkServiceConnectionStatus, error) { + vals := map[string]PrivateLinkServiceConnectionStatus{ + "approved": PrivateLinkServiceConnectionStatusApproved, + "disconnected": PrivateLinkServiceConnectionStatusDisconnected, + "pending": PrivateLinkServiceConnectionStatusPending, + "rejected": PrivateLinkServiceConnectionStatusRejected, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := PrivateLinkServiceConnectionStatus(input) + return &out, nil +} + +type ProvisioningState string + +const ( + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateMoving ProvisioningState = "Moving" + ProvisioningStateRunning ProvisioningState = "Running" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUnknown ProvisioningState = "Unknown" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +func PossibleValuesForProvisioningState() []string { + return []string{ + string(ProvisioningStateCanceled), + string(ProvisioningStateCreating), + string(ProvisioningStateDeleting), + string(ProvisioningStateFailed), + string(ProvisioningStateMoving), + string(ProvisioningStateRunning), + string(ProvisioningStateSucceeded), + string(ProvisioningStateUnknown), + string(ProvisioningStateUpdating), + } +} + +func parseProvisioningState(input string) (*ProvisioningState, error) { + vals := map[string]ProvisioningState{ + "canceled": ProvisioningStateCanceled, + "creating": ProvisioningStateCreating, + "deleting": ProvisioningStateDeleting, + "failed": ProvisioningStateFailed, + "moving": ProvisioningStateMoving, + "running": ProvisioningStateRunning, + "succeeded": ProvisioningStateSucceeded, + "unknown": ProvisioningStateUnknown, + "updating": ProvisioningStateUpdating, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ProvisioningState(input) + return &out, nil +} + +type ScaleType string + +const ( + ScaleTypeAutomatic ScaleType = "Automatic" + ScaleTypeManual ScaleType = "Manual" + ScaleTypeNone ScaleType = "None" +) + +func PossibleValuesForScaleType() []string { + return []string{ + string(ScaleTypeAutomatic), + string(ScaleTypeManual), + string(ScaleTypeNone), + } +} + +func parseScaleType(input string) (*ScaleType, error) { + vals := map[string]ScaleType{ + "automatic": ScaleTypeAutomatic, + "manual": ScaleTypeManual, + "none": ScaleTypeNone, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ScaleType(input) + return &out, nil +} + +type ServiceKind string + +const ( + ServiceKindRawWebSockets ServiceKind = "RawWebSockets" + ServiceKindSignalR ServiceKind = "SignalR" +) + +func PossibleValuesForServiceKind() []string { + return []string{ + string(ServiceKindRawWebSockets), + string(ServiceKindSignalR), + } +} + +func parseServiceKind(input string) (*ServiceKind, error) { + vals := map[string]ServiceKind{ + "rawwebsockets": ServiceKindRawWebSockets, + "signalr": ServiceKindSignalR, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := ServiceKind(input) + return &out, nil +} + +type SharedPrivateLinkResourceStatus string + +const ( + SharedPrivateLinkResourceStatusApproved SharedPrivateLinkResourceStatus = "Approved" + SharedPrivateLinkResourceStatusDisconnected SharedPrivateLinkResourceStatus = "Disconnected" + SharedPrivateLinkResourceStatusPending SharedPrivateLinkResourceStatus = "Pending" + SharedPrivateLinkResourceStatusRejected SharedPrivateLinkResourceStatus = "Rejected" + SharedPrivateLinkResourceStatusTimeout SharedPrivateLinkResourceStatus = "Timeout" +) + +func PossibleValuesForSharedPrivateLinkResourceStatus() []string { + return []string{ + string(SharedPrivateLinkResourceStatusApproved), + string(SharedPrivateLinkResourceStatusDisconnected), + string(SharedPrivateLinkResourceStatusPending), + string(SharedPrivateLinkResourceStatusRejected), + string(SharedPrivateLinkResourceStatusTimeout), + } +} + +func parseSharedPrivateLinkResourceStatus(input string) (*SharedPrivateLinkResourceStatus, error) { + vals := map[string]SharedPrivateLinkResourceStatus{ + "approved": SharedPrivateLinkResourceStatusApproved, + "disconnected": SharedPrivateLinkResourceStatusDisconnected, + "pending": SharedPrivateLinkResourceStatusPending, + "rejected": SharedPrivateLinkResourceStatusRejected, + "timeout": SharedPrivateLinkResourceStatusTimeout, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := SharedPrivateLinkResourceStatus(input) + return &out, nil +} + +type SignalRRequestType string + +const ( + SignalRRequestTypeClientConnection SignalRRequestType = "ClientConnection" + SignalRRequestTypeRESTAPI SignalRRequestType = "RESTAPI" + SignalRRequestTypeServerConnection SignalRRequestType = "ServerConnection" + SignalRRequestTypeTrace SignalRRequestType = "Trace" +) + +func PossibleValuesForSignalRRequestType() []string { + return []string{ + string(SignalRRequestTypeClientConnection), + string(SignalRRequestTypeRESTAPI), + string(SignalRRequestTypeServerConnection), + string(SignalRRequestTypeTrace), + } +} + +func parseSignalRRequestType(input string) (*SignalRRequestType, error) { + vals := map[string]SignalRRequestType{ + "clientconnection": SignalRRequestTypeClientConnection, + "restapi": SignalRRequestTypeRESTAPI, + "serverconnection": SignalRRequestTypeServerConnection, + "trace": SignalRRequestTypeTrace, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := SignalRRequestType(input) + return &out, nil +} + +type SignalRSkuTier string + +const ( + SignalRSkuTierBasic SignalRSkuTier = "Basic" + SignalRSkuTierFree SignalRSkuTier = "Free" + SignalRSkuTierPremium SignalRSkuTier = "Premium" + SignalRSkuTierStandard SignalRSkuTier = "Standard" +) + +func PossibleValuesForSignalRSkuTier() []string { + return []string{ + string(SignalRSkuTierBasic), + string(SignalRSkuTierFree), + string(SignalRSkuTierPremium), + string(SignalRSkuTierStandard), + } +} + +func parseSignalRSkuTier(input string) (*SignalRSkuTier, error) { + vals := map[string]SignalRSkuTier{ + "basic": SignalRSkuTierBasic, + "free": SignalRSkuTierFree, + "premium": SignalRSkuTierPremium, + "standard": SignalRSkuTierStandard, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := SignalRSkuTier(input) + return &out, nil +} + +type UpstreamAuthType string + +const ( + UpstreamAuthTypeManagedIdentity UpstreamAuthType = "ManagedIdentity" + UpstreamAuthTypeNone UpstreamAuthType = "None" +) + +func PossibleValuesForUpstreamAuthType() []string { + return []string{ + string(UpstreamAuthTypeManagedIdentity), + string(UpstreamAuthTypeNone), + } +} + +func parseUpstreamAuthType(input string) (*UpstreamAuthType, error) { + vals := map[string]UpstreamAuthType{ + "managedidentity": UpstreamAuthTypeManagedIdentity, + "none": UpstreamAuthTypeNone, + } + if v, ok := vals[strings.ToLower(input)]; ok { + return &v, nil + } + + // otherwise presume it's an undefined value and best-effort it + out := UpstreamAuthType(input) + return &out, nil +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_customcertificate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_customcertificate.go new file mode 100644 index 000000000000..1d3417f59658 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_customcertificate.go @@ -0,0 +1,137 @@ +package signalr + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = CustomCertificateId{} + +// CustomCertificateId is a struct representing the Resource ID for a Custom Certificate +type CustomCertificateId struct { + SubscriptionId string + ResourceGroupName string + ResourceName string + CertificateName string +} + +// NewCustomCertificateID returns a new CustomCertificateId struct +func NewCustomCertificateID(subscriptionId string, resourceGroupName string, resourceName string, certificateName string) CustomCertificateId { + return CustomCertificateId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ResourceName: resourceName, + CertificateName: certificateName, + } +} + +// ParseCustomCertificateID parses 'input' into a CustomCertificateId +func ParseCustomCertificateID(input string) (*CustomCertificateId, error) { + parser := resourceids.NewParserFromResourceIdType(CustomCertificateId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := CustomCertificateId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + if id.CertificateName, ok = parsed.Parsed["certificateName"]; !ok { + return nil, fmt.Errorf("the segment 'certificateName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseCustomCertificateIDInsensitively parses 'input' case-insensitively into a CustomCertificateId +// note: this method should only be used for API response data and not user input +func ParseCustomCertificateIDInsensitively(input string) (*CustomCertificateId, error) { + parser := resourceids.NewParserFromResourceIdType(CustomCertificateId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := CustomCertificateId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + if id.CertificateName, ok = parsed.Parsed["certificateName"]; !ok { + return nil, fmt.Errorf("the segment 'certificateName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateCustomCertificateID checks that 'input' can be parsed as a Custom Certificate ID +func ValidateCustomCertificateID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseCustomCertificateID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Custom Certificate ID +func (id CustomCertificateId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/signalR/%s/customCertificates/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ResourceName, id.CertificateName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Custom Certificate ID +func (id CustomCertificateId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftSignalRService", "Microsoft.SignalRService", "Microsoft.SignalRService"), + resourceids.StaticSegment("staticSignalR", "signalR", "signalR"), + resourceids.UserSpecifiedSegment("resourceName", "resourceValue"), + resourceids.StaticSegment("staticCustomCertificates", "customCertificates", "customCertificates"), + resourceids.UserSpecifiedSegment("certificateName", "certificateValue"), + } +} + +// String returns a human-readable description of this Custom Certificate ID +func (id CustomCertificateId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Resource Name: %q", id.ResourceName), + fmt.Sprintf("Certificate Name: %q", id.CertificateName), + } + return fmt.Sprintf("Custom Certificate (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_customdomain.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_customdomain.go new file mode 100644 index 000000000000..f0b353171445 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_customdomain.go @@ -0,0 +1,137 @@ +package signalr + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = CustomDomainId{} + +// CustomDomainId is a struct representing the Resource ID for a Custom Domain +type CustomDomainId struct { + SubscriptionId string + ResourceGroupName string + ResourceName string + Name string +} + +// NewCustomDomainID returns a new CustomDomainId struct +func NewCustomDomainID(subscriptionId string, resourceGroupName string, resourceName string, name string) CustomDomainId { + return CustomDomainId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ResourceName: resourceName, + Name: name, + } +} + +// ParseCustomDomainID parses 'input' into a CustomDomainId +func ParseCustomDomainID(input string) (*CustomDomainId, error) { + parser := resourceids.NewParserFromResourceIdType(CustomDomainId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := CustomDomainId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + if id.Name, ok = parsed.Parsed["name"]; !ok { + return nil, fmt.Errorf("the segment 'name' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseCustomDomainIDInsensitively parses 'input' case-insensitively into a CustomDomainId +// note: this method should only be used for API response data and not user input +func ParseCustomDomainIDInsensitively(input string) (*CustomDomainId, error) { + parser := resourceids.NewParserFromResourceIdType(CustomDomainId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := CustomDomainId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + if id.Name, ok = parsed.Parsed["name"]; !ok { + return nil, fmt.Errorf("the segment 'name' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateCustomDomainID checks that 'input' can be parsed as a Custom Domain ID +func ValidateCustomDomainID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseCustomDomainID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Custom Domain ID +func (id CustomDomainId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/signalR/%s/customDomains/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ResourceName, id.Name) +} + +// Segments returns a slice of Resource ID Segments which comprise this Custom Domain ID +func (id CustomDomainId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftSignalRService", "Microsoft.SignalRService", "Microsoft.SignalRService"), + resourceids.StaticSegment("staticSignalR", "signalR", "signalR"), + resourceids.UserSpecifiedSegment("resourceName", "resourceValue"), + resourceids.StaticSegment("staticCustomDomains", "customDomains", "customDomains"), + resourceids.UserSpecifiedSegment("name", "nameValue"), + } +} + +// String returns a human-readable description of this Custom Domain ID +func (id CustomDomainId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Resource Name: %q", id.ResourceName), + fmt.Sprintf("Name: %q", id.Name), + } + return fmt.Sprintf("Custom Domain (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_location.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_location.go new file mode 100644 index 000000000000..d20f653e488e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_location.go @@ -0,0 +1,111 @@ +package signalr + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = LocationId{} + +// LocationId is a struct representing the Resource ID for a Location +type LocationId struct { + SubscriptionId string + Location string +} + +// NewLocationID returns a new LocationId struct +func NewLocationID(subscriptionId string, location string) LocationId { + return LocationId{ + SubscriptionId: subscriptionId, + Location: location, + } +} + +// ParseLocationID parses 'input' into a LocationId +func ParseLocationID(input string) (*LocationId, error) { + parser := resourceids.NewParserFromResourceIdType(LocationId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := LocationId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.Location, ok = parsed.Parsed["location"]; !ok { + return nil, fmt.Errorf("the segment 'location' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseLocationIDInsensitively parses 'input' case-insensitively into a LocationId +// note: this method should only be used for API response data and not user input +func ParseLocationIDInsensitively(input string) (*LocationId, error) { + parser := resourceids.NewParserFromResourceIdType(LocationId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := LocationId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.Location, ok = parsed.Parsed["location"]; !ok { + return nil, fmt.Errorf("the segment 'location' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateLocationID checks that 'input' can be parsed as a Location ID +func ValidateLocationID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseLocationID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Location ID +func (id LocationId) ID() string { + fmtString := "/subscriptions/%s/providers/Microsoft.SignalRService/locations/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.Location) +} + +// Segments returns a slice of Resource ID Segments which comprise this Location ID +func (id LocationId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftSignalRService", "Microsoft.SignalRService", "Microsoft.SignalRService"), + resourceids.StaticSegment("staticLocations", "locations", "locations"), + resourceids.UserSpecifiedSegment("location", "locationValue"), + } +} + +// String returns a human-readable description of this Location ID +func (id LocationId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Location: %q", id.Location), + } + return fmt.Sprintf("Location (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_privateendpointconnection.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_privateendpointconnection.go new file mode 100644 index 000000000000..c1d221118f15 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_privateendpointconnection.go @@ -0,0 +1,137 @@ +package signalr + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = PrivateEndpointConnectionId{} + +// PrivateEndpointConnectionId is a struct representing the Resource ID for a Private Endpoint Connection +type PrivateEndpointConnectionId struct { + SubscriptionId string + ResourceGroupName string + ResourceName string + PrivateEndpointConnectionName string +} + +// NewPrivateEndpointConnectionID returns a new PrivateEndpointConnectionId struct +func NewPrivateEndpointConnectionID(subscriptionId string, resourceGroupName string, resourceName string, privateEndpointConnectionName string) PrivateEndpointConnectionId { + return PrivateEndpointConnectionId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ResourceName: resourceName, + PrivateEndpointConnectionName: privateEndpointConnectionName, + } +} + +// ParsePrivateEndpointConnectionID parses 'input' into a PrivateEndpointConnectionId +func ParsePrivateEndpointConnectionID(input string) (*PrivateEndpointConnectionId, error) { + parser := resourceids.NewParserFromResourceIdType(PrivateEndpointConnectionId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := PrivateEndpointConnectionId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + if id.PrivateEndpointConnectionName, ok = parsed.Parsed["privateEndpointConnectionName"]; !ok { + return nil, fmt.Errorf("the segment 'privateEndpointConnectionName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParsePrivateEndpointConnectionIDInsensitively parses 'input' case-insensitively into a PrivateEndpointConnectionId +// note: this method should only be used for API response data and not user input +func ParsePrivateEndpointConnectionIDInsensitively(input string) (*PrivateEndpointConnectionId, error) { + parser := resourceids.NewParserFromResourceIdType(PrivateEndpointConnectionId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := PrivateEndpointConnectionId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + if id.PrivateEndpointConnectionName, ok = parsed.Parsed["privateEndpointConnectionName"]; !ok { + return nil, fmt.Errorf("the segment 'privateEndpointConnectionName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidatePrivateEndpointConnectionID checks that 'input' can be parsed as a Private Endpoint Connection ID +func ValidatePrivateEndpointConnectionID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParsePrivateEndpointConnectionID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Private Endpoint Connection ID +func (id PrivateEndpointConnectionId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/signalR/%s/privateEndpointConnections/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ResourceName, id.PrivateEndpointConnectionName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Private Endpoint Connection ID +func (id PrivateEndpointConnectionId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftSignalRService", "Microsoft.SignalRService", "Microsoft.SignalRService"), + resourceids.StaticSegment("staticSignalR", "signalR", "signalR"), + resourceids.UserSpecifiedSegment("resourceName", "resourceValue"), + resourceids.StaticSegment("staticPrivateEndpointConnections", "privateEndpointConnections", "privateEndpointConnections"), + resourceids.UserSpecifiedSegment("privateEndpointConnectionName", "privateEndpointConnectionValue"), + } +} + +// String returns a human-readable description of this Private Endpoint Connection ID +func (id PrivateEndpointConnectionId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Resource Name: %q", id.ResourceName), + fmt.Sprintf("Private Endpoint Connection Name: %q", id.PrivateEndpointConnectionName), + } + return fmt.Sprintf("Private Endpoint Connection (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_sharedprivatelinkresource.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_sharedprivatelinkresource.go new file mode 100644 index 000000000000..71f3719e21b0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_sharedprivatelinkresource.go @@ -0,0 +1,137 @@ +package signalr + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = SharedPrivateLinkResourceId{} + +// SharedPrivateLinkResourceId is a struct representing the Resource ID for a Shared Private Link Resource +type SharedPrivateLinkResourceId struct { + SubscriptionId string + ResourceGroupName string + ResourceName string + SharedPrivateLinkResourceName string +} + +// NewSharedPrivateLinkResourceID returns a new SharedPrivateLinkResourceId struct +func NewSharedPrivateLinkResourceID(subscriptionId string, resourceGroupName string, resourceName string, sharedPrivateLinkResourceName string) SharedPrivateLinkResourceId { + return SharedPrivateLinkResourceId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ResourceName: resourceName, + SharedPrivateLinkResourceName: sharedPrivateLinkResourceName, + } +} + +// ParseSharedPrivateLinkResourceID parses 'input' into a SharedPrivateLinkResourceId +func ParseSharedPrivateLinkResourceID(input string) (*SharedPrivateLinkResourceId, error) { + parser := resourceids.NewParserFromResourceIdType(SharedPrivateLinkResourceId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SharedPrivateLinkResourceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + if id.SharedPrivateLinkResourceName, ok = parsed.Parsed["sharedPrivateLinkResourceName"]; !ok { + return nil, fmt.Errorf("the segment 'sharedPrivateLinkResourceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseSharedPrivateLinkResourceIDInsensitively parses 'input' case-insensitively into a SharedPrivateLinkResourceId +// note: this method should only be used for API response data and not user input +func ParseSharedPrivateLinkResourceIDInsensitively(input string) (*SharedPrivateLinkResourceId, error) { + parser := resourceids.NewParserFromResourceIdType(SharedPrivateLinkResourceId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SharedPrivateLinkResourceId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + if id.SharedPrivateLinkResourceName, ok = parsed.Parsed["sharedPrivateLinkResourceName"]; !ok { + return nil, fmt.Errorf("the segment 'sharedPrivateLinkResourceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateSharedPrivateLinkResourceID checks that 'input' can be parsed as a Shared Private Link Resource ID +func ValidateSharedPrivateLinkResourceID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseSharedPrivateLinkResourceID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Shared Private Link Resource ID +func (id SharedPrivateLinkResourceId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/signalR/%s/sharedPrivateLinkResources/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ResourceName, id.SharedPrivateLinkResourceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Shared Private Link Resource ID +func (id SharedPrivateLinkResourceId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftSignalRService", "Microsoft.SignalRService", "Microsoft.SignalRService"), + resourceids.StaticSegment("staticSignalR", "signalR", "signalR"), + resourceids.UserSpecifiedSegment("resourceName", "resourceValue"), + resourceids.StaticSegment("staticSharedPrivateLinkResources", "sharedPrivateLinkResources", "sharedPrivateLinkResources"), + resourceids.UserSpecifiedSegment("sharedPrivateLinkResourceName", "sharedPrivateLinkResourceValue"), + } +} + +// String returns a human-readable description of this Shared Private Link Resource ID +func (id SharedPrivateLinkResourceId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Resource Name: %q", id.ResourceName), + fmt.Sprintf("Shared Private Link Resource Name: %q", id.SharedPrivateLinkResourceName), + } + return fmt.Sprintf("Shared Private Link Resource (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_signalr.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_signalr.go new file mode 100644 index 000000000000..93eac7234010 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/id_signalr.go @@ -0,0 +1,124 @@ +package signalr + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = SignalRId{} + +// SignalRId is a struct representing the Resource ID for a Signal R +type SignalRId struct { + SubscriptionId string + ResourceGroupName string + ResourceName string +} + +// NewSignalRID returns a new SignalRId struct +func NewSignalRID(subscriptionId string, resourceGroupName string, resourceName string) SignalRId { + return SignalRId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + ResourceName: resourceName, + } +} + +// ParseSignalRID parses 'input' into a SignalRId +func ParseSignalRID(input string) (*SignalRId, error) { + parser := resourceids.NewParserFromResourceIdType(SignalRId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SignalRId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseSignalRIDInsensitively parses 'input' case-insensitively into a SignalRId +// note: this method should only be used for API response data and not user input +func ParseSignalRIDInsensitively(input string) (*SignalRId, error) { + parser := resourceids.NewParserFromResourceIdType(SignalRId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := SignalRId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.ResourceName, ok = parsed.Parsed["resourceName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateSignalRID checks that 'input' can be parsed as a Signal R ID +func ValidateSignalRID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseSignalRID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Signal R ID +func (id SignalRId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/signalR/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ResourceName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Signal R ID +func (id SignalRId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftSignalRService", "Microsoft.SignalRService", "Microsoft.SignalRService"), + resourceids.StaticSegment("staticSignalR", "signalR", "signalR"), + resourceids.UserSpecifiedSegment("resourceName", "resourceValue"), + } +} + +// String returns a human-readable description of this Signal R ID +func (id SignalRId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Resource Name: %q", id.ResourceName), + } + return fmt.Sprintf("Signal R (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_checknameavailability_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_checknameavailability_autorest.go new file mode 100644 index 000000000000..b9753605c70b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_checknameavailability_autorest.go @@ -0,0 +1,69 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CheckNameAvailabilityOperationResponse struct { + HttpResponse *http.Response + Model *NameAvailability +} + +// CheckNameAvailability ... +func (c SignalRClient) CheckNameAvailability(ctx context.Context, id LocationId, input NameAvailabilityParameters) (result CheckNameAvailabilityOperationResponse, err error) { + req, err := c.preparerForCheckNameAvailability(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CheckNameAvailability", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCheckNameAvailability(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CheckNameAvailability", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCheckNameAvailability prepares the CheckNameAvailability request. +func (c SignalRClient) preparerForCheckNameAvailability(ctx context.Context, id LocationId, input NameAvailabilityParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/checkNameAvailability", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCheckNameAvailability handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForCheckNameAvailability(resp *http.Response) (result CheckNameAvailabilityOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_createorupdate_autorest.go new file mode 100644 index 000000000000..df51e499d01c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_createorupdate_autorest.go @@ -0,0 +1,79 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CreateOrUpdate ... +func (c SignalRClient) CreateOrUpdate(ctx context.Context, id SignalRId, input SignalRResource) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CreateOrUpdateThenPoll performs CreateOrUpdate then polls until it's completed +func (c SignalRClient) CreateOrUpdateThenPoll(ctx context.Context, id SignalRId, input SignalRResource) error { + result, err := c.CreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing CreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c SignalRClient) preparerForCreateOrUpdate(ctx context.Context, id SignalRId, input SignalRResource) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCreateOrUpdate sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForCreateOrUpdate(ctx context.Context, req *http.Request) (future CreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatescreateorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatescreateorupdate_autorest.go new file mode 100644 index 000000000000..ac74e2c8e929 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatescreateorupdate_autorest.go @@ -0,0 +1,79 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomCertificatesCreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CustomCertificatesCreateOrUpdate ... +func (c SignalRClient) CustomCertificatesCreateOrUpdate(ctx context.Context, id CustomCertificateId, input CustomCertificate) (result CustomCertificatesCreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCustomCertificatesCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesCreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForCustomCertificatesCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesCreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CustomCertificatesCreateOrUpdateThenPoll performs CustomCertificatesCreateOrUpdate then polls until it's completed +func (c SignalRClient) CustomCertificatesCreateOrUpdateThenPoll(ctx context.Context, id CustomCertificateId, input CustomCertificate) error { + result, err := c.CustomCertificatesCreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing CustomCertificatesCreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CustomCertificatesCreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForCustomCertificatesCreateOrUpdate prepares the CustomCertificatesCreateOrUpdate request. +func (c SignalRClient) preparerForCustomCertificatesCreateOrUpdate(ctx context.Context, id CustomCertificateId, input CustomCertificate) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCustomCertificatesCreateOrUpdate sends the CustomCertificatesCreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForCustomCertificatesCreateOrUpdate(ctx context.Context, req *http.Request) (future CustomCertificatesCreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatesdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatesdelete_autorest.go new file mode 100644 index 000000000000..d362f305bdde --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatesdelete_autorest.go @@ -0,0 +1,65 @@ +package signalr + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomCertificatesDeleteOperationResponse struct { + HttpResponse *http.Response +} + +// CustomCertificatesDelete ... +func (c SignalRClient) CustomCertificatesDelete(ctx context.Context, id CustomCertificateId) (result CustomCertificatesDeleteOperationResponse, err error) { + req, err := c.preparerForCustomCertificatesDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesDelete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesDelete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCustomCertificatesDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesDelete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCustomCertificatesDelete prepares the CustomCertificatesDelete request. +func (c SignalRClient) preparerForCustomCertificatesDelete(ctx context.Context, id CustomCertificateId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCustomCertificatesDelete handles the response to the CustomCertificatesDelete request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForCustomCertificatesDelete(resp *http.Response) (result CustomCertificatesDeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatesget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatesget_autorest.go new file mode 100644 index 000000000000..b61c0db86d0b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificatesget_autorest.go @@ -0,0 +1,67 @@ +package signalr + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomCertificatesGetOperationResponse struct { + HttpResponse *http.Response + Model *CustomCertificate +} + +// CustomCertificatesGet ... +func (c SignalRClient) CustomCertificatesGet(ctx context.Context, id CustomCertificateId) (result CustomCertificatesGetOperationResponse, err error) { + req, err := c.preparerForCustomCertificatesGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCustomCertificatesGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCustomCertificatesGet prepares the CustomCertificatesGet request. +func (c SignalRClient) preparerForCustomCertificatesGet(ctx context.Context, id CustomCertificateId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCustomCertificatesGet handles the response to the CustomCertificatesGet request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForCustomCertificatesGet(resp *http.Response) (result CustomCertificatesGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificateslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificateslist_autorest.go new file mode 100644 index 000000000000..70592ebc6c5a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customcertificateslist_autorest.go @@ -0,0 +1,186 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomCertificatesListOperationResponse struct { + HttpResponse *http.Response + Model *[]CustomCertificate + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (CustomCertificatesListOperationResponse, error) +} + +type CustomCertificatesListCompleteResult struct { + Items []CustomCertificate +} + +func (r CustomCertificatesListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r CustomCertificatesListOperationResponse) LoadMore(ctx context.Context) (resp CustomCertificatesListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// CustomCertificatesList ... +func (c SignalRClient) CustomCertificatesList(ctx context.Context, id SignalRId) (resp CustomCertificatesListOperationResponse, err error) { + req, err := c.preparerForCustomCertificatesList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForCustomCertificatesList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// CustomCertificatesListComplete retrieves all of the results into a single object +func (c SignalRClient) CustomCertificatesListComplete(ctx context.Context, id SignalRId) (CustomCertificatesListCompleteResult, error) { + return c.CustomCertificatesListCompleteMatchingPredicate(ctx, id, CustomCertificateOperationPredicate{}) +} + +// CustomCertificatesListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SignalRClient) CustomCertificatesListCompleteMatchingPredicate(ctx context.Context, id SignalRId, predicate CustomCertificateOperationPredicate) (resp CustomCertificatesListCompleteResult, err error) { + items := make([]CustomCertificate, 0) + + page, err := c.CustomCertificatesList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := CustomCertificatesListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForCustomCertificatesList prepares the CustomCertificatesList request. +func (c SignalRClient) preparerForCustomCertificatesList(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/customCertificates", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForCustomCertificatesListWithNextLink prepares the CustomCertificatesList request with the given nextLink token. +func (c SignalRClient) preparerForCustomCertificatesListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCustomCertificatesList handles the response to the CustomCertificatesList request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForCustomCertificatesList(resp *http.Response) (result CustomCertificatesListOperationResponse, err error) { + type page struct { + Values []CustomCertificate `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result CustomCertificatesListOperationResponse, err error) { + req, err := c.preparerForCustomCertificatesListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCustomCertificatesList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomCertificatesList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainscreateorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainscreateorupdate_autorest.go new file mode 100644 index 000000000000..3a7ac111f9b9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainscreateorupdate_autorest.go @@ -0,0 +1,79 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomDomainsCreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CustomDomainsCreateOrUpdate ... +func (c SignalRClient) CustomDomainsCreateOrUpdate(ctx context.Context, id CustomDomainId, input CustomDomain) (result CustomDomainsCreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCustomDomainsCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsCreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForCustomDomainsCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsCreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CustomDomainsCreateOrUpdateThenPoll performs CustomDomainsCreateOrUpdate then polls until it's completed +func (c SignalRClient) CustomDomainsCreateOrUpdateThenPoll(ctx context.Context, id CustomDomainId, input CustomDomain) error { + result, err := c.CustomDomainsCreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing CustomDomainsCreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CustomDomainsCreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForCustomDomainsCreateOrUpdate prepares the CustomDomainsCreateOrUpdate request. +func (c SignalRClient) preparerForCustomDomainsCreateOrUpdate(ctx context.Context, id CustomDomainId, input CustomDomain) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCustomDomainsCreateOrUpdate sends the CustomDomainsCreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForCustomDomainsCreateOrUpdate(ctx context.Context, req *http.Request) (future CustomDomainsCreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainsdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainsdelete_autorest.go new file mode 100644 index 000000000000..89e9169c92f0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainsdelete_autorest.go @@ -0,0 +1,78 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomDomainsDeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// CustomDomainsDelete ... +func (c SignalRClient) CustomDomainsDelete(ctx context.Context, id CustomDomainId) (result CustomDomainsDeleteOperationResponse, err error) { + req, err := c.preparerForCustomDomainsDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsDelete", nil, "Failure preparing request") + return + } + + result, err = c.senderForCustomDomainsDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsDelete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// CustomDomainsDeleteThenPoll performs CustomDomainsDelete then polls until it's completed +func (c SignalRClient) CustomDomainsDeleteThenPoll(ctx context.Context, id CustomDomainId) error { + result, err := c.CustomDomainsDelete(ctx, id) + if err != nil { + return fmt.Errorf("performing CustomDomainsDelete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after CustomDomainsDelete: %+v", err) + } + + return nil +} + +// preparerForCustomDomainsDelete prepares the CustomDomainsDelete request. +func (c SignalRClient) preparerForCustomDomainsDelete(ctx context.Context, id CustomDomainId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForCustomDomainsDelete sends the CustomDomainsDelete request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForCustomDomainsDelete(ctx context.Context, req *http.Request) (future CustomDomainsDeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainsget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainsget_autorest.go new file mode 100644 index 000000000000..11c780aed48b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainsget_autorest.go @@ -0,0 +1,67 @@ +package signalr + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomDomainsGetOperationResponse struct { + HttpResponse *http.Response + Model *CustomDomain +} + +// CustomDomainsGet ... +func (c SignalRClient) CustomDomainsGet(ctx context.Context, id CustomDomainId) (result CustomDomainsGetOperationResponse, err error) { + req, err := c.preparerForCustomDomainsGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCustomDomainsGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCustomDomainsGet prepares the CustomDomainsGet request. +func (c SignalRClient) preparerForCustomDomainsGet(ctx context.Context, id CustomDomainId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCustomDomainsGet handles the response to the CustomDomainsGet request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForCustomDomainsGet(resp *http.Response) (result CustomDomainsGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainslist_autorest.go new file mode 100644 index 000000000000..97d11162896b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_customdomainslist_autorest.go @@ -0,0 +1,186 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomDomainsListOperationResponse struct { + HttpResponse *http.Response + Model *[]CustomDomain + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (CustomDomainsListOperationResponse, error) +} + +type CustomDomainsListCompleteResult struct { + Items []CustomDomain +} + +func (r CustomDomainsListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r CustomDomainsListOperationResponse) LoadMore(ctx context.Context) (resp CustomDomainsListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// CustomDomainsList ... +func (c SignalRClient) CustomDomainsList(ctx context.Context, id SignalRId) (resp CustomDomainsListOperationResponse, err error) { + req, err := c.preparerForCustomDomainsList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForCustomDomainsList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// CustomDomainsListComplete retrieves all of the results into a single object +func (c SignalRClient) CustomDomainsListComplete(ctx context.Context, id SignalRId) (CustomDomainsListCompleteResult, error) { + return c.CustomDomainsListCompleteMatchingPredicate(ctx, id, CustomDomainOperationPredicate{}) +} + +// CustomDomainsListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SignalRClient) CustomDomainsListCompleteMatchingPredicate(ctx context.Context, id SignalRId, predicate CustomDomainOperationPredicate) (resp CustomDomainsListCompleteResult, err error) { + items := make([]CustomDomain, 0) + + page, err := c.CustomDomainsList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := CustomDomainsListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForCustomDomainsList prepares the CustomDomainsList request. +func (c SignalRClient) preparerForCustomDomainsList(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/customDomains", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForCustomDomainsListWithNextLink prepares the CustomDomainsList request with the given nextLink token. +func (c SignalRClient) preparerForCustomDomainsListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCustomDomainsList handles the response to the CustomDomainsList request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForCustomDomainsList(resp *http.Response) (result CustomDomainsListOperationResponse, err error) { + type page struct { + Values []CustomDomain `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result CustomDomainsListOperationResponse, err error) { + req, err := c.preparerForCustomDomainsListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCustomDomainsList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "CustomDomainsList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_delete_autorest.go new file mode 100644 index 000000000000..a0aa9b75e280 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_delete_autorest.go @@ -0,0 +1,78 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Delete ... +func (c SignalRClient) Delete(ctx context.Context, id SignalRId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = c.senderForDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// DeleteThenPoll performs Delete then polls until it's completed +func (c SignalRClient) DeleteThenPoll(ctx context.Context, id SignalRId) error { + result, err := c.Delete(ctx, id) + if err != nil { + return fmt.Errorf("performing Delete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Delete: %+v", err) + } + + return nil +} + +// preparerForDelete prepares the Delete request. +func (c SignalRClient) preparerForDelete(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForDelete sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForDelete(ctx context.Context, req *http.Request) (future DeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_get_autorest.go new file mode 100644 index 000000000000..d54b8ea530f9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_get_autorest.go @@ -0,0 +1,67 @@ +package signalr + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *SignalRResource +} + +// Get ... +func (c SignalRClient) Get(ctx context.Context, id SignalRId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c SignalRClient) preparerForGet(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listbyresourcegroup_autorest.go new file mode 100644 index 000000000000..d1bddeb41025 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listbyresourcegroup_autorest.go @@ -0,0 +1,187 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListByResourceGroupOperationResponse struct { + HttpResponse *http.Response + Model *[]SignalRResource + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListByResourceGroupOperationResponse, error) +} + +type ListByResourceGroupCompleteResult struct { + Items []SignalRResource +} + +func (r ListByResourceGroupOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ListByResourceGroupOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListByResourceGroup ... +func (c SignalRClient) ListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroup(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListByResourceGroup", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListByResourceGroup(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListByResourceGroup", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListByResourceGroupComplete retrieves all of the results into a single object +func (c SignalRClient) ListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ListByResourceGroupCompleteResult, error) { + return c.ListByResourceGroupCompleteMatchingPredicate(ctx, id, SignalRResourceOperationPredicate{}) +} + +// ListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SignalRClient) ListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate SignalRResourceOperationPredicate) (resp ListByResourceGroupCompleteResult, err error) { + items := make([]SignalRResource, 0) + + page, err := c.ListByResourceGroup(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListByResourceGroupCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListByResourceGroup prepares the ListByResourceGroup request. +func (c SignalRClient) preparerForListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.SignalRService/signalR", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListByResourceGroupWithNextLink prepares the ListByResourceGroup request with the given nextLink token. +func (c SignalRClient) preparerForListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListByResourceGroup handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForListByResourceGroup(resp *http.Response) (result ListByResourceGroupOperationResponse, err error) { + type page struct { + Values []SignalRResource `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByResourceGroupOperationResponse, err error) { + req, err := c.preparerForListByResourceGroupWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListByResourceGroup", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListByResourceGroup(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListByResourceGroup", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listbysubscription_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listbysubscription_autorest.go new file mode 100644 index 000000000000..0685a9f3b122 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listbysubscription_autorest.go @@ -0,0 +1,187 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListBySubscriptionOperationResponse struct { + HttpResponse *http.Response + Model *[]SignalRResource + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (ListBySubscriptionOperationResponse, error) +} + +type ListBySubscriptionCompleteResult struct { + Items []SignalRResource +} + +func (r ListBySubscriptionOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r ListBySubscriptionOperationResponse) LoadMore(ctx context.Context) (resp ListBySubscriptionOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// ListBySubscription ... +func (c SignalRClient) ListBySubscription(ctx context.Context, id commonids.SubscriptionId) (resp ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscription(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListBySubscription", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForListBySubscription(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListBySubscription", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// ListBySubscriptionComplete retrieves all of the results into a single object +func (c SignalRClient) ListBySubscriptionComplete(ctx context.Context, id commonids.SubscriptionId) (ListBySubscriptionCompleteResult, error) { + return c.ListBySubscriptionCompleteMatchingPredicate(ctx, id, SignalRResourceOperationPredicate{}) +} + +// ListBySubscriptionCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SignalRClient) ListBySubscriptionCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate SignalRResourceOperationPredicate) (resp ListBySubscriptionCompleteResult, err error) { + items := make([]SignalRResource, 0) + + page, err := c.ListBySubscription(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := ListBySubscriptionCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForListBySubscription prepares the ListBySubscription request. +func (c SignalRClient) preparerForListBySubscription(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.SignalRService/signalR", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForListBySubscriptionWithNextLink prepares the ListBySubscription request with the given nextLink token. +func (c SignalRClient) preparerForListBySubscriptionWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListBySubscription handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForListBySubscription(resp *http.Response) (result ListBySubscriptionOperationResponse, err error) { + type page struct { + Values []SignalRResource `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListBySubscriptionOperationResponse, err error) { + req, err := c.preparerForListBySubscriptionWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListBySubscription", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListBySubscription(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListBySubscription", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listkeys_autorest.go new file mode 100644 index 000000000000..addf72c34999 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listkeys_autorest.go @@ -0,0 +1,68 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListKeysOperationResponse struct { + HttpResponse *http.Response + Model *SignalRKeys +} + +// ListKeys ... +func (c SignalRClient) ListKeys(ctx context.Context, id SignalRId) (result ListKeysOperationResponse, err error) { + req, err := c.preparerForListKeys(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListKeys", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListKeys", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListKeys(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListKeys", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForListKeys prepares the ListKeys request. +func (c SignalRClient) preparerForListKeys(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListKeys handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForListKeys(resp *http.Response) (result ListKeysOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listskus_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listskus_autorest.go new file mode 100644 index 000000000000..e3cb6e56b81c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_listskus_autorest.go @@ -0,0 +1,68 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListSkusOperationResponse struct { + HttpResponse *http.Response + Model *SkuList +} + +// ListSkus ... +func (c SignalRClient) ListSkus(ctx context.Context, id SignalRId) (result ListSkusOperationResponse, err error) { + req, err := c.preparerForListSkus(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListSkus", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListSkus", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForListSkus(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "ListSkus", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForListSkus prepares the ListSkus request. +func (c SignalRClient) preparerForListSkus(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/skus", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForListSkus handles the response to the ListSkus request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForListSkus(resp *http.Response) (result ListSkusOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsdelete_autorest.go new file mode 100644 index 000000000000..73899e288520 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsdelete_autorest.go @@ -0,0 +1,78 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionsDeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// PrivateEndpointConnectionsDelete ... +func (c SignalRClient) PrivateEndpointConnectionsDelete(ctx context.Context, id PrivateEndpointConnectionId) (result PrivateEndpointConnectionsDeleteOperationResponse, err error) { + req, err := c.preparerForPrivateEndpointConnectionsDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsDelete", nil, "Failure preparing request") + return + } + + result, err = c.senderForPrivateEndpointConnectionsDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsDelete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// PrivateEndpointConnectionsDeleteThenPoll performs PrivateEndpointConnectionsDelete then polls until it's completed +func (c SignalRClient) PrivateEndpointConnectionsDeleteThenPoll(ctx context.Context, id PrivateEndpointConnectionId) error { + result, err := c.PrivateEndpointConnectionsDelete(ctx, id) + if err != nil { + return fmt.Errorf("performing PrivateEndpointConnectionsDelete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after PrivateEndpointConnectionsDelete: %+v", err) + } + + return nil +} + +// preparerForPrivateEndpointConnectionsDelete prepares the PrivateEndpointConnectionsDelete request. +func (c SignalRClient) preparerForPrivateEndpointConnectionsDelete(ctx context.Context, id PrivateEndpointConnectionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForPrivateEndpointConnectionsDelete sends the PrivateEndpointConnectionsDelete request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForPrivateEndpointConnectionsDelete(ctx context.Context, req *http.Request) (future PrivateEndpointConnectionsDeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsget_autorest.go new file mode 100644 index 000000000000..bebe6f03b070 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsget_autorest.go @@ -0,0 +1,67 @@ +package signalr + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionsGetOperationResponse struct { + HttpResponse *http.Response + Model *PrivateEndpointConnection +} + +// PrivateEndpointConnectionsGet ... +func (c SignalRClient) PrivateEndpointConnectionsGet(ctx context.Context, id PrivateEndpointConnectionId) (result PrivateEndpointConnectionsGetOperationResponse, err error) { + req, err := c.preparerForPrivateEndpointConnectionsGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForPrivateEndpointConnectionsGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForPrivateEndpointConnectionsGet prepares the PrivateEndpointConnectionsGet request. +func (c SignalRClient) preparerForPrivateEndpointConnectionsGet(ctx context.Context, id PrivateEndpointConnectionId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForPrivateEndpointConnectionsGet handles the response to the PrivateEndpointConnectionsGet request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForPrivateEndpointConnectionsGet(resp *http.Response) (result PrivateEndpointConnectionsGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionslist_autorest.go new file mode 100644 index 000000000000..9341a17127b2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionslist_autorest.go @@ -0,0 +1,186 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionsListOperationResponse struct { + HttpResponse *http.Response + Model *[]PrivateEndpointConnection + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (PrivateEndpointConnectionsListOperationResponse, error) +} + +type PrivateEndpointConnectionsListCompleteResult struct { + Items []PrivateEndpointConnection +} + +func (r PrivateEndpointConnectionsListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r PrivateEndpointConnectionsListOperationResponse) LoadMore(ctx context.Context) (resp PrivateEndpointConnectionsListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// PrivateEndpointConnectionsList ... +func (c SignalRClient) PrivateEndpointConnectionsList(ctx context.Context, id SignalRId) (resp PrivateEndpointConnectionsListOperationResponse, err error) { + req, err := c.preparerForPrivateEndpointConnectionsList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForPrivateEndpointConnectionsList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// PrivateEndpointConnectionsListComplete retrieves all of the results into a single object +func (c SignalRClient) PrivateEndpointConnectionsListComplete(ctx context.Context, id SignalRId) (PrivateEndpointConnectionsListCompleteResult, error) { + return c.PrivateEndpointConnectionsListCompleteMatchingPredicate(ctx, id, PrivateEndpointConnectionOperationPredicate{}) +} + +// PrivateEndpointConnectionsListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SignalRClient) PrivateEndpointConnectionsListCompleteMatchingPredicate(ctx context.Context, id SignalRId, predicate PrivateEndpointConnectionOperationPredicate) (resp PrivateEndpointConnectionsListCompleteResult, err error) { + items := make([]PrivateEndpointConnection, 0) + + page, err := c.PrivateEndpointConnectionsList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := PrivateEndpointConnectionsListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForPrivateEndpointConnectionsList prepares the PrivateEndpointConnectionsList request. +func (c SignalRClient) preparerForPrivateEndpointConnectionsList(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/privateEndpointConnections", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForPrivateEndpointConnectionsListWithNextLink prepares the PrivateEndpointConnectionsList request with the given nextLink token. +func (c SignalRClient) preparerForPrivateEndpointConnectionsListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForPrivateEndpointConnectionsList handles the response to the PrivateEndpointConnectionsList request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForPrivateEndpointConnectionsList(resp *http.Response) (result PrivateEndpointConnectionsListOperationResponse, err error) { + type page struct { + Values []PrivateEndpointConnection `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result PrivateEndpointConnectionsListOperationResponse, err error) { + req, err := c.preparerForPrivateEndpointConnectionsListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForPrivateEndpointConnectionsList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsupdate_autorest.go new file mode 100644 index 000000000000..858b9c3ee737 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privateendpointconnectionsupdate_autorest.go @@ -0,0 +1,68 @@ +package signalr + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionsUpdateOperationResponse struct { + HttpResponse *http.Response + Model *PrivateEndpointConnection +} + +// PrivateEndpointConnectionsUpdate ... +func (c SignalRClient) PrivateEndpointConnectionsUpdate(ctx context.Context, id PrivateEndpointConnectionId, input PrivateEndpointConnection) (result PrivateEndpointConnectionsUpdateOperationResponse, err error) { + req, err := c.preparerForPrivateEndpointConnectionsUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForPrivateEndpointConnectionsUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateEndpointConnectionsUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForPrivateEndpointConnectionsUpdate prepares the PrivateEndpointConnectionsUpdate request. +func (c SignalRClient) preparerForPrivateEndpointConnectionsUpdate(ctx context.Context, id PrivateEndpointConnectionId, input PrivateEndpointConnection) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForPrivateEndpointConnectionsUpdate handles the response to the PrivateEndpointConnectionsUpdate request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForPrivateEndpointConnectionsUpdate(resp *http.Response) (result PrivateEndpointConnectionsUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privatelinkresourceslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privatelinkresourceslist_autorest.go new file mode 100644 index 000000000000..4bd2c25e5316 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_privatelinkresourceslist_autorest.go @@ -0,0 +1,186 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateLinkResourcesListOperationResponse struct { + HttpResponse *http.Response + Model *[]PrivateLinkResource + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (PrivateLinkResourcesListOperationResponse, error) +} + +type PrivateLinkResourcesListCompleteResult struct { + Items []PrivateLinkResource +} + +func (r PrivateLinkResourcesListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r PrivateLinkResourcesListOperationResponse) LoadMore(ctx context.Context) (resp PrivateLinkResourcesListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// PrivateLinkResourcesList ... +func (c SignalRClient) PrivateLinkResourcesList(ctx context.Context, id SignalRId) (resp PrivateLinkResourcesListOperationResponse, err error) { + req, err := c.preparerForPrivateLinkResourcesList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateLinkResourcesList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateLinkResourcesList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForPrivateLinkResourcesList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateLinkResourcesList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// PrivateLinkResourcesListComplete retrieves all of the results into a single object +func (c SignalRClient) PrivateLinkResourcesListComplete(ctx context.Context, id SignalRId) (PrivateLinkResourcesListCompleteResult, error) { + return c.PrivateLinkResourcesListCompleteMatchingPredicate(ctx, id, PrivateLinkResourceOperationPredicate{}) +} + +// PrivateLinkResourcesListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SignalRClient) PrivateLinkResourcesListCompleteMatchingPredicate(ctx context.Context, id SignalRId, predicate PrivateLinkResourceOperationPredicate) (resp PrivateLinkResourcesListCompleteResult, err error) { + items := make([]PrivateLinkResource, 0) + + page, err := c.PrivateLinkResourcesList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := PrivateLinkResourcesListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForPrivateLinkResourcesList prepares the PrivateLinkResourcesList request. +func (c SignalRClient) preparerForPrivateLinkResourcesList(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/privateLinkResources", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForPrivateLinkResourcesListWithNextLink prepares the PrivateLinkResourcesList request with the given nextLink token. +func (c SignalRClient) preparerForPrivateLinkResourcesListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForPrivateLinkResourcesList handles the response to the PrivateLinkResourcesList request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForPrivateLinkResourcesList(resp *http.Response) (result PrivateLinkResourcesListOperationResponse, err error) { + type page struct { + Values []PrivateLinkResource `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result PrivateLinkResourcesListOperationResponse, err error) { + req, err := c.preparerForPrivateLinkResourcesListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateLinkResourcesList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateLinkResourcesList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForPrivateLinkResourcesList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "PrivateLinkResourcesList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_regeneratekey_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_regeneratekey_autorest.go new file mode 100644 index 000000000000..493d3dc9684f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_regeneratekey_autorest.go @@ -0,0 +1,79 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateKeyOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// RegenerateKey ... +func (c SignalRClient) RegenerateKey(ctx context.Context, id SignalRId, input RegenerateKeyParameters) (result RegenerateKeyOperationResponse, err error) { + req, err := c.preparerForRegenerateKey(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "RegenerateKey", nil, "Failure preparing request") + return + } + + result, err = c.senderForRegenerateKey(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "RegenerateKey", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// RegenerateKeyThenPoll performs RegenerateKey then polls until it's completed +func (c SignalRClient) RegenerateKeyThenPoll(ctx context.Context, id SignalRId, input RegenerateKeyParameters) error { + result, err := c.RegenerateKey(ctx, id, input) + if err != nil { + return fmt.Errorf("performing RegenerateKey: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after RegenerateKey: %+v", err) + } + + return nil +} + +// preparerForRegenerateKey prepares the RegenerateKey request. +func (c SignalRClient) preparerForRegenerateKey(ctx context.Context, id SignalRId, input RegenerateKeyParameters) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/regenerateKey", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForRegenerateKey sends the RegenerateKey request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForRegenerateKey(ctx context.Context, req *http.Request) (future RegenerateKeyOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_restart_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_restart_autorest.go new file mode 100644 index 000000000000..c1d9ae14be6e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_restart_autorest.go @@ -0,0 +1,78 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RestartOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Restart ... +func (c SignalRClient) Restart(ctx context.Context, id SignalRId) (result RestartOperationResponse, err error) { + req, err := c.preparerForRestart(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "Restart", nil, "Failure preparing request") + return + } + + result, err = c.senderForRestart(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "Restart", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// RestartThenPoll performs Restart then polls until it's completed +func (c SignalRClient) RestartThenPoll(ctx context.Context, id SignalRId) error { + result, err := c.Restart(ctx, id) + if err != nil { + return fmt.Errorf("performing Restart: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Restart: %+v", err) + } + + return nil +} + +// preparerForRestart prepares the Restart request. +func (c SignalRClient) preparerForRestart(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/restart", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForRestart sends the Restart request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForRestart(ctx context.Context, req *http.Request) (future RestartOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcescreateorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcescreateorupdate_autorest.go new file mode 100644 index 000000000000..bc806a9b73d7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcescreateorupdate_autorest.go @@ -0,0 +1,79 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SharedPrivateLinkResourcesCreateOrUpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// SharedPrivateLinkResourcesCreateOrUpdate ... +func (c SignalRClient) SharedPrivateLinkResourcesCreateOrUpdate(ctx context.Context, id SharedPrivateLinkResourceId, input SharedPrivateLinkResource) (result SharedPrivateLinkResourcesCreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForSharedPrivateLinkResourcesCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesCreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = c.senderForSharedPrivateLinkResourcesCreateOrUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesCreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// SharedPrivateLinkResourcesCreateOrUpdateThenPoll performs SharedPrivateLinkResourcesCreateOrUpdate then polls until it's completed +func (c SignalRClient) SharedPrivateLinkResourcesCreateOrUpdateThenPoll(ctx context.Context, id SharedPrivateLinkResourceId, input SharedPrivateLinkResource) error { + result, err := c.SharedPrivateLinkResourcesCreateOrUpdate(ctx, id, input) + if err != nil { + return fmt.Errorf("performing SharedPrivateLinkResourcesCreateOrUpdate: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after SharedPrivateLinkResourcesCreateOrUpdate: %+v", err) + } + + return nil +} + +// preparerForSharedPrivateLinkResourcesCreateOrUpdate prepares the SharedPrivateLinkResourcesCreateOrUpdate request. +func (c SignalRClient) preparerForSharedPrivateLinkResourcesCreateOrUpdate(ctx context.Context, id SharedPrivateLinkResourceId, input SharedPrivateLinkResource) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForSharedPrivateLinkResourcesCreateOrUpdate sends the SharedPrivateLinkResourcesCreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForSharedPrivateLinkResourcesCreateOrUpdate(ctx context.Context, req *http.Request) (future SharedPrivateLinkResourcesCreateOrUpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcesdelete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcesdelete_autorest.go new file mode 100644 index 000000000000..94f01fed123f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcesdelete_autorest.go @@ -0,0 +1,78 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SharedPrivateLinkResourcesDeleteOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// SharedPrivateLinkResourcesDelete ... +func (c SignalRClient) SharedPrivateLinkResourcesDelete(ctx context.Context, id SharedPrivateLinkResourceId) (result SharedPrivateLinkResourcesDeleteOperationResponse, err error) { + req, err := c.preparerForSharedPrivateLinkResourcesDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesDelete", nil, "Failure preparing request") + return + } + + result, err = c.senderForSharedPrivateLinkResourcesDelete(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesDelete", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// SharedPrivateLinkResourcesDeleteThenPoll performs SharedPrivateLinkResourcesDelete then polls until it's completed +func (c SignalRClient) SharedPrivateLinkResourcesDeleteThenPoll(ctx context.Context, id SharedPrivateLinkResourceId) error { + result, err := c.SharedPrivateLinkResourcesDelete(ctx, id) + if err != nil { + return fmt.Errorf("performing SharedPrivateLinkResourcesDelete: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after SharedPrivateLinkResourcesDelete: %+v", err) + } + + return nil +} + +// preparerForSharedPrivateLinkResourcesDelete prepares the SharedPrivateLinkResourcesDelete request. +func (c SignalRClient) preparerForSharedPrivateLinkResourcesDelete(ctx context.Context, id SharedPrivateLinkResourceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForSharedPrivateLinkResourcesDelete sends the SharedPrivateLinkResourcesDelete request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForSharedPrivateLinkResourcesDelete(ctx context.Context, req *http.Request) (future SharedPrivateLinkResourcesDeleteOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcesget_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcesget_autorest.go new file mode 100644 index 000000000000..ba463f54a3de --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourcesget_autorest.go @@ -0,0 +1,67 @@ +package signalr + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SharedPrivateLinkResourcesGetOperationResponse struct { + HttpResponse *http.Response + Model *SharedPrivateLinkResource +} + +// SharedPrivateLinkResourcesGet ... +func (c SignalRClient) SharedPrivateLinkResourcesGet(ctx context.Context, id SharedPrivateLinkResourceId) (result SharedPrivateLinkResourcesGetOperationResponse, err error) { + req, err := c.preparerForSharedPrivateLinkResourcesGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesGet", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesGet", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForSharedPrivateLinkResourcesGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesGet", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForSharedPrivateLinkResourcesGet prepares the SharedPrivateLinkResourcesGet request. +func (c SignalRClient) preparerForSharedPrivateLinkResourcesGet(ctx context.Context, id SharedPrivateLinkResourceId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForSharedPrivateLinkResourcesGet handles the response to the SharedPrivateLinkResourcesGet request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForSharedPrivateLinkResourcesGet(resp *http.Response) (result SharedPrivateLinkResourcesGetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourceslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourceslist_autorest.go new file mode 100644 index 000000000000..503b76457586 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_sharedprivatelinkresourceslist_autorest.go @@ -0,0 +1,186 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SharedPrivateLinkResourcesListOperationResponse struct { + HttpResponse *http.Response + Model *[]SharedPrivateLinkResource + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (SharedPrivateLinkResourcesListOperationResponse, error) +} + +type SharedPrivateLinkResourcesListCompleteResult struct { + Items []SharedPrivateLinkResource +} + +func (r SharedPrivateLinkResourcesListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r SharedPrivateLinkResourcesListOperationResponse) LoadMore(ctx context.Context) (resp SharedPrivateLinkResourcesListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// SharedPrivateLinkResourcesList ... +func (c SignalRClient) SharedPrivateLinkResourcesList(ctx context.Context, id SignalRId) (resp SharedPrivateLinkResourcesListOperationResponse, err error) { + req, err := c.preparerForSharedPrivateLinkResourcesList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForSharedPrivateLinkResourcesList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// SharedPrivateLinkResourcesListComplete retrieves all of the results into a single object +func (c SignalRClient) SharedPrivateLinkResourcesListComplete(ctx context.Context, id SignalRId) (SharedPrivateLinkResourcesListCompleteResult, error) { + return c.SharedPrivateLinkResourcesListCompleteMatchingPredicate(ctx, id, SharedPrivateLinkResourceOperationPredicate{}) +} + +// SharedPrivateLinkResourcesListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SignalRClient) SharedPrivateLinkResourcesListCompleteMatchingPredicate(ctx context.Context, id SignalRId, predicate SharedPrivateLinkResourceOperationPredicate) (resp SharedPrivateLinkResourcesListCompleteResult, err error) { + items := make([]SharedPrivateLinkResource, 0) + + page, err := c.SharedPrivateLinkResourcesList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := SharedPrivateLinkResourcesListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForSharedPrivateLinkResourcesList prepares the SharedPrivateLinkResourcesList request. +func (c SignalRClient) preparerForSharedPrivateLinkResourcesList(ctx context.Context, id SignalRId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/sharedPrivateLinkResources", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForSharedPrivateLinkResourcesListWithNextLink prepares the SharedPrivateLinkResourcesList request with the given nextLink token. +func (c SignalRClient) preparerForSharedPrivateLinkResourcesListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForSharedPrivateLinkResourcesList handles the response to the SharedPrivateLinkResourcesList request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForSharedPrivateLinkResourcesList(resp *http.Response) (result SharedPrivateLinkResourcesListOperationResponse, err error) { + type page struct { + Values []SharedPrivateLinkResource `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result SharedPrivateLinkResourcesListOperationResponse, err error) { + req, err := c.preparerForSharedPrivateLinkResourcesListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForSharedPrivateLinkResourcesList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "SharedPrivateLinkResourcesList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_update_autorest.go new file mode 100644 index 000000000000..f90077a5bf53 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_update_autorest.go @@ -0,0 +1,79 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/go-azure-helpers/polling" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpdateOperationResponse struct { + Poller polling.LongRunningPoller + HttpResponse *http.Response +} + +// Update ... +func (c SignalRClient) Update(ctx context.Context, id SignalRId, input SignalRResource) (result UpdateOperationResponse, err error) { + req, err := c.preparerForUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "Update", nil, "Failure preparing request") + return + } + + result, err = c.senderForUpdate(ctx, req) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "Update", result.HttpResponse, "Failure sending request") + return + } + + return +} + +// UpdateThenPoll performs Update then polls until it's completed +func (c SignalRClient) UpdateThenPoll(ctx context.Context, id SignalRId, input SignalRResource) error { + result, err := c.Update(ctx, id, input) + if err != nil { + return fmt.Errorf("performing Update: %+v", err) + } + + if err := result.Poller.PollUntilDone(); err != nil { + return fmt.Errorf("polling after Update: %+v", err) + } + + return nil +} + +// preparerForUpdate prepares the Update request. +func (c SignalRClient) preparerForUpdate(ctx context.Context, id SignalRId, input SignalRResource) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// senderForUpdate sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (c SignalRClient) senderForUpdate(ctx context.Context, req *http.Request) (future UpdateOperationResponse, err error) { + var resp *http.Response + resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + return + } + + future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_usageslist_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_usageslist_autorest.go new file mode 100644 index 000000000000..081740d059e2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/method_usageslist_autorest.go @@ -0,0 +1,186 @@ +package signalr + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UsagesListOperationResponse struct { + HttpResponse *http.Response + Model *[]SignalRUsage + + nextLink *string + nextPageFunc func(ctx context.Context, nextLink string) (UsagesListOperationResponse, error) +} + +type UsagesListCompleteResult struct { + Items []SignalRUsage +} + +func (r UsagesListOperationResponse) HasMore() bool { + return r.nextLink != nil +} + +func (r UsagesListOperationResponse) LoadMore(ctx context.Context) (resp UsagesListOperationResponse, err error) { + if !r.HasMore() { + err = fmt.Errorf("no more pages returned") + return + } + return r.nextPageFunc(ctx, *r.nextLink) +} + +// UsagesList ... +func (c SignalRClient) UsagesList(ctx context.Context, id LocationId) (resp UsagesListOperationResponse, err error) { + req, err := c.preparerForUsagesList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "UsagesList", nil, "Failure preparing request") + return + } + + resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "UsagesList", resp.HttpResponse, "Failure sending request") + return + } + + resp, err = c.responderForUsagesList(resp.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "UsagesList", resp.HttpResponse, "Failure responding to request") + return + } + return +} + +// UsagesListComplete retrieves all of the results into a single object +func (c SignalRClient) UsagesListComplete(ctx context.Context, id LocationId) (UsagesListCompleteResult, error) { + return c.UsagesListCompleteMatchingPredicate(ctx, id, SignalRUsageOperationPredicate{}) +} + +// UsagesListCompleteMatchingPredicate retrieves all of the results and then applied the predicate +func (c SignalRClient) UsagesListCompleteMatchingPredicate(ctx context.Context, id LocationId, predicate SignalRUsageOperationPredicate) (resp UsagesListCompleteResult, err error) { + items := make([]SignalRUsage, 0) + + page, err := c.UsagesList(ctx, id) + if err != nil { + err = fmt.Errorf("loading the initial page: %+v", err) + return + } + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + + for page.HasMore() { + page, err = page.LoadMore(ctx) + if err != nil { + err = fmt.Errorf("loading the next page: %+v", err) + return + } + + if page.Model != nil { + for _, v := range *page.Model { + if predicate.Matches(v) { + items = append(items, v) + } + } + } + } + + out := UsagesListCompleteResult{ + Items: items, + } + return out, nil +} + +// preparerForUsagesList prepares the UsagesList request. +func (c SignalRClient) preparerForUsagesList(ctx context.Context, id LocationId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/usages", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// preparerForUsagesListWithNextLink prepares the UsagesList request with the given nextLink token. +func (c SignalRClient) preparerForUsagesListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { + uri, err := url.Parse(nextLink) + if err != nil { + return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) + } + queryParameters := map[string]interface{}{} + for k, v := range uri.Query() { + if len(v) == 0 { + continue + } + val := v[0] + val = autorest.Encode("query", val) + queryParameters[k] = val + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(uri.Path), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForUsagesList handles the response to the UsagesList request. The method always +// closes the http.Response Body. +func (c SignalRClient) responderForUsagesList(resp *http.Response) (result UsagesListOperationResponse, err error) { + type page struct { + Values []SignalRUsage `json:"value"` + NextLink *string `json:"nextLink"` + } + var respObj page + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&respObj), + autorest.ByClosing()) + result.HttpResponse = resp + result.Model = &respObj.Values + result.nextLink = respObj.NextLink + if respObj.NextLink != nil { + result.nextPageFunc = func(ctx context.Context, nextLink string) (result UsagesListOperationResponse, err error) { + req, err := c.preparerForUsagesListWithNextLink(ctx, nextLink) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "UsagesList", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "UsagesList", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForUsagesList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "signalr.SignalRClient", "UsagesList", result.HttpResponse, "Failure responding to request") + return + } + + return + } + } + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customcertificate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customcertificate.go new file mode 100644 index 000000000000..d6ff9633aa07 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customcertificate.go @@ -0,0 +1,16 @@ +package signalr + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomCertificate struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties CustomCertificateProperties `json:"properties"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customcertificateproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customcertificateproperties.go new file mode 100644 index 000000000000..95b0e37cbc8d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customcertificateproperties.go @@ -0,0 +1,11 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomCertificateProperties struct { + KeyVaultBaseUri string `json:"keyVaultBaseUri"` + KeyVaultSecretName string `json:"keyVaultSecretName"` + KeyVaultSecretVersion *string `json:"keyVaultSecretVersion,omitempty"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customdomain.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customdomain.go new file mode 100644 index 000000000000..07cf8a4002ee --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customdomain.go @@ -0,0 +1,16 @@ +package signalr + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomDomain struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties CustomDomainProperties `json:"properties"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customdomainproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customdomainproperties.go new file mode 100644 index 000000000000..c084ddc8155e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_customdomainproperties.go @@ -0,0 +1,10 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CustomDomainProperties struct { + CustomCertificate ResourceReference `json:"customCertificate"` + DomainName string `json:"domainName"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_livetracecategory.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_livetracecategory.go new file mode 100644 index 000000000000..eaf0b128ba77 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_livetracecategory.go @@ -0,0 +1,9 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type LiveTraceCategory struct { + Enabled *string `json:"enabled,omitempty"` + Name *string `json:"name,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_livetraceconfiguration.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_livetraceconfiguration.go new file mode 100644 index 000000000000..62766225faf7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_livetraceconfiguration.go @@ -0,0 +1,9 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type LiveTraceConfiguration struct { + Categories *[]LiveTraceCategory `json:"categories,omitempty"` + Enabled *string `json:"enabled,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_managedidentitysettings.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_managedidentitysettings.go new file mode 100644 index 000000000000..05ada7009e8b --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_managedidentitysettings.go @@ -0,0 +1,8 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ManagedIdentitySettings struct { + Resource *string `json:"resource,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_nameavailability.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_nameavailability.go new file mode 100644 index 000000000000..1c5d98741212 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_nameavailability.go @@ -0,0 +1,10 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NameAvailability struct { + Message *string `json:"message,omitempty"` + NameAvailable *bool `json:"nameAvailable,omitempty"` + Reason *string `json:"reason,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_nameavailabilityparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_nameavailabilityparameters.go new file mode 100644 index 000000000000..e555e38d3e05 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_nameavailabilityparameters.go @@ -0,0 +1,9 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NameAvailabilityParameters struct { + Name string `json:"name"` + Type string `json:"type"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_networkacl.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_networkacl.go new file mode 100644 index 000000000000..4527c32d44e5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_networkacl.go @@ -0,0 +1,9 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type NetworkACL struct { + Allow *[]SignalRRequestType `json:"allow,omitempty"` + Deny *[]SignalRRequestType `json:"deny,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpoint.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpoint.go new file mode 100644 index 000000000000..386ec10fcc56 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpoint.go @@ -0,0 +1,8 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpoint struct { + Id *string `json:"id,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointacl.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointacl.go new file mode 100644 index 000000000000..023e23531e9d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointacl.go @@ -0,0 +1,10 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointACL struct { + Allow *[]SignalRRequestType `json:"allow,omitempty"` + Deny *[]SignalRRequestType `json:"deny,omitempty"` + Name string `json:"name"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointconnection.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointconnection.go new file mode 100644 index 000000000000..f82669103c58 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointconnection.go @@ -0,0 +1,16 @@ +package signalr + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnection struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *PrivateEndpointConnectionProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointconnectionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointconnectionproperties.go new file mode 100644 index 000000000000..4f5798029775 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privateendpointconnectionproperties.go @@ -0,0 +1,11 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateEndpointConnectionProperties struct { + GroupIds *[]string `json:"groupIds,omitempty"` + PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState,omitempty"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkresource.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkresource.go new file mode 100644 index 000000000000..066fc50b9d4c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkresource.go @@ -0,0 +1,11 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateLinkResource struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *PrivateLinkResourceProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkresourceproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkresourceproperties.go new file mode 100644 index 000000000000..15661eded284 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkresourceproperties.go @@ -0,0 +1,11 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateLinkResourceProperties struct { + GroupId *string `json:"groupId,omitempty"` + RequiredMembers *[]string `json:"requiredMembers,omitempty"` + RequiredZoneNames *[]string `json:"requiredZoneNames,omitempty"` + ShareablePrivateLinkResourceTypes *[]ShareablePrivateLinkResourceType `json:"shareablePrivateLinkResourceTypes,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkserviceconnectionstate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkserviceconnectionstate.go new file mode 100644 index 000000000000..943f9ca6832e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_privatelinkserviceconnectionstate.go @@ -0,0 +1,10 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type PrivateLinkServiceConnectionState struct { + ActionsRequired *string `json:"actionsRequired,omitempty"` + Description *string `json:"description,omitempty"` + Status *PrivateLinkServiceConnectionStatus `json:"status,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_regeneratekeyparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_regeneratekeyparameters.go new file mode 100644 index 000000000000..13b82dd658cf --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_regeneratekeyparameters.go @@ -0,0 +1,8 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegenerateKeyParameters struct { + KeyType *KeyType `json:"keyType,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcelogcategory.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcelogcategory.go new file mode 100644 index 000000000000..d43e44612c09 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcelogcategory.go @@ -0,0 +1,9 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ResourceLogCategory struct { + Enabled *string `json:"enabled,omitempty"` + Name *string `json:"name,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcelogconfiguration.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcelogconfiguration.go new file mode 100644 index 000000000000..34bfdaaa1e44 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcelogconfiguration.go @@ -0,0 +1,8 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ResourceLogConfiguration struct { + Categories *[]ResourceLogCategory `json:"categories,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcereference.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcereference.go new file mode 100644 index 000000000000..7a2971d96a85 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcereference.go @@ -0,0 +1,8 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ResourceReference struct { + Id *string `json:"id,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcesku.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcesku.go new file mode 100644 index 000000000000..e05ec7fcdc79 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_resourcesku.go @@ -0,0 +1,12 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ResourceSku struct { + Capacity *int64 `json:"capacity,omitempty"` + Family *string `json:"family,omitempty"` + Name string `json:"name"` + Size *string `json:"size,omitempty"` + Tier *SignalRSkuTier `json:"tier,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_serverlessupstreamsettings.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_serverlessupstreamsettings.go new file mode 100644 index 000000000000..7248ea8446b6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_serverlessupstreamsettings.go @@ -0,0 +1,8 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ServerlessUpstreamSettings struct { + Templates *[]UpstreamTemplate `json:"templates,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_shareableprivatelinkresourceproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_shareableprivatelinkresourceproperties.go new file mode 100644 index 000000000000..acc486255758 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_shareableprivatelinkresourceproperties.go @@ -0,0 +1,10 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ShareablePrivateLinkResourceProperties struct { + Description *string `json:"description,omitempty"` + GroupId *string `json:"groupId,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_shareableprivatelinkresourcetype.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_shareableprivatelinkresourcetype.go new file mode 100644 index 000000000000..18407d00fe3d --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_shareableprivatelinkresourcetype.go @@ -0,0 +1,9 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ShareablePrivateLinkResourceType struct { + Name *string `json:"name,omitempty"` + Properties *ShareablePrivateLinkResourceProperties `json:"properties,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sharedprivatelinkresource.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sharedprivatelinkresource.go new file mode 100644 index 000000000000..6c5aab1998be --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sharedprivatelinkresource.go @@ -0,0 +1,16 @@ +package signalr + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SharedPrivateLinkResource struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SharedPrivateLinkResourceProperties `json:"properties,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sharedprivatelinkresourceproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sharedprivatelinkresourceproperties.go new file mode 100644 index 000000000000..425fbc505263 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sharedprivatelinkresourceproperties.go @@ -0,0 +1,12 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SharedPrivateLinkResourceProperties struct { + GroupId string `json:"groupId"` + PrivateLinkResourceId string `json:"privateLinkResourceId"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` + RequestMessage *string `json:"requestMessage,omitempty"` + Status *SharedPrivateLinkResourceStatus `json:"status,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrcorssettings.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrcorssettings.go new file mode 100644 index 000000000000..aa046d4b367c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrcorssettings.go @@ -0,0 +1,8 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRCorsSettings struct { + AllowedOrigins *[]string `json:"allowedOrigins,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrfeature.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrfeature.go new file mode 100644 index 000000000000..506f4ec0e675 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrfeature.go @@ -0,0 +1,10 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRFeature struct { + Flag FeatureFlags `json:"flag"` + Properties *map[string]string `json:"properties,omitempty"` + Value string `json:"value"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrkeys.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrkeys.go new file mode 100644 index 000000000000..70821e28a59c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrkeys.go @@ -0,0 +1,11 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRKeys struct { + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + PrimaryKey *string `json:"primaryKey,omitempty"` + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + SecondaryKey *string `json:"secondaryKey,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrnetworkacls.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrnetworkacls.go new file mode 100644 index 000000000000..05050a335b86 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrnetworkacls.go @@ -0,0 +1,10 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRNetworkACLs struct { + DefaultAction *ACLAction `json:"defaultAction,omitempty"` + PrivateEndpoints *[]PrivateEndpointACL `json:"privateEndpoints,omitempty"` + PublicNetwork *NetworkACL `json:"publicNetwork,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrproperties.go new file mode 100644 index 000000000000..39d0b709f8b6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrproperties.go @@ -0,0 +1,26 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRProperties struct { + Cors *SignalRCorsSettings `json:"cors,omitempty"` + DisableAadAuth *bool `json:"disableAadAuth,omitempty"` + DisableLocalAuth *bool `json:"disableLocalAuth,omitempty"` + ExternalIP *string `json:"externalIP,omitempty"` + Features *[]SignalRFeature `json:"features,omitempty"` + HostName *string `json:"hostName,omitempty"` + HostNamePrefix *string `json:"hostNamePrefix,omitempty"` + LiveTraceConfiguration *LiveTraceConfiguration `json:"liveTraceConfiguration,omitempty"` + NetworkACLs *SignalRNetworkACLs `json:"networkACLs,omitempty"` + PrivateEndpointConnections *[]PrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` + PublicNetworkAccess *string `json:"publicNetworkAccess,omitempty"` + PublicPort *int64 `json:"publicPort,omitempty"` + ResourceLogConfiguration *ResourceLogConfiguration `json:"resourceLogConfiguration,omitempty"` + ServerPort *int64 `json:"serverPort,omitempty"` + SharedPrivateLinkResources *[]SharedPrivateLinkResource `json:"sharedPrivateLinkResources,omitempty"` + Tls *SignalRTlsSettings `json:"tls,omitempty"` + Upstream *ServerlessUpstreamSettings `json:"upstream,omitempty"` + Version *string `json:"version,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrresource.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrresource.go new file mode 100644 index 000000000000..cb8f23323bff --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrresource.go @@ -0,0 +1,22 @@ +package signalr + +import ( + "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" + "github.com/hashicorp/go-azure-helpers/resourcemanager/systemdata" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRResource struct { + Id *string `json:"id,omitempty"` + Identity *identity.SystemOrUserAssignedMap `json:"identity,omitempty"` + Kind *ServiceKind `json:"kind,omitempty"` + Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` + Properties *SignalRProperties `json:"properties,omitempty"` + Sku *ResourceSku `json:"sku,omitempty"` + SystemData *systemdata.SystemData `json:"systemData,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrtlssettings.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrtlssettings.go new file mode 100644 index 000000000000..94dbfbda5e65 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrtlssettings.go @@ -0,0 +1,8 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRTlsSettings struct { + ClientCertEnabled *bool `json:"clientCertEnabled,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrusage.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrusage.go new file mode 100644 index 000000000000..2bd863e5aff2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrusage.go @@ -0,0 +1,12 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRUsage struct { + CurrentValue *int64 `json:"currentValue,omitempty"` + Id *string `json:"id,omitempty"` + Limit *int64 `json:"limit,omitempty"` + Name *SignalRUsageName `json:"name,omitempty"` + Unit *string `json:"unit,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrusagename.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrusagename.go new file mode 100644 index 000000000000..f9a475cc7c12 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_signalrusagename.go @@ -0,0 +1,9 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SignalRUsageName struct { + LocalizedValue *string `json:"localizedValue,omitempty"` + Value *string `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sku.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sku.go new file mode 100644 index 000000000000..0b2efca5d625 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_sku.go @@ -0,0 +1,10 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type Sku struct { + Capacity *SkuCapacity `json:"capacity,omitempty"` + ResourceType *string `json:"resourceType,omitempty"` + Sku *ResourceSku `json:"sku,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_skucapacity.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_skucapacity.go new file mode 100644 index 000000000000..3ac0d557740e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_skucapacity.go @@ -0,0 +1,12 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SkuCapacity struct { + AllowedValues *[]int64 `json:"allowedValues,omitempty"` + Default *int64 `json:"default,omitempty"` + Maximum *int64 `json:"maximum,omitempty"` + Minimum *int64 `json:"minimum,omitempty"` + ScaleType *ScaleType `json:"scaleType,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_skulist.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_skulist.go new file mode 100644 index 000000000000..70410fb96c83 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_skulist.go @@ -0,0 +1,9 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type SkuList struct { + NextLink *string `json:"nextLink,omitempty"` + Value *[]Sku `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_upstreamauthsettings.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_upstreamauthsettings.go new file mode 100644 index 000000000000..e5418bfaecf0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_upstreamauthsettings.go @@ -0,0 +1,9 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpstreamAuthSettings struct { + ManagedIdentity *ManagedIdentitySettings `json:"managedIdentity,omitempty"` + Type *UpstreamAuthType `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_upstreamtemplate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_upstreamtemplate.go new file mode 100644 index 000000000000..476b1dd7cde9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/model_upstreamtemplate.go @@ -0,0 +1,12 @@ +package signalr + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type UpstreamTemplate struct { + Auth *UpstreamAuthSettings `json:"auth,omitempty"` + CategoryPattern *string `json:"categoryPattern,omitempty"` + EventPattern *string `json:"eventPattern,omitempty"` + HubPattern *string `json:"hubPattern,omitempty"` + UrlTemplate string `json:"urlTemplate"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/predicates.go new file mode 100644 index 000000000000..e99a7eefcbba --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/predicates.go @@ -0,0 +1,172 @@ +package signalr + +type CustomCertificateOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p CustomCertificateOperationPredicate) Matches(input CustomCertificate) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} + +type CustomDomainOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p CustomDomainOperationPredicate) Matches(input CustomDomain) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} + +type PrivateEndpointConnectionOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p PrivateEndpointConnectionOperationPredicate) Matches(input PrivateEndpointConnection) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} + +type PrivateLinkResourceOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p PrivateLinkResourceOperationPredicate) Matches(input PrivateLinkResource) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} + +type SharedPrivateLinkResourceOperationPredicate struct { + Id *string + Name *string + Type *string +} + +func (p SharedPrivateLinkResourceOperationPredicate) Matches(input SharedPrivateLinkResource) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} + +type SignalRResourceOperationPredicate struct { + Id *string + Location *string + Name *string + Type *string +} + +func (p SignalRResourceOperationPredicate) Matches(input SignalRResource) bool { + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Location != nil && (input.Location == nil && *p.Location != *input.Location) { + return false + } + + if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { + return false + } + + if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { + return false + } + + return true +} + +type SignalRUsageOperationPredicate struct { + CurrentValue *int64 + Id *string + Limit *int64 + Unit *string +} + +func (p SignalRUsageOperationPredicate) Matches(input SignalRUsage) bool { + + if p.CurrentValue != nil && (input.CurrentValue == nil && *p.CurrentValue != *input.CurrentValue) { + return false + } + + if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { + return false + } + + if p.Limit != nil && (input.Limit == nil && *p.Limit != *input.Limit) { + return false + } + + if p.Unit != nil && (input.Unit == nil && *p.Unit != *input.Unit) { + return false + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/version.go new file mode 100644 index 000000000000..7ee51955822c --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr/version.go @@ -0,0 +1,12 @@ +package signalr + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2022-02-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/signalr/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/README.md new file mode 100644 index 000000000000..f317f67ddbb6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/README.md @@ -0,0 +1,89 @@ + +## `github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies` Documentation + +The `objectreplicationpolicies` SDK allows for interaction with the Azure Resource Manager Service `storage` (API Version `2021-04-01`). + +This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). + +### Import Path + +```go +import "github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies" +``` + + +### Client Initialization + +```go +client := objectreplicationpolicies.NewObjectReplicationPoliciesClientWithBaseURI("https://management.azure.com") +client.Client.Authorizer = authorizer +``` + + +### Example Usage: `ObjectReplicationPoliciesClient.CreateOrUpdate` + +```go +ctx := context.TODO() +id := objectreplicationpolicies.NewObjectReplicationPoliciesID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "objectReplicationPolicyIdValue") + +payload := objectreplicationpolicies.ObjectReplicationPolicy{ + // ... +} + + +read, err := client.CreateOrUpdate(ctx, id, payload) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ObjectReplicationPoliciesClient.Delete` + +```go +ctx := context.TODO() +id := objectreplicationpolicies.NewObjectReplicationPoliciesID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "objectReplicationPolicyIdValue") + +read, err := client.Delete(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ObjectReplicationPoliciesClient.Get` + +```go +ctx := context.TODO() +id := objectreplicationpolicies.NewObjectReplicationPoliciesID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue", "objectReplicationPolicyIdValue") + +read, err := client.Get(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` + + +### Example Usage: `ObjectReplicationPoliciesClient.List` + +```go +ctx := context.TODO() +id := objectreplicationpolicies.NewStorageAccountID("12345678-1234-9876-4563-123456789012", "example-resource-group", "accountValue") + +read, err := client.List(ctx, id) +if err != nil { + // handle the error +} +if model := read.Model; model != nil { + // do something with the model/response object +} +``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/client.go new file mode 100644 index 000000000000..d85f5f511abe --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/client.go @@ -0,0 +1,18 @@ +package objectreplicationpolicies + +import "github.com/Azure/go-autorest/autorest" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ObjectReplicationPoliciesClient struct { + Client autorest.Client + baseUri string +} + +func NewObjectReplicationPoliciesClientWithBaseURI(endpoint string) ObjectReplicationPoliciesClient { + return ObjectReplicationPoliciesClient{ + Client: autorest.NewClientWithUserAgent(userAgent()), + baseUri: endpoint, + } +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/id_objectreplicationpolicies.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/id_objectreplicationpolicies.go new file mode 100644 index 000000000000..2f1836d56113 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/id_objectreplicationpolicies.go @@ -0,0 +1,137 @@ +package objectreplicationpolicies + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = ObjectReplicationPoliciesId{} + +// ObjectReplicationPoliciesId is a struct representing the Resource ID for a Object Replication Policies +type ObjectReplicationPoliciesId struct { + SubscriptionId string + ResourceGroupName string + AccountName string + ObjectReplicationPolicyId string +} + +// NewObjectReplicationPoliciesID returns a new ObjectReplicationPoliciesId struct +func NewObjectReplicationPoliciesID(subscriptionId string, resourceGroupName string, accountName string, objectReplicationPolicyId string) ObjectReplicationPoliciesId { + return ObjectReplicationPoliciesId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + ObjectReplicationPolicyId: objectReplicationPolicyId, + } +} + +// ParseObjectReplicationPoliciesID parses 'input' into a ObjectReplicationPoliciesId +func ParseObjectReplicationPoliciesID(input string) (*ObjectReplicationPoliciesId, error) { + parser := resourceids.NewParserFromResourceIdType(ObjectReplicationPoliciesId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ObjectReplicationPoliciesId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.ObjectReplicationPolicyId, ok = parsed.Parsed["objectReplicationPolicyId"]; !ok { + return nil, fmt.Errorf("the segment 'objectReplicationPolicyId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseObjectReplicationPoliciesIDInsensitively parses 'input' case-insensitively into a ObjectReplicationPoliciesId +// note: this method should only be used for API response data and not user input +func ParseObjectReplicationPoliciesIDInsensitively(input string) (*ObjectReplicationPoliciesId, error) { + parser := resourceids.NewParserFromResourceIdType(ObjectReplicationPoliciesId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := ObjectReplicationPoliciesId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + if id.ObjectReplicationPolicyId, ok = parsed.Parsed["objectReplicationPolicyId"]; !ok { + return nil, fmt.Errorf("the segment 'objectReplicationPolicyId' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateObjectReplicationPoliciesID checks that 'input' can be parsed as a Object Replication Policies ID +func ValidateObjectReplicationPoliciesID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseObjectReplicationPoliciesID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Object Replication Policies ID +func (id ObjectReplicationPoliciesId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/objectReplicationPolicies/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName, id.ObjectReplicationPolicyId) +} + +// Segments returns a slice of Resource ID Segments which comprise this Object Replication Policies ID +func (id ObjectReplicationPoliciesId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftStorage", "Microsoft.Storage", "Microsoft.Storage"), + resourceids.StaticSegment("staticStorageAccounts", "storageAccounts", "storageAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + resourceids.StaticSegment("staticObjectReplicationPolicies", "objectReplicationPolicies", "objectReplicationPolicies"), + resourceids.UserSpecifiedSegment("objectReplicationPolicyId", "objectReplicationPolicyIdValue"), + } +} + +// String returns a human-readable description of this Object Replication Policies ID +func (id ObjectReplicationPoliciesId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + fmt.Sprintf("Object Replication Policy: %q", id.ObjectReplicationPolicyId), + } + return fmt.Sprintf("Object Replication Policies (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/id_storageaccount.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/id_storageaccount.go new file mode 100644 index 000000000000..cba80e114277 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/id_storageaccount.go @@ -0,0 +1,124 @@ +package objectreplicationpolicies + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +var _ resourceids.ResourceId = StorageAccountId{} + +// StorageAccountId is a struct representing the Resource ID for a Storage Account +type StorageAccountId struct { + SubscriptionId string + ResourceGroupName string + AccountName string +} + +// NewStorageAccountID returns a new StorageAccountId struct +func NewStorageAccountID(subscriptionId string, resourceGroupName string, accountName string) StorageAccountId { + return StorageAccountId{ + SubscriptionId: subscriptionId, + ResourceGroupName: resourceGroupName, + AccountName: accountName, + } +} + +// ParseStorageAccountID parses 'input' into a StorageAccountId +func ParseStorageAccountID(input string) (*StorageAccountId, error) { + parser := resourceids.NewParserFromResourceIdType(StorageAccountId{}) + parsed, err := parser.Parse(input, false) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := StorageAccountId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ParseStorageAccountIDInsensitively parses 'input' case-insensitively into a StorageAccountId +// note: this method should only be used for API response data and not user input +func ParseStorageAccountIDInsensitively(input string) (*StorageAccountId, error) { + parser := resourceids.NewParserFromResourceIdType(StorageAccountId{}) + parsed, err := parser.Parse(input, true) + if err != nil { + return nil, fmt.Errorf("parsing %q: %+v", input, err) + } + + var ok bool + id := StorageAccountId{} + + if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { + return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) + } + + if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { + return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) + } + + if id.AccountName, ok = parsed.Parsed["accountName"]; !ok { + return nil, fmt.Errorf("the segment 'accountName' was not found in the resource id %q", input) + } + + return &id, nil +} + +// ValidateStorageAccountID checks that 'input' can be parsed as a Storage Account ID +func ValidateStorageAccountID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := ParseStorageAccountID(v); err != nil { + errors = append(errors, err) + } + + return +} + +// ID returns the formatted Storage Account ID +func (id StorageAccountId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AccountName) +} + +// Segments returns a slice of Resource ID Segments which comprise this Storage Account ID +func (id StorageAccountId) Segments() []resourceids.Segment { + return []resourceids.Segment{ + resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), + resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), + resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), + resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), + resourceids.StaticSegment("staticProviders", "providers", "providers"), + resourceids.ResourceProviderSegment("staticMicrosoftStorage", "Microsoft.Storage", "Microsoft.Storage"), + resourceids.StaticSegment("staticStorageAccounts", "storageAccounts", "storageAccounts"), + resourceids.UserSpecifiedSegment("accountName", "accountValue"), + } +} + +// String returns a human-readable description of this Storage Account ID +func (id StorageAccountId) String() string { + components := []string{ + fmt.Sprintf("Subscription: %q", id.SubscriptionId), + fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), + fmt.Sprintf("Account Name: %q", id.AccountName), + } + return fmt.Sprintf("Storage Account (%s)", strings.Join(components, "\n")) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_createorupdate_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_createorupdate_autorest.go new file mode 100644 index 000000000000..9a8e42cf4c0e --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_createorupdate_autorest.go @@ -0,0 +1,68 @@ +package objectreplicationpolicies + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type CreateOrUpdateOperationResponse struct { + HttpResponse *http.Response + Model *ObjectReplicationPolicy +} + +// CreateOrUpdate ... +func (c ObjectReplicationPoliciesClient) CreateOrUpdate(ctx context.Context, id ObjectReplicationPoliciesId, input ObjectReplicationPolicy) (result CreateOrUpdateOperationResponse, err error) { + req, err := c.preparerForCreateOrUpdate(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "CreateOrUpdate", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForCreateOrUpdate(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "CreateOrUpdate", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForCreateOrUpdate prepares the CreateOrUpdate request. +func (c ObjectReplicationPoliciesClient) preparerForCreateOrUpdate(ctx context.Context, id ObjectReplicationPoliciesId, input ObjectReplicationPolicy) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForCreateOrUpdate handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (c ObjectReplicationPoliciesClient) responderForCreateOrUpdate(resp *http.Response) (result CreateOrUpdateOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_delete_autorest.go new file mode 100644 index 000000000000..a18ae53ca84a --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_delete_autorest.go @@ -0,0 +1,65 @@ +package objectreplicationpolicies + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DeleteOperationResponse struct { + HttpResponse *http.Response +} + +// Delete ... +func (c ObjectReplicationPoliciesClient) Delete(ctx context.Context, id ObjectReplicationPoliciesId) (result DeleteOperationResponse, err error) { + req, err := c.preparerForDelete(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "Delete", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "Delete", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDelete(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "Delete", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDelete prepares the Delete request. +func (c ObjectReplicationPoliciesClient) preparerForDelete(ctx context.Context, id ObjectReplicationPoliciesId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsDelete(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDelete handles the response to the Delete request. The method always +// closes the http.Response Body. +func (c ObjectReplicationPoliciesClient) responderForDelete(resp *http.Response) (result DeleteOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_get_autorest.go new file mode 100644 index 000000000000..96f8e2deb381 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_get_autorest.go @@ -0,0 +1,67 @@ +package objectreplicationpolicies + +import ( + "context" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type GetOperationResponse struct { + HttpResponse *http.Response + Model *ObjectReplicationPolicy +} + +// Get ... +func (c ObjectReplicationPoliciesClient) Get(ctx context.Context, id ObjectReplicationPoliciesId) (result GetOperationResponse, err error) { + req, err := c.preparerForGet(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "Get", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "Get", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForGet(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "Get", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForGet prepares the Get request. +func (c ObjectReplicationPoliciesClient) preparerForGet(ctx context.Context, id ObjectReplicationPoliciesId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(id.ID()), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForGet handles the response to the Get request. The method always +// closes the http.Response Body. +func (c ObjectReplicationPoliciesClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_list_autorest.go new file mode 100644 index 000000000000..2da7f3f44e1f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/method_list_autorest.go @@ -0,0 +1,68 @@ +package objectreplicationpolicies + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ListOperationResponse struct { + HttpResponse *http.Response + Model *ObjectReplicationPolicies +} + +// List ... +func (c ObjectReplicationPoliciesClient) List(ctx context.Context, id StorageAccountId) (result ListOperationResponse, err error) { + req, err := c.preparerForList(ctx, id) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "List", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "List", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForList(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "objectreplicationpolicies.ObjectReplicationPoliciesClient", "List", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForList prepares the List request. +func (c ObjectReplicationPoliciesClient) preparerForList(ctx context.Context, id StorageAccountId) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsGet(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/objectReplicationPolicies", id.ID())), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForList handles the response to the List request. The method always +// closes the http.Response Body. +func (c ObjectReplicationPoliciesClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicies.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicies.go new file mode 100644 index 000000000000..e9617fd29cdd --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicies.go @@ -0,0 +1,8 @@ +package objectreplicationpolicies + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ObjectReplicationPolicies struct { + Value *[]ObjectReplicationPolicy `json:"value,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicy.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicy.go new file mode 100644 index 000000000000..5d8e7ab7bc42 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicy.go @@ -0,0 +1,11 @@ +package objectreplicationpolicies + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ObjectReplicationPolicy struct { + Id *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *ObjectReplicationPolicyProperties `json:"properties,omitempty"` + Type *string `json:"type,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyfilter.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyfilter.go new file mode 100644 index 000000000000..e324d04d5a49 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyfilter.go @@ -0,0 +1,9 @@ +package objectreplicationpolicies + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ObjectReplicationPolicyFilter struct { + MinCreationTime *string `json:"minCreationTime,omitempty"` + PrefixMatch *[]string `json:"prefixMatch,omitempty"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyproperties.go new file mode 100644 index 000000000000..1bc675c903f5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyproperties.go @@ -0,0 +1,30 @@ +package objectreplicationpolicies + +import ( + "time" + + "github.com/hashicorp/go-azure-helpers/lang/dates" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ObjectReplicationPolicyProperties struct { + DestinationAccount string `json:"destinationAccount"` + EnabledTime *string `json:"enabledTime,omitempty"` + PolicyId *string `json:"policyId,omitempty"` + Rules *[]ObjectReplicationPolicyRule `json:"rules,omitempty"` + SourceAccount string `json:"sourceAccount"` +} + +func (o *ObjectReplicationPolicyProperties) GetEnabledTimeAsTime() (*time.Time, error) { + if o.EnabledTime == nil { + return nil, nil + } + return dates.ParseAsFormat(o.EnabledTime, "2006-01-02T15:04:05Z07:00") +} + +func (o *ObjectReplicationPolicyProperties) SetEnabledTimeAsTime(input time.Time) { + formatted := input.Format("2006-01-02T15:04:05Z07:00") + o.EnabledTime = &formatted +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyrule.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyrule.go new file mode 100644 index 000000000000..8bbb947ff397 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/model_objectreplicationpolicyrule.go @@ -0,0 +1,11 @@ +package objectreplicationpolicies + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type ObjectReplicationPolicyRule struct { + DestinationContainer string `json:"destinationContainer"` + Filters *ObjectReplicationPolicyFilter `json:"filters,omitempty"` + RuleId *string `json:"ruleId,omitempty"` + SourceContainer string `json:"sourceContainer"` +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/version.go new file mode 100644 index 000000000000..fec2341a232f --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies/version.go @@ -0,0 +1,12 @@ +package objectreplicationpolicies + +import "fmt" + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +const defaultApiVersion = "2021-04-01" + +func userAgent() string { + return fmt.Sprintf("hashicorp/go-azure-sdk/objectreplicationpolicies/%s", defaultApiVersion) +} diff --git a/vendor/github.com/hashicorp/go-hclog/README.md b/vendor/github.com/hashicorp/go-hclog/README.md index 5d56f4b59c3f..21a17c5af39b 100644 --- a/vendor/github.com/hashicorp/go-hclog/README.md +++ b/vendor/github.com/hashicorp/go-hclog/README.md @@ -17,11 +17,8 @@ JSON output mode for production. ## Stability Note -While this library is fully open source and HashiCorp will be maintaining it -(since we are and will be making extensive use of it), the API and output -format is subject to minor changes as we fully bake and vet it in our projects. -This notice will be removed once it's fully integrated into our major projects -and no further changes are anticipated. +This library has reached 1.0 stability. Its API can be considered solidified +and promised through future versions. ## Installation and Docs @@ -102,7 +99,7 @@ into all the callers. ### Using `hclog.Fmt()` ```go -var int totalBandwidth = 200 +totalBandwidth := 200 appLogger.Info("total bandwidth exceeded", "bandwidth", hclog.Fmt("%d GB/s", totalBandwidth)) ``` @@ -146,3 +143,6 @@ log.Printf("[DEBUG] %d", 42) Notice that if `appLogger` is initialized with the `INFO` log level _and_ you specify `InferLevels: true`, you will not see any output here. You must change `appLogger` to `DEBUG` to see output. See the docs for more information. + +If the log lines start with a timestamp you can use the +`InferLevelsWithTimestamp` option to try and ignore them. diff --git a/vendor/github.com/hashicorp/go-hclog/colorize_unix.go b/vendor/github.com/hashicorp/go-hclog/colorize_unix.go index 44aa9bf2c620..9635c838b4e9 100644 --- a/vendor/github.com/hashicorp/go-hclog/colorize_unix.go +++ b/vendor/github.com/hashicorp/go-hclog/colorize_unix.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package hclog @@ -21,6 +22,7 @@ func (l *intLogger) setColorization(opts *LoggerOptions) { isCygwinTerm := isatty.IsCygwinTerminal(fi.Fd()) isTerm := isUnixTerm || isCygwinTerm if !isTerm { + l.headerColor = ColorOff l.writer.color = ColorOff } } diff --git a/vendor/github.com/hashicorp/go-hclog/colorize_windows.go b/vendor/github.com/hashicorp/go-hclog/colorize_windows.go index 23486b6d74f8..30859168eebe 100644 --- a/vendor/github.com/hashicorp/go-hclog/colorize_windows.go +++ b/vendor/github.com/hashicorp/go-hclog/colorize_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package hclog @@ -26,8 +27,12 @@ func (l *intLogger) setColorization(opts *LoggerOptions) { isTerm := isUnixTerm || isCygwinTerm if !isTerm { l.writer.color = ColorOff + l.headerColor = ColorOff return } - l.writer.w = colorable.NewColorable(fi) + + if l.headerColor == ColorOff { + l.writer.w = colorable.NewColorable(fi) + } } } diff --git a/vendor/github.com/hashicorp/go-hclog/global.go b/vendor/github.com/hashicorp/go-hclog/global.go index 22ebc57d877f..b9f00217cae3 100644 --- a/vendor/github.com/hashicorp/go-hclog/global.go +++ b/vendor/github.com/hashicorp/go-hclog/global.go @@ -2,6 +2,7 @@ package hclog import ( "sync" + "time" ) var ( @@ -14,6 +15,7 @@ var ( DefaultOptions = &LoggerOptions{ Level: DefaultLevel, Output: DefaultOutput, + TimeFn: time.Now, } ) diff --git a/vendor/github.com/hashicorp/go-hclog/interceptlogger.go b/vendor/github.com/hashicorp/go-hclog/interceptlogger.go index 631baf2f0cc1..ff42f1bfc1dd 100644 --- a/vendor/github.com/hashicorp/go-hclog/interceptlogger.go +++ b/vendor/github.com/hashicorp/go-hclog/interceptlogger.go @@ -180,9 +180,10 @@ func (i *interceptLogger) StandardWriterIntercept(opts *StandardLoggerOptions) i func (i *interceptLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer { return &stdlogAdapter{ - log: i, - inferLevels: opts.InferLevels, - forceLevel: opts.ForceLevel, + log: i, + inferLevels: opts.InferLevels, + inferLevelsWithTimestamp: opts.InferLevelsWithTimestamp, + forceLevel: opts.ForceLevel, } } diff --git a/vendor/github.com/hashicorp/go-hclog/intlogger.go b/vendor/github.com/hashicorp/go-hclog/intlogger.go index 6099e67260e8..83232f7a622f 100644 --- a/vendor/github.com/hashicorp/go-hclog/intlogger.go +++ b/vendor/github.com/hashicorp/go-hclog/intlogger.go @@ -60,6 +60,7 @@ type intLogger struct { callerOffset int name string timeFormat string + timeFn TimeFunction disableTime bool // This is an interface so that it's shared by any derived loggers, since @@ -68,6 +69,8 @@ type intLogger struct { writer *writer level *int32 + headerColor ColorOption + implied []interface{} exclude func(level Level, msg string, args ...interface{}) bool @@ -112,16 +115,28 @@ func newLogger(opts *LoggerOptions) *intLogger { mutex = new(sync.Mutex) } + var primaryColor, headerColor ColorOption + + if opts.ColorHeaderOnly { + primaryColor = ColorOff + headerColor = opts.Color + } else { + primaryColor = opts.Color + headerColor = ColorOff + } + l := &intLogger{ json: opts.JSONFormat, name: opts.Name, timeFormat: TimeFormat, + timeFn: time.Now, disableTime: opts.DisableTime, mutex: mutex, - writer: newWriter(output, opts.Color), + writer: newWriter(output, primaryColor), level: new(int32), exclude: opts.Exclude, independentLevels: opts.IndependentLevels, + headerColor: headerColor, } if opts.IncludeLocation { l.callerOffset = offsetIntLogger + opts.AdditionalLocationOffset @@ -130,6 +145,9 @@ func newLogger(opts *LoggerOptions) *intLogger { if l.json { l.timeFormat = TimeFormatJSON } + if opts.TimeFn != nil { + l.timeFn = opts.TimeFn + } if opts.TimeFormat != "" { l.timeFormat = opts.TimeFormat } @@ -152,7 +170,7 @@ func (l *intLogger) log(name string, level Level, msg string, args ...interface{ return } - t := time.Now() + t := l.timeFn() l.mutex.Lock() defer l.mutex.Unlock() @@ -199,6 +217,24 @@ func trimCallerPath(path string) string { return path[idx+1:] } +// isNormal indicates if the rune is one allowed to exist as an unquoted +// string value. This is a subset of ASCII, `-` through `~`. +func isNormal(r rune) bool { + return 0x2D <= r && r <= 0x7E // - through ~ +} + +// needsQuoting returns false if all the runes in string are normal, according +// to isNormal +func needsQuoting(str string) bool { + for _, r := range str { + if !isNormal(r) { + return true + } + } + + return false +} + // Non-JSON logging format function func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string, args ...interface{}) { @@ -209,7 +245,12 @@ func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string, s, ok := _levelToBracket[level] if ok { - l.writer.WriteString(s) + if l.headerColor != ColorOff { + color := _levelToColor[level] + color.Fprint(l.writer, s) + } else { + l.writer.WriteString(s) + } } else { l.writer.WriteString("[?????]") } @@ -263,6 +304,7 @@ func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string, val = st if st == "" { val = `""` + raw = true } case int: val = strconv.FormatInt(int64(st), 10) @@ -295,6 +337,9 @@ func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string, continue FOR case Format: val = fmt.Sprintf(st[0].(string), st[1:]...) + case Quote: + raw = true + val = strconv.Quote(string(st)) default: v := reflect.ValueOf(st) if v.Kind() == reflect.Slice { @@ -320,13 +365,11 @@ func (l *intLogger) logPlain(t time.Time, name string, level Level, msg string, l.writer.WriteString("=\n") writeIndent(l.writer, val, " | ") l.writer.WriteString(" ") - } else if !raw && strings.ContainsAny(val, " \t") { + } else if !raw && needsQuoting(val) { l.writer.WriteByte(' ') l.writer.WriteString(key) l.writer.WriteByte('=') - l.writer.WriteByte('"') - l.writer.WriteString(val) - l.writer.WriteByte('"') + l.writer.WriteString(strconv.Quote(val)) } else { l.writer.WriteByte(' ') l.writer.WriteString(key) @@ -684,9 +727,10 @@ func (l *intLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer { newLog.callerOffset = l.callerOffset + 4 } return &stdlogAdapter{ - log: &newLog, - inferLevels: opts.InferLevels, - forceLevel: opts.ForceLevel, + log: &newLog, + inferLevels: opts.InferLevels, + inferLevelsWithTimestamp: opts.InferLevelsWithTimestamp, + forceLevel: opts.ForceLevel, } } diff --git a/vendor/github.com/hashicorp/go-hclog/logger.go b/vendor/github.com/hashicorp/go-hclog/logger.go index 7f36b1fd20f4..858143028427 100644 --- a/vendor/github.com/hashicorp/go-hclog/logger.go +++ b/vendor/github.com/hashicorp/go-hclog/logger.go @@ -5,6 +5,7 @@ import ( "log" "os" "strings" + "time" ) var ( @@ -67,6 +68,12 @@ type Octal int // text output. For example: L.Info("bits", Binary(17)) type Binary int +// A simple shortcut to format strings with Go quoting. Control and +// non-printable characters will be escaped with their backslash equivalents in +// output. Intended for untrusted or multiline strings which should be logged +// as concisely as possible. +type Quote string + // ColorOption expresses how the output should be colored, if at all. type ColorOption uint8 @@ -206,6 +213,15 @@ type StandardLoggerOptions struct { // [DEBUG] and strip it off before reapplying it. InferLevels bool + // Indicate that some minimal parsing should be done on strings to try + // and detect their level and re-emit them while ignoring possible + // timestamp values in the beginning of the string. + // This supports the strings like [ERROR], [ERR] [TRACE], [WARN], [INFO], + // [DEBUG] and strip it off before reapplying it. + // The timestamp detection may result in false positives and incomplete + // string outputs. + InferLevelsWithTimestamp bool + // ForceLevel is used to force all output from the standard logger to be at // the specified level. Similar to InferLevels, this will strip any level // prefix contained in the logged string before applying the forced level. @@ -213,6 +229,8 @@ type StandardLoggerOptions struct { ForceLevel Level } +type TimeFunction = func() time.Time + // LoggerOptions can be used to configure a new logger. type LoggerOptions struct { // Name of the subsystem to prefix logs with @@ -242,6 +260,9 @@ type LoggerOptions struct { // The time format to use instead of the default TimeFormat string + // A function which is called to get the time object that is formatted using `TimeFormat` + TimeFn TimeFunction + // Control whether or not to display the time at all. This is required // because setting TimeFormat to empty assumes the default format. DisableTime bool @@ -250,6 +271,9 @@ type LoggerOptions struct { // are concretely instances of *os.File. Color ColorOption + // Only color the header, not the body. This can help with readability of long messages. + ColorHeaderOnly bool + // A function which is called with the log information and if it returns true the value // should not be logged. // This is useful when interacting with a system that you wish to suppress the log diff --git a/vendor/github.com/hashicorp/go-hclog/stdlog.go b/vendor/github.com/hashicorp/go-hclog/stdlog.go index f35d875d327a..641f20ccbcc8 100644 --- a/vendor/github.com/hashicorp/go-hclog/stdlog.go +++ b/vendor/github.com/hashicorp/go-hclog/stdlog.go @@ -3,16 +3,22 @@ package hclog import ( "bytes" "log" + "regexp" "strings" ) +// Regex to ignore characters commonly found in timestamp formats from the +// beginning of inputs. +var logTimestampRegexp = regexp.MustCompile(`^[\d\s\:\/\.\+-TZ]*`) + // Provides a io.Writer to shim the data out of *log.Logger // and back into our Logger. This is basically the only way to // build upon *log.Logger. type stdlogAdapter struct { - log Logger - inferLevels bool - forceLevel Level + log Logger + inferLevels bool + inferLevelsWithTimestamp bool + forceLevel Level } // Take the data, infer the levels if configured, and send it through @@ -28,6 +34,10 @@ func (s *stdlogAdapter) Write(data []byte) (int, error) { // Log at the forced level s.dispatch(str, s.forceLevel) } else if s.inferLevels { + if s.inferLevelsWithTimestamp { + str = s.trimTimestamp(str) + } + level, str := s.pickLevel(str) s.dispatch(str, level) } else { @@ -64,7 +74,7 @@ func (s *stdlogAdapter) pickLevel(str string) (Level, string) { case strings.HasPrefix(str, "[INFO]"): return Info, strings.TrimSpace(str[6:]) case strings.HasPrefix(str, "[WARN]"): - return Warn, strings.TrimSpace(str[7:]) + return Warn, strings.TrimSpace(str[6:]) case strings.HasPrefix(str, "[ERROR]"): return Error, strings.TrimSpace(str[7:]) case strings.HasPrefix(str, "[ERR]"): @@ -74,6 +84,11 @@ func (s *stdlogAdapter) pickLevel(str string) (Level, string) { } } +func (s *stdlogAdapter) trimTimestamp(str string) string { + idx := logTimestampRegexp.FindStringIndex(str) + return str[idx[1]:] +} + type logWriter struct { l *log.Logger } diff --git a/vendor/github.com/hashicorp/go-plugin/README.md b/vendor/github.com/hashicorp/go-plugin/README.md index 46ee09fc0ca9..39391f24fe42 100644 --- a/vendor/github.com/hashicorp/go-plugin/README.md +++ b/vendor/github.com/hashicorp/go-plugin/README.md @@ -3,8 +3,9 @@ `go-plugin` is a Go (golang) plugin system over RPC. It is the plugin system that has been in use by HashiCorp tooling for over 4 years. While initially created for [Packer](https://www.packer.io), it is additionally in use by -[Terraform](https://www.terraform.io), [Nomad](https://www.nomadproject.io), and -[Vault](https://www.vaultproject.io). +[Terraform](https://www.terraform.io), [Nomad](https://www.nomadproject.io), +[Vault](https://www.vaultproject.io), and +[Boundary](https://www.boundaryproject.io). While the plugin system is over RPC, it is currently only designed to work over a local [reliable] network. Plugins over a real network are not supported diff --git a/vendor/github.com/hashicorp/go-plugin/client.go b/vendor/github.com/hashicorp/go-plugin/client.go index 67dca883576e..e0bee88a1d4a 100644 --- a/vendor/github.com/hashicorp/go-plugin/client.go +++ b/vendor/github.com/hashicorp/go-plugin/client.go @@ -574,6 +574,8 @@ func (c *Client) Start() (addr net.Addr, err error) { c.config.TLSConfig = &tls.Config{ Certificates: []tls.Certificate{cert}, + ClientAuth: tls.RequireAndVerifyClientCert, + MinVersion: tls.VersionTLS12, ServerName: "localhost", } } @@ -629,17 +631,19 @@ func (c *Client) Start() (addr net.Addr, err error) { // Wait for the command to end. err := cmd.Wait() - debugMsgArgs := []interface{}{ + msgArgs := []interface{}{ "path", path, "pid", pid, } if err != nil { - debugMsgArgs = append(debugMsgArgs, + msgArgs = append(msgArgs, []interface{}{"error", err.Error()}...) + c.logger.Error("plugin process exited", msgArgs...) + } else { + // Log and make sure to flush the logs right away + c.logger.Info("plugin process exited", msgArgs...) } - // Log and make sure to flush the logs write away - c.logger.Debug("plugin process exited", debugMsgArgs...) os.Stderr.Sync() // Set that we exited, which takes a lock @@ -774,7 +778,7 @@ func (c *Client) Start() (addr net.Addr, err error) { } // loadServerCert is used by AutoMTLS to read an x.509 cert returned by the -// server, and load it as the RootCA for the client TLSConfig. +// server, and load it as the RootCA and ClientCA for the client TLSConfig. func (c *Client) loadServerCert(cert string) error { certPool := x509.NewCertPool() @@ -791,6 +795,7 @@ func (c *Client) loadServerCert(cert string) error { certPool.AddCert(x509Cert) c.config.TLSConfig.RootCAs = certPool + c.config.TLSConfig.ClientCAs = certPool return nil } diff --git a/vendor/github.com/hashicorp/go-plugin/process_posix.go b/vendor/github.com/hashicorp/go-plugin/process_posix.go index 70ba546bf6dd..185957f8d115 100644 --- a/vendor/github.com/hashicorp/go-plugin/process_posix.go +++ b/vendor/github.com/hashicorp/go-plugin/process_posix.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package plugin diff --git a/vendor/github.com/hashicorp/go-plugin/process_windows.go b/vendor/github.com/hashicorp/go-plugin/process_windows.go index 9f7b0180901f..0eaa7705d22c 100644 --- a/vendor/github.com/hashicorp/go-plugin/process_windows.go +++ b/vendor/github.com/hashicorp/go-plugin/process_windows.go @@ -19,6 +19,7 @@ func _pidAlive(pid int) bool { if err != nil { return false } + defer syscall.CloseHandle(h) var ec uint32 if e := syscall.GetExitCodeProcess(h, &ec); e != nil { diff --git a/vendor/github.com/hashicorp/go-plugin/rpc_server.go b/vendor/github.com/hashicorp/go-plugin/rpc_server.go index 5bb18dd5db16..449ba6cc1ee9 100644 --- a/vendor/github.com/hashicorp/go-plugin/rpc_server.go +++ b/vendor/github.com/hashicorp/go-plugin/rpc_server.go @@ -45,7 +45,11 @@ func (s *RPCServer) Serve(lis net.Listener) { for { conn, err := lis.Accept() if err != nil { - log.Printf("[ERR] plugin: plugin server: %s", err) + severity := "ERR" + if errors.Is(err, net.ErrClosed) { + severity = "DEBUG" + } + log.Printf("[%s] plugin: plugin server: %s", severity, err) return } diff --git a/vendor/github.com/hashicorp/go-plugin/server.go b/vendor/github.com/hashicorp/go-plugin/server.go index 7a58cc391975..e134999103fd 100644 --- a/vendor/github.com/hashicorp/go-plugin/server.go +++ b/vendor/github.com/hashicorp/go-plugin/server.go @@ -304,13 +304,13 @@ func Serve(opts *ServeConfig) { certPEM, keyPEM, err := generateCert() if err != nil { - logger.Error("failed to generate client certificate", "error", err) + logger.Error("failed to generate server certificate", "error", err) panic(err) } cert, err := tls.X509KeyPair(certPEM, keyPEM) if err != nil { - logger.Error("failed to parse client certificate", "error", err) + logger.Error("failed to parse server certificate", "error", err) panic(err) } @@ -319,6 +319,8 @@ func Serve(opts *ServeConfig) { ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: clientCertPool, MinVersion: tls.VersionTLS12, + RootCAs: clientCertPool, + ServerName: "localhost", } // We send back the raw leaf cert data for the client rather than the diff --git a/vendor/github.com/hashicorp/go-uuid/LICENSE b/vendor/github.com/hashicorp/go-uuid/LICENSE index e87a115e462e..a320b309c44a 100644 --- a/vendor/github.com/hashicorp/go-uuid/LICENSE +++ b/vendor/github.com/hashicorp/go-uuid/LICENSE @@ -1,3 +1,5 @@ +Copyright © 2015-2022 HashiCorp, Inc. + Mozilla Public License, version 2.0 1. Definitions diff --git a/vendor/github.com/hashicorp/go-version/CHANGELOG.md b/vendor/github.com/hashicorp/go-version/CHANGELOG.md index 2020c4727432..5f16dd140c3f 100644 --- a/vendor/github.com/hashicorp/go-version/CHANGELOG.md +++ b/vendor/github.com/hashicorp/go-version/CHANGELOG.md @@ -1,4 +1,17 @@ -# 1.4.0 (January 5, 2021) +# 1.6.0 (June 28, 2022) + +FEATURES: + +- Add `Prerelease` function to `Constraint` to return true if the version includes a prerelease field ([#100](https://github.com/hashicorp/go-version/pull/100)) + +# 1.5.0 (May 18, 2022) + +FEATURES: + +- Use `encoding` `TextMarshaler` & `TextUnmarshaler` instead of JSON equivalents ([#95](https://github.com/hashicorp/go-version/pull/95)) +- Add JSON handlers to allow parsing from/to JSON ([#93](https://github.com/hashicorp/go-version/pull/93)) + +# 1.4.0 (January 5, 2022) FEATURES: diff --git a/vendor/github.com/hashicorp/go-version/README.md b/vendor/github.com/hashicorp/go-version/README.md index 851a337beb41..4d2505090335 100644 --- a/vendor/github.com/hashicorp/go-version/README.md +++ b/vendor/github.com/hashicorp/go-version/README.md @@ -1,5 +1,5 @@ # Versioning Library for Go -[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/master.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/master) +[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/main.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/main) [![GoDoc](https://godoc.org/github.com/hashicorp/go-version?status.svg)](https://godoc.org/github.com/hashicorp/go-version) go-version is a library for parsing versions and version constraints, diff --git a/vendor/github.com/hashicorp/go-version/constraint.go b/vendor/github.com/hashicorp/go-version/constraint.go index 1d8809028109..da5d1aca1480 100644 --- a/vendor/github.com/hashicorp/go-version/constraint.go +++ b/vendor/github.com/hashicorp/go-version/constraint.go @@ -163,6 +163,12 @@ func (c *Constraint) Check(v *Version) bool { return c.f(v, c.check) } +// Prerelease returns true if the version underlying this constraint +// contains a prerelease field. +func (c *Constraint) Prerelease() bool { + return len(c.check.Prerelease()) > 0 +} + func (c *Constraint) String() string { return c.original } diff --git a/vendor/github.com/hashicorp/go-version/version.go b/vendor/github.com/hashicorp/go-version/version.go index 116a74466db4..e87df69906d8 100644 --- a/vendor/github.com/hashicorp/go-version/version.go +++ b/vendor/github.com/hashicorp/go-version/version.go @@ -388,3 +388,20 @@ func (v *Version) String() string { func (v *Version) Original() string { return v.original } + +// UnmarshalText implements encoding.TextUnmarshaler interface. +func (v *Version) UnmarshalText(b []byte) error { + temp, err := NewVersion(string(b)) + if err != nil { + return err + } + + *v = *temp + + return nil +} + +// MarshalText implements encoding.TextMarshaler interface. +func (v *Version) MarshalText() ([]byte, error) { + return []byte(v.String()), nil +} diff --git a/vendor/github.com/hashicorp/hc-install/README.md b/vendor/github.com/hashicorp/hc-install/README.md index 87c06a203469..eb287ff0fc7a 100644 --- a/vendor/github.com/hashicorp/hc-install/README.md +++ b/vendor/github.com/hashicorp/hc-install/README.md @@ -31,7 +31,7 @@ The `Installer` offers a few high-level methods: The `Installer` methods accept number of different `Source` types. Each comes with different trade-offs described below. - - `fs.{AnyVersion,ExactVersion}` - Finds a binary in `$PATH` (or additional paths) + - `fs.{AnyVersion,ExactVersion,Version}` - Finds a binary in `$PATH` (or additional paths) - **Pros:** - This is most convenient when you already have the product installed on your system which you already manage. diff --git a/vendor/github.com/hashicorp/hc-install/fs/version.go b/vendor/github.com/hashicorp/hc-install/fs/version.go new file mode 100644 index 000000000000..26633b8afc89 --- /dev/null +++ b/vendor/github.com/hashicorp/hc-install/fs/version.go @@ -0,0 +1,97 @@ +package fs + +import ( + "context" + "fmt" + "log" + "path/filepath" + "time" + + "github.com/hashicorp/go-version" + "github.com/hashicorp/hc-install/errors" + "github.com/hashicorp/hc-install/internal/src" + "github.com/hashicorp/hc-install/internal/validators" + "github.com/hashicorp/hc-install/product" +) + +// Version finds the first executable binary of the product name +// which matches the version constraint within system $PATH and any declared ExtraPaths +// (which are *appended* to any directories in $PATH) +type Version struct { + Product product.Product + Constraints version.Constraints + ExtraPaths []string + Timeout time.Duration + + logger *log.Logger +} + +func (*Version) IsSourceImpl() src.InstallSrcSigil { + return src.InstallSrcSigil{} +} + +func (v *Version) SetLogger(logger *log.Logger) { + v.logger = logger +} + +func (v *Version) log() *log.Logger { + if v.logger == nil { + return discardLogger + } + return v.logger +} + +func (v *Version) Validate() error { + if !validators.IsBinaryNameValid(v.Product.BinaryName()) { + return fmt.Errorf("invalid binary name: %q", v.Product.BinaryName()) + } + if len(v.Constraints) == 0 { + return fmt.Errorf("undeclared version constraints") + } + if v.Product.GetVersion == nil { + return fmt.Errorf("undeclared version getter") + } + return nil +} + +func (v *Version) Find(ctx context.Context) (string, error) { + timeout := defaultTimeout + if v.Timeout > 0 { + timeout = v.Timeout + } + ctx, cancelFunc := context.WithTimeout(ctx, timeout) + defer cancelFunc() + + execPath, err := findFile(lookupDirs(v.ExtraPaths), v.Product.BinaryName(), func(file string) error { + err := checkExecutable(file) + if err != nil { + return err + } + + ver, err := v.Product.GetVersion(ctx, file) + if err != nil { + return err + } + + for _, vc := range v.Constraints { + if !vc.Check(ver) { + return fmt.Errorf("version (%s) doesn't meet constraints %s", ver, vc.String()) + } + } + + return nil + }) + if err != nil { + return "", errors.SkippableErr(err) + } + + if !filepath.IsAbs(execPath) { + var err error + execPath, err = filepath.Abs(execPath) + if err != nil { + return "", errors.SkippableErr(err) + } + } + + return execPath, nil +} diff --git a/vendor/github.com/hashicorp/hc-install/product/vault.go b/vendor/github.com/hashicorp/hc-install/product/vault.go new file mode 100644 index 000000000000..d03bc4fabc20 --- /dev/null +++ b/vendor/github.com/hashicorp/hc-install/product/vault.go @@ -0,0 +1,54 @@ +package product + +import ( + "context" + "fmt" + "os/exec" + "regexp" + "runtime" + "strings" + + "github.com/hashicorp/go-version" + "github.com/hashicorp/hc-install/internal/build" +) + +var ( + vaultVersionOutputRe = regexp.MustCompile(`Vault ` + simpleVersionRe) + v1_17 = version.Must(version.NewVersion("1.17")) +) + +var Vault = Product{ + Name: "vault", + BinaryName: func() string { + if runtime.GOOS == "windows" { + return "vault.exe" + } + return "vault" + }, + GetVersion: func(ctx context.Context, path string) (*version.Version, error) { + cmd := exec.CommandContext(ctx, path, "version") + + out, err := cmd.Output() + if err != nil { + return nil, err + } + + stdout := strings.TrimSpace(string(out)) + + submatches := vaultVersionOutputRe.FindStringSubmatch(stdout) + if len(submatches) != 2 { + return nil, fmt.Errorf("unexpected number of version matches %d for %s", len(submatches), stdout) + } + v, err := version.NewVersion(submatches[1]) + if err != nil { + return nil, fmt.Errorf("unable to parse version %q: %w", submatches[1], err) + } + + return v, err + }, + BuildInstructions: &BuildInstructions{ + GitRepoURL: "https://github.com/hashicorp/vault.git", + PreCloneCheck: &build.GoIsInstalled{}, + Build: &build.GoBuild{Version: v1_17}, + }, +} diff --git a/vendor/github.com/hashicorp/hcl/v2/CHANGELOG.md b/vendor/github.com/hashicorp/hcl/v2/CHANGELOG.md index 449187cac9e5..9f6c23b1cdf5 100644 --- a/vendor/github.com/hashicorp/hcl/v2/CHANGELOG.md +++ b/vendor/github.com/hashicorp/hcl/v2/CHANGELOG.md @@ -1,5 +1,52 @@ # HCL Changelog +## v2.13.0 (June 22, 2022) + +### Enhancements + +* hcl: `hcl.Diagnostic` how has an additional field `Extra` which is intended for carrying arbitrary supporting data ("extra information") related to the diagnostic message, intended to allow diagnostic renderers to optionally tailor the presentation of messages for particular situations. ([#539](https://github.com/hashicorp/hcl/pull/539)) +* hclsyntax: When an error occurs during a function call, the returned diagnostics will include _extra information_ (as described in the previous point) about which function was being called and, if the message is about an error returned by the function itself, that raw `error` value without any post-processing. ([#539](https://github.com/hashicorp/hcl/pull/539)) + +### Bugs Fixed + +* hclwrite: Fixed a potential data race for any situation where `hclwrite.Format` runs concurrently with itself. ([#534](https://github.com/hashicorp/hcl/pull/534)) + +## v2.12.0 (April 22, 2022) + +### Enhancements + +* hclsyntax: Evaluation of conditional expressions will now produce more precise error messages about inconsistencies between the types of the true and false result expressions, particularly in cases where both are of the same structural type kind but differ in their nested elements. ([#530](https://github.com/hashicorp/hcl/pull/530)) +* hclsyntax: The lexer will no longer allocate a small object on the heap for each token. Instead, in that situation it will allocate only when needed to return a diagnostic message with source location information. ([#490](https://github.com/hashicorp/hcl/pull/490)) +* hclwrite: New functions `TokensForTuple`, `TokensForObject`, and `TokensForFunctionCall` allow for more easily constructing the three constructs which are supported for static analysis and which HCL-based languages typically use in contexts where an expression is used only for its syntax, and not evaluated to produce a real value. For example, these new functions together are sufficient to construct all valid type constraint expressions from [the Type Expressions Extension](./ext/typeexpr/), which is the basis of variable type constraints in the Terraform language at the time of writing. ([#502](https://github.com/hashicorp/hcl/pull/502)) +* json: New functions `IsJSONExpression` and `IsJSONBody` to determine if a given expression or body was created by the JSON syntax parser. In normal situations it's better not to worry about what syntax a particular expression/body originated in, but this can be useful in some trickier cases where an application needs to shim for backwards-compatibility or for static analysis that needs to have special handling of the JSON syntax's embedded expression/template conventions. ([#524](https://github.com/hashicorp/hcl/pull/524)) + +### Bugs Fixed + +* gohcl: Fix docs about supported types for blocks. ([#507](https://github.com/hashicorp/hcl/pull/507)) + +## v2.11.1 (December 1, 2021) + +### Bugs Fixed + +* hclsyntax: The type for an upgraded unknown value with a splat expression cannot be known ([#495](https://github.com/hashicorp/hcl/pull/495)) + +## v2.11.0 (December 1, 2021) + +### Enhancements + +* hclsyntax: Various error messages related to unexpectedly reaching end of file while parsing a delimited subtree will now return specialized messages describing the opening tokens as "unclosed", instead of returning a generic diagnostic that just happens to refer to the empty source range at the end of the file. This gives better feedback when error messages are being presented alongside a source code snippet, as is common in HCL-based applications, because it shows which innermost container the parser was working on when it encountered the error. ([#492](https://github.com/hashicorp/hcl/pull/492)) + +### Bugs Fixed + +* hclsyntax: Upgrading an unknown single value to a list using a splat expression must return unknown ([#493](https://github.com/hashicorp/hcl/pull/493)) + +## v2.10.1 (July 21, 2021) + +* dynblock: Decode unknown dynamic blocks in order to obtain any diagnostics even though the decoded value is not used ([#476](https://github.com/hashicorp/hcl/pull/476)) +* hclsyntax: Calling functions is now more robust in the face of an incorrectly-implemented function which returns a `function.ArgError` whose argument index is out of range for the length of the arguments. Previously this would often lead to a panic, but now it'll return a less-precice error message instead. Functions that return out-of-bounds argument indices still ought to be fixed so that the resulting error diagnostics can be as precise as possible. ([#472](https://github.com/hashicorp/hcl/pull/472)) +* hclsyntax: Ensure marks on unknown values are maintained when processing string templates. ([#478](https://github.com/hashicorp/hcl/pull/478)) +* hcl: Improved error messages for various common error situtions in `hcl.Index` and `hcl.GetAttr`. These are part of the implementation of indexing and attribute lookup in the native syntax expression language too, so the new error messages will apply to problems using those operators. ([#474](https://github.com/hashicorp/hcl/pull/474)) + ## v2.10.0 (April 20, 2021) ### Enhancements diff --git a/vendor/github.com/hashicorp/hcl/v2/diagnostic.go b/vendor/github.com/hashicorp/hcl/v2/diagnostic.go index c80535b7a73f..bcf4eb39c03d 100644 --- a/vendor/github.com/hashicorp/hcl/v2/diagnostic.go +++ b/vendor/github.com/hashicorp/hcl/v2/diagnostic.go @@ -63,6 +63,28 @@ type Diagnostic struct { // case of colliding names. Expression Expression EvalContext *EvalContext + + // Extra is an extension point for additional machine-readable information + // about this problem. + // + // Recipients of diagnostic objects may type-assert this value with + // specific interface types they know about to discover if any additional + // information is available that is interesting for their use-case. + // + // Extra is always considered to be optional extra information and so a + // diagnostic message should still always be fully described (from the + // perspective of a human who understands the language the messages are + // written in) by the other fields in case a particular recipient. + // + // Functions that return diagnostics with Extra populated should typically + // document that they place values implementing a particular interface, + // rather than a concrete type, and define that interface such that its + // methods can dynamically indicate a lack of support at runtime even + // if the interface happens to be statically available. An Extra + // type that wraps other Extra values should additionally implement + // interface DiagnosticExtraUnwrapper to return the value they are wrapping + // so that callers can access inner values to type-assert against. + Extra interface{} } // Diagnostics is a list of Diagnostic instances. @@ -141,3 +163,24 @@ type DiagnosticWriter interface { WriteDiagnostic(*Diagnostic) error WriteDiagnostics(Diagnostics) error } + +// DiagnosticExtraUnwrapper is an interface implemented by values in the +// Extra field of Diagnostic when they are wrapping another "Extra" value that +// was generated downstream. +// +// Diagnostic recipients which want to examine "Extra" values to sniff for +// particular types of extra data can either type-assert this interface +// directly and repeatedly unwrap until they recieve nil, or can use the +// helper function DiagnosticExtra. +type DiagnosticExtraUnwrapper interface { + // If the reciever is wrapping another "diagnostic extra" value, returns + // that value. Otherwise returns nil to indicate dynamically that nothing + // is wrapped. + // + // The "nothing is wrapped" condition can be signalled either by this + // method returning nil or by a type not implementing this interface at all. + // + // Implementers should never create unwrap "cycles" where a nested extra + // value returns a value that was also wrapping it. + UnwrapDiagnosticExtra() interface{} +} diff --git a/vendor/github.com/hashicorp/hcl/v2/diagnostic_typeparams.go b/vendor/github.com/hashicorp/hcl/v2/diagnostic_typeparams.go new file mode 100644 index 000000000000..6994e2336dc5 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/v2/diagnostic_typeparams.go @@ -0,0 +1,39 @@ +//go:build go1.18 +// +build go1.18 + +package hcl + +// This file contains additional diagnostics-related symbols that use the +// Go 1.18 type parameters syntax and would therefore be incompatible with +// Go 1.17 and earlier. + +// DiagnosticExtra attempts to retrieve an "extra value" of type T from the +// given diagnostic, if either the diag.Extra field directly contains a value +// of that type or the value implements DiagnosticExtraUnwrapper and directly +// or indirectly returns a value of that type. +// +// Type T should typically be an interface type, so that code which generates +// diagnostics can potentially return different implementations of the same +// interface dynamically as needed. +// +// If a value of type T is found, returns that value and true to indicate +// success. Otherwise, returns the zero value of T and false to indicate +// failure. +func DiagnosticExtra[T any](diag *Diagnostic) (T, bool) { + extra := diag.Extra + var zero T + + for { + if ret, ok := extra.(T); ok { + return ret, true + } + + if unwrap, ok := extra.(DiagnosticExtraUnwrapper); ok { + // If our "extra" implements DiagnosticExtraUnwrapper then we'll + // unwrap one level and try this again. + extra = unwrap.UnwrapDiagnosticExtra() + } else { + return zero, false + } + } +} diff --git a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/expression.go b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/expression.go index 63f2e88ec778..358fd5d5108e 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/expression.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/expression.go @@ -2,6 +2,7 @@ package hclsyntax import ( "fmt" + "sort" "sync" "github.com/hashicorp/hcl/v2" @@ -25,7 +26,7 @@ type Expression interface { } // Assert that Expression implements hcl.Expression -var assertExprImplExpr hcl.Expression = Expression(nil) +var _ hcl.Expression = Expression(nil) // ParenthesesExpr represents an expression written in grouping // parentheses. @@ -269,6 +270,10 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti } } + diagExtra := functionCallDiagExtra{ + calledFunctionName: e.Name, + } + params := f.Params() varParam := f.VarParam() @@ -296,6 +301,7 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti Context: e.Range().Ptr(), Expression: expandExpr, EvalContext: ctx, + Extra: &diagExtra, }) return cty.DynamicVal, diags } @@ -310,6 +316,7 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti Context: e.Range().Ptr(), Expression: expandExpr, EvalContext: ctx, + Extra: &diagExtra, }) return cty.DynamicVal, diags } @@ -341,6 +348,7 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti Context: e.Range().Ptr(), Expression: expandExpr, EvalContext: ctx, + Extra: &diagExtra, }) return cty.DynamicVal, diags } @@ -364,6 +372,7 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti Context: e.Range().Ptr(), Expression: e, EvalContext: ctx, + Extra: &diagExtra, }, } } @@ -381,6 +390,7 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti Context: e.Range().Ptr(), Expression: e, EvalContext: ctx, + Extra: &diagExtra, }, } } @@ -425,6 +435,7 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti Context: e.Range().Ptr(), Expression: argExpr, EvalContext: ctx, + Extra: &diagExtra, }) } } @@ -441,6 +452,10 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti resultVal, err := f.Call(argVals) if err != nil { + // For errors in the underlying call itself we also return the raw + // call error via an extra method on our "diagnostic extra" value. + diagExtra.functionCallError = err + switch terr := err.(type) { case function.ArgError: i := terr.Index @@ -451,22 +466,57 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti param = varParam } - // this can happen if an argument is (incorrectly) null. - if i > len(e.Args)-1 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid function argument", - Detail: fmt.Sprintf( - "Invalid value for %q parameter: %s.", - param.Name, err, - ), - Subject: args[len(params)].StartRange().Ptr(), - Context: e.Range().Ptr(), - Expression: e, - EvalContext: ctx, - }) + if param == nil || i > len(args)-1 { + // Getting here means that the function we called has a bug: + // it returned an arg error that refers to an argument index + // that wasn't present in the call. For that situation + // we'll degrade to a less specific error just to give + // some sort of answer, but best to still fix the buggy + // function so that it only returns argument indices that + // are in range. + switch { + case param != nil: + // In this case we'll assume that the function was trying + // to talk about a final variadic parameter but the caller + // didn't actually provide any arguments for it. That means + // we can at least still name the parameter in the + // error message, but our source range will be the call + // as a whole because we don't have an argument expression + // to highlight specifically. + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid function argument", + Detail: fmt.Sprintf( + "Invalid value for %q parameter: %s.", + param.Name, err, + ), + Subject: e.Range().Ptr(), + Expression: e, + EvalContext: ctx, + Extra: &diagExtra, + }) + default: + // This is the most degenerate case of all, where the + // index is out of range even for the declared parameters, + // and so we can't tell which parameter the function is + // trying to report an error for. Just a generic error + // report in that case. + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Error in function call", + Detail: fmt.Sprintf( + "Call to function %q failed: %s.", + e.Name, err, + ), + Subject: e.StartRange().Ptr(), + Context: e.Range().Ptr(), + Expression: e, + EvalContext: ctx, + Extra: &diagExtra, + }) + } } else { - argExpr := e.Args[i] + argExpr := args[i] // TODO: we should also unpick a PathError here and show the // path to the deep value where the error was detected. @@ -481,6 +531,7 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti Context: e.Range().Ptr(), Expression: argExpr, EvalContext: ctx, + Extra: &diagExtra, }) } @@ -496,6 +547,7 @@ func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnosti Context: e.Range().Ptr(), Expression: e, EvalContext: ctx, + Extra: &diagExtra, }) } @@ -528,6 +580,39 @@ func (e *FunctionCallExpr) ExprCall() *hcl.StaticCall { return ret } +// FunctionCallDiagExtra is an interface implemented by the value in the "Extra" +// field of some diagnostics returned by FunctionCallExpr.Value, giving +// cooperating callers access to some machine-readable information about the +// call that a diagnostic relates to. +type FunctionCallDiagExtra interface { + // CalledFunctionName returns the name of the function being called at + // the time the diagnostic was generated, if any. Returns an empty string + // if there is no known called function. + CalledFunctionName() string + + // FunctionCallError returns the error value returned by the implementation + // of the function being called, if any. Returns nil if the diagnostic was + // not returned in response to a call error. + // + // Some errors related to calling functions are generated by HCL itself + // rather than by the underlying function, in which case this method + // will return nil. + FunctionCallError() error +} + +type functionCallDiagExtra struct { + calledFunctionName string + functionCallError error +} + +func (e *functionCallDiagExtra) CalledFunctionName() string { + return e.calledFunctionName +} + +func (e *functionCallDiagExtra) FunctionCallError() error { + return e.functionCallError +} + type ConditionalExpr struct { Condition Expression TrueResult Expression @@ -582,12 +667,8 @@ func (e *ConditionalExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostic Severity: hcl.DiagError, Summary: "Inconsistent conditional result types", Detail: fmt.Sprintf( - // FIXME: Need a helper function for showing natural-language type diffs, - // since this will generate some useless messages in some cases, like - // "These expressions are object and object respectively" if the - // object types don't exactly match. - "The true and false result expressions must have consistent types. The given expressions are %s and %s, respectively.", - trueResult.Type().FriendlyName(), falseResult.Type().FriendlyName(), + "The true and false result expressions must have consistent types. %s.", + describeConditionalTypeMismatch(trueResult.Type(), falseResult.Type()), ), Subject: hcl.RangeBetween(e.TrueResult.Range(), e.FalseResult.Range()).Ptr(), Context: &e.SrcRange, @@ -619,7 +700,7 @@ func (e *ConditionalExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostic diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Incorrect condition type", - Detail: fmt.Sprintf("The condition expression must be of type bool."), + Detail: "The condition expression must be of type bool.", Subject: e.Condition.Range().Ptr(), Context: &e.SrcRange, Expression: e.Condition, @@ -679,6 +760,144 @@ func (e *ConditionalExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostic } } +// describeConditionalTypeMismatch makes a best effort to describe the +// difference between types in the true and false arms of a conditional +// expression in a way that would be useful to someone trying to understand +// why their conditional expression isn't valid. +// +// NOTE: This function is only designed to deal with situations +// where trueTy and falseTy are different. Calling it with two equal +// types will produce a nonsense result. This function also only really +// deals with situations that type unification can't resolve, so we should +// call this function only after trying type unification first. +func describeConditionalTypeMismatch(trueTy, falseTy cty.Type) string { + // The main tricky cases here are when both trueTy and falseTy are + // of the same structural type kind, such as both being object types + // or both being tuple types. In that case the "FriendlyName" method + // returns only "object" or "tuple" and so we need to do some more + // work to describe what's different inside them. + + switch { + case trueTy.IsObjectType() && falseTy.IsObjectType(): + // We'll first gather up the attribute names and sort them. In the + // event that there are multiple attributes that disagree across + // the two types, we'll prefer to report the one that sorts lexically + // least just so that our error message is consistent between + // evaluations. + var trueAttrs, falseAttrs []string + for name := range trueTy.AttributeTypes() { + trueAttrs = append(trueAttrs, name) + } + sort.Strings(trueAttrs) + for name := range falseTy.AttributeTypes() { + falseAttrs = append(falseAttrs, name) + } + sort.Strings(falseAttrs) + + for _, name := range trueAttrs { + if !falseTy.HasAttribute(name) { + return fmt.Sprintf("The 'true' value includes object attribute %q, which is absent in the 'false' value", name) + } + trueAty := trueTy.AttributeType(name) + falseAty := falseTy.AttributeType(name) + if !trueAty.Equals(falseAty) { + // For deeply-nested differences this will likely get very + // clunky quickly by nesting these messages inside one another, + // but we'll accept that for now in the interests of producing + // _some_ useful feedback, even if it isn't as concise as + // we'd prefer it to be. Deeply-nested structures in + // conditionals are thankfully not super common. + return fmt.Sprintf( + "Type mismatch for object attribute %q: %s", + name, describeConditionalTypeMismatch(trueAty, falseAty), + ) + } + } + for _, name := range falseAttrs { + if !trueTy.HasAttribute(name) { + return fmt.Sprintf("The 'false' value includes object attribute %q, which is absent in the 'true' value", name) + } + // NOTE: We don't need to check the attribute types again, because + // any attribute that both types have in common would already have + // been checked in the previous loop. + } + case trueTy.IsTupleType() && falseTy.IsTupleType(): + trueEtys := trueTy.TupleElementTypes() + falseEtys := falseTy.TupleElementTypes() + + if trueCount, falseCount := len(trueEtys), len(falseEtys); trueCount != falseCount { + return fmt.Sprintf("The 'true' tuple has length %d, but the 'false' tuple has length %d", trueCount, falseCount) + } + + // NOTE: Thanks to the condition above, we know that both tuples are + // of the same length and so they must have some differing types + // instead. + for i := range trueEtys { + trueEty := trueEtys[i] + falseEty := falseEtys[i] + + if !trueEty.Equals(falseEty) { + // For deeply-nested differences this will likely get very + // clunky quickly by nesting these messages inside one another, + // but we'll accept that for now in the interests of producing + // _some_ useful feedback, even if it isn't as concise as + // we'd prefer it to be. Deeply-nested structures in + // conditionals are thankfully not super common. + return fmt.Sprintf( + "Type mismatch for tuple element %d: %s", + i, describeConditionalTypeMismatch(trueEty, falseEty), + ) + } + } + case trueTy.IsCollectionType() && falseTy.IsCollectionType(): + // For this case we're specifically interested in the situation where: + // - both collections are of the same kind, AND + // - the element types of both are either object or tuple types. + // This is just to avoid writing a useless statement like + // "The 'true' value is list of object, but the 'false' value is list of object". + // This still doesn't account for more awkward cases like collections + // of collections of structural types, but we won't let perfect be + // the enemy of the good. + trueEty := trueTy.ElementType() + falseEty := falseTy.ElementType() + if (trueTy.IsListType() && falseTy.IsListType()) || (trueTy.IsMapType() && falseTy.IsMapType()) || (trueTy.IsSetType() && falseTy.IsSetType()) { + if (trueEty.IsObjectType() && falseEty.IsObjectType()) || (trueEty.IsTupleType() && falseEty.IsTupleType()) { + noun := "collection" + switch { // NOTE: We now know that trueTy and falseTy have the same collection kind + case trueTy.IsListType(): + noun = "list" + case trueTy.IsSetType(): + noun = "set" + case trueTy.IsMapType(): + noun = "map" + } + return fmt.Sprintf( + "Mismatched %s element types: %s", + noun, describeConditionalTypeMismatch(trueEty, falseEty), + ) + } + } + } + + // If we don't manage any more specialized message, we'll just report + // what the two types are. + trueName := trueTy.FriendlyName() + falseName := falseTy.FriendlyName() + if trueName == falseName { + // Absolute last resort for when we have no special rule above but + // we have two types with the same friendly name anyway. This is + // the most vague of all possible messages but is reserved for + // particularly awkward cases, like lists of lists of differing tuple + // types. + return "At least one deeply-nested attribute or element is not compatible across both the 'true' and the 'false' value" + } + return fmt.Sprintf( + "The 'true' value is %s, but the 'false' value is %s", + trueTy.FriendlyName(), falseTy.FriendlyName(), + ) + +} + func (e *ConditionalExpr) Range() hcl.Range { return e.SrcRange } @@ -1399,9 +1618,22 @@ func (e *SplatExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { return cty.DynamicVal, diags } + upgradedUnknown := false if autoUpgrade { + // If we're upgrading an unknown value to a tuple/list, the result + // cannot be known. Otherwise a tuple containing an unknown value will + // upgrade to a different number of elements depending on whether + // sourceVal becomes null or not. + // We record this condition here so we can process any remaining + // expression after the * to verify the result of the traversal. For + // example, it is valid to use a splat on a single object to retrieve a + // list of a single attribute, but we still need to check if that + // attribute actually exists. + upgradedUnknown = !sourceVal.IsKnown() + sourceVal = cty.TupleVal([]cty.Value{sourceVal}) sourceTy = sourceVal.Type() + } // We'll compute our result type lazily if we need it. In the normal case @@ -1466,6 +1698,10 @@ func (e *SplatExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { } e.Item.clearValue(ctx) // clean up our temporary value + if upgradedUnknown { + return cty.DynamicVal, diags + } + if !isKnown { // We'll ingore the resultTy diagnostics in this case since they // will just be the same errors we saw while iterating above. diff --git a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/expression_template.go b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/expression_template.go index 0b7e07a5b157..c3f96943d7fb 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/expression_template.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/expression_template.go @@ -48,6 +48,12 @@ func (e *TemplateExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) continue } + // Unmark the part and merge its marks into the set + unmarkedVal, partMarks := partVal.Unmark() + for k, v := range partMarks { + marks[k] = v + } + if !partVal.IsKnown() { // If any part is unknown then the result as a whole must be // unknown too. We'll keep on processing the rest of the parts @@ -57,7 +63,7 @@ func (e *TemplateExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) continue } - strVal, err := convert.Convert(partVal, cty.String) + strVal, err := convert.Convert(unmarkedVal, cty.String) if err != nil { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, @@ -74,13 +80,7 @@ func (e *TemplateExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) continue } - // Unmark the part and merge its marks into the set - unmarked, partMarks := strVal.Unmark() - for k, v := range partMarks { - marks[k] = v - } - - buf.WriteString(unmarked.AsString()) + buf.WriteString(strVal.AsString()) } var ret cty.Value diff --git a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go index eef13aaf456e..ec83d3dc23c7 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go @@ -76,14 +76,37 @@ Token: default: bad := p.Read() if !p.recovery { - if bad.Type == TokenOQuote { + switch bad.Type { + case TokenOQuote: diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Invalid argument name", Detail: "Argument names must not be quoted.", Subject: &bad.Range, }) - } else { + case TokenEOF: + switch end { + case TokenCBrace: + // If we're looking for a closing brace then we're parsing a block + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unclosed configuration block", + Detail: "There is no closing brace for this block before the end of the file. This may be caused by incorrect brace nesting elsewhere in this file.", + Subject: &startRange, + }) + default: + // The only other "end" should itself be TokenEOF (for + // the top-level body) and so we shouldn't get here, + // but we'll return a generic error message anyway to + // be resilient. + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unclosed configuration body", + Detail: "Found end of file before the end of this configuration body.", + Subject: &startRange, + }) + } + default: diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Argument or block definition required", @@ -144,8 +167,6 @@ func (p *parser) ParseBodyItem() (Node, hcl.Diagnostics) { }, } } - - return nil, nil } // parseSingleAttrBody is a weird variant of ParseBody that deals with the @@ -388,12 +409,23 @@ Token: // user intent for this one, we'll skip it if we're already in // recovery mode. if !p.recovery { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid single-argument block definition", - Detail: "A single-line block definition must end with a closing brace immediately after its single argument definition.", - Subject: p.Peek().Range.Ptr(), - }) + switch p.Peek().Type { + case TokenEOF: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unclosed configuration block", + Detail: "There is no closing brace for this block before the end of the file. This may be caused by incorrect brace nesting elsewhere in this file.", + Subject: oBrace.Range.Ptr(), + Context: hcl.RangeBetween(ident.Range, oBrace.Range).Ptr(), + }) + default: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid single-argument block definition", + Detail: "A single-line block definition must end with a closing brace immediately after its single argument definition.", + Subject: p.Peek().Range.Ptr(), + }) + } } p.recover(TokenCBrace) } @@ -1059,12 +1091,22 @@ func (p *parser) parseExpressionTerm() (Expression, hcl.Diagnostics) { default: var diags hcl.Diagnostics if !p.recovery { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid expression", - Detail: "Expected the start of an expression, but found an invalid expression token.", - Subject: &start.Range, - }) + switch start.Type { + case TokenEOF: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Missing expression", + Detail: "Expected the start of an expression, but found the end of the file.", + Subject: &start.Range, + }) + default: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid expression", + Detail: "Expected the start of an expression, but found an invalid expression token.", + Subject: &start.Range, + }) + } } p.setRecovery() @@ -1163,13 +1205,23 @@ Token: } if sep.Type != TokenComma { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing argument separator", - Detail: "A comma is required to separate each function argument from the next.", - Subject: &sep.Range, - Context: hcl.RangeBetween(name.Range, sep.Range).Ptr(), - }) + switch sep.Type { + case TokenEOF: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unterminated function call", + Detail: "There is no closing parenthesis for this function call before the end of the file. This may be caused by incorrect parethesis nesting elsewhere in this file.", + Subject: hcl.RangeBetween(name.Range, openTok.Range).Ptr(), + }) + default: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Missing argument separator", + Detail: "A comma is required to separate each function argument from the next.", + Subject: &sep.Range, + Context: hcl.RangeBetween(name.Range, sep.Range).Ptr(), + }) + } closeTok = p.recover(TokenCParen) break Token } @@ -1242,13 +1294,23 @@ func (p *parser) parseTupleCons() (Expression, hcl.Diagnostics) { if next.Type != TokenComma { if !p.recovery { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing item separator", - Detail: "Expected a comma to mark the beginning of the next item.", - Subject: &next.Range, - Context: hcl.RangeBetween(open.Range, next.Range).Ptr(), - }) + switch next.Type { + case TokenEOF: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unterminated tuple constructor expression", + Detail: "There is no corresponding closing bracket before the end of the file. This may be caused by incorrect bracket nesting elsewhere in this file.", + Subject: open.Range.Ptr(), + }) + default: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Missing item separator", + Detail: "Expected a comma to mark the beginning of the next item.", + Subject: &next.Range, + Context: hcl.RangeBetween(open.Range, next.Range).Ptr(), + }) + } } close = p.recover(TokenCBrack) break @@ -1359,6 +1421,13 @@ func (p *parser) parseObjectCons() (Expression, hcl.Diagnostics) { Subject: &next.Range, Context: hcl.RangeBetween(open.Range, next.Range).Ptr(), }) + case TokenEOF: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unterminated object constructor expression", + Detail: "There is no corresponding closing brace before the end of the file. This may be caused by incorrect brace nesting elsewhere in this file.", + Subject: open.Range.Ptr(), + }) default: diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, @@ -1399,13 +1468,23 @@ func (p *parser) parseObjectCons() (Expression, hcl.Diagnostics) { if next.Type != TokenComma && next.Type != TokenNewline { if !p.recovery { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing attribute separator", - Detail: "Expected a newline or comma to mark the beginning of the next attribute.", - Subject: &next.Range, - Context: hcl.RangeBetween(open.Range, next.Range).Ptr(), - }) + switch next.Type { + case TokenEOF: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unterminated object constructor expression", + Detail: "There is no corresponding closing brace before the end of the file. This may be caused by incorrect brace nesting elsewhere in this file.", + Subject: open.Range.Ptr(), + }) + default: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Missing attribute separator", + Detail: "Expected a newline or comma to mark the beginning of the next attribute.", + Subject: &next.Range, + Context: hcl.RangeBetween(open.Range, next.Range).Ptr(), + }) + } } close = p.recover(TokenCBrace) break @@ -1661,7 +1740,7 @@ func (p *parser) parseQuotedStringLiteral() (string, hcl.Range, hcl.Diagnostics) var diags hcl.Diagnostics ret := &bytes.Buffer{} - var cQuote Token + var endRange hcl.Range Token: for { @@ -1669,7 +1748,7 @@ Token: switch tok.Type { case TokenCQuote: - cQuote = tok + endRange = tok.Range break Token case TokenQuotedLit: @@ -1712,6 +1791,7 @@ Token: Subject: &tok.Range, Context: hcl.RangeBetween(oQuote.Range, tok.Range).Ptr(), }) + endRange = tok.Range break Token default: @@ -1724,13 +1804,14 @@ Token: Context: hcl.RangeBetween(oQuote.Range, tok.Range).Ptr(), }) p.recover(TokenCQuote) + endRange = tok.Range break Token } } - return ret.String(), hcl.RangeBetween(oQuote.Range, cQuote.Range), diags + return ret.String(), hcl.RangeBetween(oQuote.Range, endRange), diags } // ParseStringLiteralToken processes the given token, which must be either a diff --git a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser_template.go b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser_template.go index 02181fc799c2..ae8805856cd6 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser_template.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser_template.go @@ -414,22 +414,42 @@ Token: if close.Type != TokenTemplateSeqEnd { if !p.recovery { switch close.Type { - case TokenColon: + case TokenEOF: diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, - Summary: "Extra characters after interpolation expression", - Detail: "Template interpolation doesn't expect a colon at this location. Did you intend this to be a literal sequence to be processed as part of another language? If so, you can escape it by starting with \"$${\" instead of just \"${\".", - Subject: &close.Range, - Context: hcl.RangeBetween(startRange, close.Range).Ptr(), + Summary: "Unclosed template interpolation sequence", + Detail: "There is no closing brace for this interpolation sequence before the end of the file. This might be caused by incorrect nesting inside the given expression.", + Subject: &startRange, }) - default: + case TokenColon: diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Extra characters after interpolation expression", - Detail: "Expected a closing brace to end the interpolation expression, but found extra characters.\n\nThis can happen when you include interpolation syntax for another language, such as shell scripting, but forget to escape the interpolation start token. If this is an embedded sequence for another language, escape it by starting with \"$${\" instead of just \"${\".", + Detail: "Template interpolation doesn't expect a colon at this location. Did you intend this to be a literal sequence to be processed as part of another language? If so, you can escape it by starting with \"$${\" instead of just \"${\".", Subject: &close.Range, Context: hcl.RangeBetween(startRange, close.Range).Ptr(), }) + default: + if (close.Type == TokenCQuote || close.Type == TokenOQuote) && end == TokenCQuote { + // We'll get here if we're processing a _quoted_ + // template and we find an errant quote inside an + // interpolation sequence, which suggests that + // the interpolation sequence is missing its terminator. + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unclosed template interpolation sequence", + Detail: "There is no closing brace for this interpolation sequence before the end of the quoted template. This might be caused by incorrect nesting inside the given expression.", + Subject: &startRange, + }) + } else { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Extra characters after interpolation expression", + Detail: "Expected a closing brace to end the interpolation expression, but found extra characters.\n\nThis can happen when you include interpolation syntax for another language, such as shell scripting, but forget to escape the interpolation start token. If this is an embedded sequence for another language, escape it by starting with \"$${\" instead of just \"${\".", + Subject: &close.Range, + Context: hcl.RangeBetween(startRange, close.Range).Ptr(), + }) + } } } p.recover(TokenTemplateSeqEnd) diff --git a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/spec.md b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/spec.md index 550bd93adf15..33c152daa898 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/spec.md +++ b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/spec.md @@ -293,18 +293,20 @@ Between the open and closing delimiters of these sequences, newline sequences are ignored as whitespace. There is a syntax ambiguity between _for expressions_ and collection values -whose first element is a reference to a variable named `for`. The -_for expression_ interpretation has priority, so to produce a tuple whose -first element is the value of a variable named `for`, or an object with a -key named `for`, use parentheses to disambiguate: +whose first element starts with an identifier named `for`. The _for expression_ +interpretation has priority, so to write a key literally named `for` +or an expression derived from a variable named `for` you must use parentheses +or quotes to disambiguate: - `[for, foo, baz]` is a syntax error. - `[(for), foo, baz]` is a tuple whose first element is the value of variable `for`. -- `{for: 1, baz: 2}` is a syntax error. -- `{(for): 1, baz: 2}` is an object with an attribute literally named `for`. -- `{baz: 2, for: 1}` is equivalent to the previous example, and resolves the +- `{for = 1, baz = 2}` is a syntax error. +- `{"for" = 1, baz = 2}` is an object with an attribute literally named `for`. +- `{baz = 2, for = 1}` is equivalent to the previous example, and resolves the ambiguity by reordering. +- `{(for) = 1, baz = 2}` is an object with a key with the same value as the + variable `for`. ### Template Expressions @@ -489,7 +491,7 @@ that were produced against each distinct key. - `[for v in ["a", "b"]: v]` returns `["a", "b"]`. - `[for i, v in ["a", "b"]: i]` returns `[0, 1]`. - `{for i, v in ["a", "b"]: v => i}` returns `{a = 0, b = 1}`. -- `{for i, v in ["a", "a", "b"]: k => v}` produces an error, because attribute +- `{for i, v in ["a", "a", "b"]: v => i}` produces an error, because attribute `a` is defined twice. - `{for i, v in ["a", "a", "b"]: v => i...}` returns `{a = [0, 1], b = [2]}`. @@ -888,7 +890,7 @@ as templates. - `hello ${true}` produces the string `"hello true"` - `${""}${true}` produces the string `"true"` because there are two interpolation sequences, even though one produces an empty result. -- `%{ for v in [true] }${v}%{ endif }` produces the string `true` because +- `%{ for v in [true] }${v}%{ endfor }` produces the string `true` because the presence of the `for` directive circumvents the unwrapping even though the final result is a single value. diff --git a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/structure.go b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/structure.go index 2f7470c7724a..f42ae918ee62 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/structure.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/structure.go @@ -13,17 +13,12 @@ func (b *Block) AsHCLBlock() *hcl.Block { return nil } - lastHeaderRange := b.TypeRange - if len(b.LabelRanges) > 0 { - lastHeaderRange = b.LabelRanges[len(b.LabelRanges)-1] - } - return &hcl.Block{ Type: b.Type, Labels: b.Labels, Body: b.Body, - DefRange: hcl.RangeBetween(b.TypeRange, lastHeaderRange), + DefRange: b.DefRange(), TypeRange: b.TypeRange, LabelRanges: b.LabelRanges, } @@ -40,7 +35,7 @@ type Body struct { hiddenBlocks map[string]struct{} SrcRange hcl.Range - EndRange hcl.Range // Final token of the body, for reporting missing items + EndRange hcl.Range // Final token of the body (zero-length range) } // Assert that *Body implements hcl.Body @@ -390,5 +385,9 @@ func (b *Block) Range() hcl.Range { } func (b *Block) DefRange() hcl.Range { - return hcl.RangeBetween(b.TypeRange, b.OpenBraceRange) + lastHeaderRange := b.TypeRange + if len(b.LabelRanges) > 0 { + lastHeaderRange = b.LabelRanges[len(b.LabelRanges)-1] + } + return hcl.RangeBetween(b.TypeRange, lastHeaderRange) } diff --git a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/token.go b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/token.go index f4c6c9342422..5ef093f9adf5 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/token.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/token.go @@ -191,8 +191,10 @@ func checkInvalidTokens(tokens Tokens) hcl.Diagnostics { toldBadUTF8 := 0 for _, tok := range tokens { - // copy token so it's safe to point to it - tok := tok + tokRange := func() *hcl.Range { + r := tok.Range + return &r + } switch tok.Type { case TokenBitwiseAnd, TokenBitwiseOr, TokenBitwiseXor, TokenBitwiseNot: @@ -211,7 +213,7 @@ func checkInvalidTokens(tokens Tokens) hcl.Diagnostics { Severity: hcl.DiagError, Summary: "Unsupported operator", Detail: fmt.Sprintf("Bitwise operators are not supported.%s", suggestion), - Subject: &tok.Range, + Subject: tokRange(), }) toldBitwise++ } @@ -221,7 +223,7 @@ func checkInvalidTokens(tokens Tokens) hcl.Diagnostics { Severity: hcl.DiagError, Summary: "Unsupported operator", Detail: "\"**\" is not a supported operator. Exponentiation is not supported as an operator.", - Subject: &tok.Range, + Subject: tokRange(), }) toldExponent++ @@ -234,7 +236,7 @@ func checkInvalidTokens(tokens Tokens) hcl.Diagnostics { Severity: hcl.DiagError, Summary: "Invalid character", Detail: "The \"`\" character is not valid. To create a multi-line string, use the \"heredoc\" syntax, like \"< 0 { + if _, err := w.Write(line); err != nil { + return err + } + } + if err != nil { + if errors.Is(err, io.EOF) { + return nil + } + + return err + } + } +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/cmd_default.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/cmd_default.go index 2e88dd3e6aca..6d7b768ee7c7 100644 --- a/vendor/github.com/hashicorp/terraform-exec/tfexec/cmd_default.go +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/cmd_default.go @@ -1,3 +1,4 @@ +//go:build !linux // +build !linux package tfexec @@ -6,26 +7,12 @@ import ( "context" "os/exec" "strings" + "sync" ) func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { var errBuf strings.Builder - cmd.Stdout = mergeWriters(cmd.Stdout, tf.stdout) - cmd.Stderr = mergeWriters(cmd.Stderr, tf.stderr, &errBuf) - - go func() { - <-ctx.Done() - if ctx.Err() == context.DeadlineExceeded || ctx.Err() == context.Canceled { - if cmd != nil && cmd.Process != nil && cmd.ProcessState != nil { - err := cmd.Process.Kill() - if err != nil { - tf.logger.Printf("error from kill: %s", err) - } - } - } - }() - // check for early cancellation select { case <-ctx.Done(): @@ -33,7 +20,52 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { default: } - err := cmd.Run() + // Read stdout / stderr logs from pipe instead of setting cmd.Stdout and + // cmd.Stderr because it can cause hanging when killing the command + // https://github.com/golang/go/issues/23019 + stdoutWriter := mergeWriters(cmd.Stdout, tf.stdout) + stderrWriter := mergeWriters(tf.stderr, &errBuf) + + cmd.Stderr = nil + cmd.Stdout = nil + + stdoutPipe, err := cmd.StdoutPipe() + if err != nil { + return err + } + + stderrPipe, err := cmd.StderrPipe() + if err != nil { + return err + } + + err = cmd.Start() + if err == nil && ctx.Err() != nil { + err = ctx.Err() + } + if err != nil { + return tf.wrapExitError(ctx, err, "") + } + + var errStdout, errStderr error + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + errStdout = writeOutput(ctx, stdoutPipe, stdoutWriter) + }() + + wg.Add(1) + go func() { + defer wg.Done() + errStderr = writeOutput(ctx, stderrPipe, stderrWriter) + }() + + // Reads from pipes must be completed before calling cmd.Wait(). Otherwise + // can cause a race condition + wg.Wait() + + err = cmd.Wait() if err == nil && ctx.Err() != nil { err = ctx.Err() } @@ -41,5 +73,13 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { return tf.wrapExitError(ctx, err, errBuf.String()) } + // Return error if there was an issue reading the std out/err + if errStdout != nil && ctx.Err() != nil { + return tf.wrapExitError(ctx, errStdout, errBuf.String()) + } + if errStderr != nil && ctx.Err() != nil { + return tf.wrapExitError(ctx, errStderr, errBuf.String()) + } + return nil } diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/cmd_linux.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/cmd_linux.go index 7cbdcb96f127..6fa40e0aa31b 100644 --- a/vendor/github.com/hashicorp/terraform-exec/tfexec/cmd_linux.go +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/cmd_linux.go @@ -4,15 +4,13 @@ import ( "context" "os/exec" "strings" + "sync" "syscall" ) func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { var errBuf strings.Builder - cmd.Stdout = mergeWriters(cmd.Stdout, tf.stdout) - cmd.Stderr = mergeWriters(cmd.Stderr, tf.stderr, &errBuf) - cmd.SysProcAttr = &syscall.SysProcAttr{ // kill children if parent is dead Pdeathsig: syscall.SIGKILL, @@ -20,21 +18,6 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { Setpgid: true, } - go func() { - <-ctx.Done() - if ctx.Err() == context.DeadlineExceeded || ctx.Err() == context.Canceled { - if cmd != nil && cmd.Process != nil && cmd.ProcessState != nil { - // send SIGINT to process group - err := syscall.Kill(-cmd.Process.Pid, syscall.SIGINT) - if err != nil { - tf.logger.Printf("error from SIGINT: %s", err) - } - } - - // TODO: send a kill if it doesn't respond for a bit? - } - }() - // check for early cancellation select { case <-ctx.Done(): @@ -42,7 +25,52 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { default: } - err := cmd.Run() + // Read stdout / stderr logs from pipe instead of setting cmd.Stdout and + // cmd.Stderr because it can cause hanging when killing the command + // https://github.com/golang/go/issues/23019 + stdoutWriter := mergeWriters(cmd.Stdout, tf.stdout) + stderrWriter := mergeWriters(tf.stderr, &errBuf) + + cmd.Stderr = nil + cmd.Stdout = nil + + stdoutPipe, err := cmd.StdoutPipe() + if err != nil { + return err + } + + stderrPipe, err := cmd.StderrPipe() + if err != nil { + return err + } + + err = cmd.Start() + if err == nil && ctx.Err() != nil { + err = ctx.Err() + } + if err != nil { + return tf.wrapExitError(ctx, err, "") + } + + var errStdout, errStderr error + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + errStdout = writeOutput(ctx, stdoutPipe, stdoutWriter) + }() + + wg.Add(1) + go func() { + defer wg.Done() + errStderr = writeOutput(ctx, stderrPipe, stderrWriter) + }() + + // Reads from pipes must be completed before calling cmd.Wait(). Otherwise + // can cause a race condition + wg.Wait() + + err = cmd.Wait() if err == nil && ctx.Err() != nil { err = ctx.Err() } @@ -50,5 +78,13 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error { return tf.wrapExitError(ctx, err, errBuf.String()) } + // Return error if there was an issue reading the std out/err + if errStdout != nil && ctx.Err() != nil { + return tf.wrapExitError(ctx, errStdout, errBuf.String()) + } + if errStderr != nil && ctx.Err() != nil { + return tf.wrapExitError(ctx, errStderr, errBuf.String()) + } + return nil } diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/exit_errors.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/exit_errors.go index b2b0ada62bc3..ea25b2a56309 100644 --- a/vendor/github.com/hashicorp/terraform-exec/tfexec/exit_errors.go +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/exit_errors.go @@ -18,10 +18,18 @@ var ( usageRegexp = regexp.MustCompile(`Too many command line arguments|^Usage: .*Options:.*|Error: Invalid -\d+ option`) - noInitErrRegexp = regexp.MustCompile(`Error: Could not satisfy plugin requirements|` + - `Error: Could not load plugin|` + // v0.13 - `Please run \"terraform init\"|` + // v1.1.0 early alpha versions (ref 89b05050) - `run:\s+terraform init`) // v1.1.0 (ref df578afd) + noInitErrRegexp = regexp.MustCompile( + // UNINITIALISED PROVIDERS/MODULES + `Error: Could not satisfy plugin requirements|` + + `Error: Could not load plugin|` + // v0.13 + `Please run \"terraform init\"|` + // v1.1.0 early alpha versions (ref 89b05050) + `run:\s+terraform init|` + // v1.1.0 (ref df578afd) + `Run\s+\"terraform init\"|` + // v1.2.0 + + // UNINITIALISED BACKENDS + `Error: Initialization required.|` + // v0.13 + `Error: Backend initialization required, please run \"terraform init\"`, // v0.15 + ) noConfigErrRegexp = regexp.MustCompile(`Error: No configuration files`) @@ -33,8 +41,11 @@ var ( tfVersionMismatchConstraintRegexp = regexp.MustCompile(`required_version = "(.+)"|Required version: (.+)\b`) configInvalidErrRegexp = regexp.MustCompile(`There are some problems with the configuration, described below.`) - stateLockErrRegexp = regexp.MustCompile(`Error acquiring the state lock`) - stateLockInfoRegexp = regexp.MustCompile(`Lock Info:\n\s*ID:\s*([^\n]+)\n\s*Path:\s*([^\n]+)\n\s*Operation:\s*([^\n]+)\n\s*Who:\s*([^\n]+)\n\s*Version:\s*([^\n]+)\n\s*Created:\s*([^\n]+)\n`) + stateLockErrRegexp = regexp.MustCompile(`Error acquiring the state lock`) + stateLockInfoRegexp = regexp.MustCompile(`Lock Info:\n\s*ID:\s*([^\n]+)\n\s*Path:\s*([^\n]+)\n\s*Operation:\s*([^\n]+)\n\s*Who:\s*([^\n]+)\n\s*Version:\s*([^\n]+)\n\s*Created:\s*([^\n]+)\n`) + statePlanReadErrRegexp = regexp.MustCompile( + `Terraform couldn't read the given file as a state or plan file.|` + + `Error: Failed to read the given file as a state or plan file`) ) func (tf *Terraform) wrapExitError(ctx context.Context, err error, stderr string) error { @@ -147,6 +158,8 @@ func (tf *Terraform) wrapExitError(ctx context.Context, err error, stderr string Created: submatches[6], } } + case statePlanReadErrRegexp.MatchString(stderr): + return &ErrStatePlanRead{stderr: stderr} } return fmt.Errorf("%w\n%s", &unwrapper{exitErr, ctxErr}, stderr) @@ -223,6 +236,16 @@ func (e *ErrNoInit) Error() string { return e.stderr } +type ErrStatePlanRead struct { + unwrapper + + stderr string +} + +func (e *ErrStatePlanRead) Error() string { + return e.stderr +} + type ErrNoConfig struct { unwrapper diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/force_unlock.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/force_unlock.go new file mode 100644 index 000000000000..c8dddffa10a2 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/force_unlock.go @@ -0,0 +1,50 @@ +package tfexec + +import ( + "context" + "os/exec" +) + +type forceUnlockConfig struct { + dir string +} + +var defaultForceUnlockOptions = forceUnlockConfig{} + +type ForceUnlockOption interface { + configureForceUnlock(*forceUnlockConfig) +} + +func (opt *DirOption) configureForceUnlock(conf *forceUnlockConfig) { + conf.dir = opt.path +} + +// ForceUnlock represents the `terraform force-unlock` command +func (tf *Terraform) ForceUnlock(ctx context.Context, lockID string, opts ...ForceUnlockOption) error { + unlockCmd := tf.forceUnlockCmd(ctx, lockID, opts...) + + if err := tf.runTerraformCmd(ctx, unlockCmd); err != nil { + return err + } + + return nil +} + +func (tf *Terraform) forceUnlockCmd(ctx context.Context, lockID string, opts ...ForceUnlockOption) *exec.Cmd { + c := defaultForceUnlockOptions + + for _, o := range opts { + o.configureForceUnlock(&c) + } + args := []string{"force-unlock", "-force"} + + // positional arguments + args = append(args, lockID) + + // optional positional arguments + if c.dir != "" { + args = append(args, c.dir) + } + + return tf.buildTerraformCmd(ctx, nil, args...) +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/graph.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/graph.go new file mode 100644 index 000000000000..73396280ba92 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/graph.go @@ -0,0 +1,85 @@ +package tfexec + +import ( + "context" + "fmt" + "os/exec" + "strings" +) + +type graphConfig struct { + plan string + drawCycles bool + graphType string +} + +var defaultGraphOptions = graphConfig{} + +type GraphOption interface { + configureGraph(*graphConfig) +} + +func (opt *GraphPlanOption) configureGraph(conf *graphConfig) { + conf.plan = opt.file +} + +func (opt *DrawCyclesOption) configureGraph(conf *graphConfig) { + conf.drawCycles = opt.drawCycles +} + +func (opt *GraphTypeOption) configureGraph(conf *graphConfig) { + conf.graphType = opt.graphType +} + +func (tf *Terraform) Graph(ctx context.Context, opts ...GraphOption) (string, error) { + graphCmd, err := tf.graphCmd(ctx, opts...) + if err != nil { + return "", err + } + var outBuf strings.Builder + graphCmd.Stdout = &outBuf + err = tf.runTerraformCmd(ctx, graphCmd) + if err != nil { + return "", err + } + + return outBuf.String(), nil + +} + +func (tf *Terraform) graphCmd(ctx context.Context, opts ...GraphOption) (*exec.Cmd, error) { + c := defaultGraphOptions + + for _, o := range opts { + o.configureGraph(&c) + } + + args := []string{"graph"} + + if c.plan != "" { + // plan was a positional arguement prior to Terraform 0.15.0. Ensure proper use by checking version. + if err := tf.compatible(ctx, tf0_15_0, nil); err == nil { + args = append(args, "-plan="+c.plan) + } else { + args = append(args, c.plan) + } + } + + if c.drawCycles { + err := tf.compatible(ctx, tf0_5_0, nil) + if err != nil { + return nil, fmt.Errorf("-draw-cycles was first introduced in Terraform 0.5.0: %w", err) + } + args = append(args, "-draw-cycles") + } + + if c.graphType != "" { + err := tf.compatible(ctx, tf0_8_0, nil) + if err != nil { + return nil, fmt.Errorf("-graph-type was first introduced in Terraform 0.8.0: %w", err) + } + args = append(args, "-type="+c.graphType) + } + + return tf.buildTerraformCmd(ctx, nil, args...), nil +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/options.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/options.go index fb2d5bd74b81..ad3cc65c66bd 100644 --- a/vendor/github.com/hashicorp/terraform-exec/tfexec/options.go +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/options.go @@ -14,6 +14,16 @@ func AllowMissingConfig(allowMissingConfig bool) *AllowMissingConfigOption { return &AllowMissingConfigOption{allowMissingConfig} } +// AllowMissingOption represents the -allow-missing flag. +type AllowMissingOption struct { + allowMissing bool +} + +// AllowMissing represents the -allow-missing flag. +func AllowMissing(allowMissing bool) *AllowMissingOption { + return &AllowMissingOption{allowMissing} +} + // BackendOption represents the -backend flag. type BackendOption struct { backend bool @@ -108,6 +118,15 @@ func Destroy(destroy bool) *DestroyFlagOption { return &DestroyFlagOption{destroy} } +type DrawCyclesOption struct { + drawCycles bool +} + +// DrawCycles represents the -draw-cycles flag. +func DrawCycles(drawCycles bool) *DrawCyclesOption { + return &DrawCyclesOption{drawCycles} +} + type DryRunOption struct { dryRun bool } @@ -212,6 +231,15 @@ func Parallelism(n int) *ParallelismOption { return &ParallelismOption{n} } +type GraphPlanOption struct { + file string +} + +// GraphPlan represents the -plan flag which is a specified plan file string +func GraphPlan(file string) *GraphPlanOption { + return &GraphPlanOption{file} +} + type PlatformOption struct { platform string } @@ -334,6 +362,14 @@ func Target(resource string) *TargetOption { return &TargetOption{resource} } +type GraphTypeOption struct { + graphType string +} + +func GraphType(graphType string) *GraphTypeOption { + return &GraphTypeOption{graphType} +} + type UpdateOption struct { update bool } @@ -373,21 +409,3 @@ type VerifyPluginsOption struct { func VerifyPlugins(verifyPlugins bool) *VerifyPluginsOption { return &VerifyPluginsOption{verifyPlugins} } - -// FromStateOption represents the -from-state option of the "terraform add" command. -type FromStateOption struct { - fromState bool -} - -func FromState(fromState bool) *FromStateOption { - return &FromStateOption{fromState} -} - -// IncludeOptionalOption represents the -optional option of the "terraform add" command. -type IncludeOptionalOption struct { - includeOptional bool -} - -func IncludeOptional(includeOptional bool) *IncludeOptionalOption { - return &IncludeOptionalOption{includeOptional} -} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/state_pull.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/state_pull.go new file mode 100644 index 000000000000..11b6b9c77f0e --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/state_pull.go @@ -0,0 +1,55 @@ +package tfexec + +import ( + "bytes" + "context" + "os/exec" +) + +type statePullConfig struct { + reattachInfo ReattachInfo +} + +var defaultStatePullConfig = statePullConfig{} + +type StatePullOption interface { + configureShow(*statePullConfig) +} + +func (opt *ReattachOption) configureStatePull(conf *statePullConfig) { + conf.reattachInfo = opt.info +} + +func (tf *Terraform) StatePull(ctx context.Context, opts ...StatePullOption) (string, error) { + c := defaultStatePullConfig + + for _, o := range opts { + o.configureShow(&c) + } + + mergeEnv := map[string]string{} + if c.reattachInfo != nil { + reattachStr, err := c.reattachInfo.marshalString() + if err != nil { + return "", err + } + mergeEnv[reattachEnvVar] = reattachStr + } + + cmd := tf.statePullCmd(ctx, mergeEnv) + + var ret bytes.Buffer + cmd.Stdout = &ret + err := tf.runTerraformCmd(ctx, cmd) + if err != nil { + return "", err + } + + return ret.String(), nil +} + +func (tf *Terraform) statePullCmd(ctx context.Context, mergeEnv map[string]string) *exec.Cmd { + args := []string{"state", "pull"} + + return tf.buildTerraformCmd(ctx, mergeEnv, args...) +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/state_push.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/state_push.go new file mode 100644 index 000000000000..14e55a2eb3fe --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/state_push.go @@ -0,0 +1,67 @@ +package tfexec + +import ( + "context" + "os/exec" + "strconv" +) + +type statePushConfig struct { + force bool + lock bool + lockTimeout string +} + +var defaultStatePushOptions = statePushConfig{ + lock: false, + lockTimeout: "0s", +} + +// StatePushCmdOption represents options used in the Refresh method. +type StatePushCmdOption interface { + configureStatePush(*statePushConfig) +} + +func (opt *ForceOption) configureStatePush(conf *statePushConfig) { + conf.force = opt.force +} + +func (opt *LockOption) configureStatePush(conf *statePushConfig) { + conf.lock = opt.lock +} + +func (opt *LockTimeoutOption) configureStatePush(conf *statePushConfig) { + conf.lockTimeout = opt.timeout +} + +func (tf *Terraform) StatePush(ctx context.Context, path string, opts ...StatePushCmdOption) error { + cmd, err := tf.statePushCmd(ctx, path, opts...) + if err != nil { + return err + } + return tf.runTerraformCmd(ctx, cmd) +} + +func (tf *Terraform) statePushCmd(ctx context.Context, path string, opts ...StatePushCmdOption) (*exec.Cmd, error) { + c := defaultStatePushOptions + + for _, o := range opts { + o.configureStatePush(&c) + } + + args := []string{"state", "push"} + + if c.force { + args = append(args, "-force") + } + + args = append(args, "-lock="+strconv.FormatBool(c.lock)) + + if c.lockTimeout != "" { + args = append(args, "-lock-timeout="+c.lockTimeout) + } + + args = append(args, path) + + return tf.buildTerraformCmd(ctx, nil, args...), nil +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/taint.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/taint.go new file mode 100644 index 000000000000..cd69df3085f6 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/taint.go @@ -0,0 +1,78 @@ +package tfexec + +import ( + "context" + "fmt" + "os/exec" + "strconv" +) + +type taintConfig struct { + state string + allowMissing bool + lock bool + lockTimeout string +} + +var defaultTaintOptions = taintConfig{ + allowMissing: false, + lock: true, +} + +// TaintOption represents options used in the Taint method. +type TaintOption interface { + configureTaint(*taintConfig) +} + +func (opt *StateOption) configureTaint(conf *taintConfig) { + conf.state = opt.path +} + +func (opt *AllowMissingOption) configureTaint(conf *taintConfig) { + conf.allowMissing = opt.allowMissing +} + +func (opt *LockOption) configureTaint(conf *taintConfig) { + conf.lock = opt.lock +} + +func (opt *LockTimeoutOption) configureTaint(conf *taintConfig) { + conf.lockTimeout = opt.timeout +} + +// Taint represents the terraform taint subcommand. +func (tf *Terraform) Taint(ctx context.Context, address string, opts ...TaintOption) error { + err := tf.compatible(ctx, tf0_4_1, nil) + if err != nil { + return fmt.Errorf("taint was first introduced in Terraform 0.4.1: %w", err) + } + taintCmd := tf.taintCmd(ctx, address, opts...) + return tf.runTerraformCmd(ctx, taintCmd) +} + +func (tf *Terraform) taintCmd(ctx context.Context, address string, opts ...TaintOption) *exec.Cmd { + c := defaultTaintOptions + + for _, o := range opts { + o.configureTaint(&c) + } + + args := []string{"taint", "-no-color"} + + if c.lockTimeout != "" { + args = append(args, "-lock-timeout="+c.lockTimeout) + } + + // string opts: only pass if set + if c.state != "" { + args = append(args, "-state="+c.state) + } + + args = append(args, "-lock="+strconv.FormatBool(c.lock)) + if c.allowMissing { + args = append(args, "-allow-missing") + } + args = append(args, address) + + return tf.buildTerraformCmd(ctx, nil, args...) +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/terraform.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/terraform.go index 74787af0c256..bb8be17d5815 100644 --- a/vendor/github.com/hashicorp/terraform-exec/tfexec/terraform.go +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/terraform.go @@ -48,19 +48,30 @@ type Terraform struct { skipProviderVerify bool env map[string]string - stdout io.Writer - stderr io.Writer - logger printfer + stdout io.Writer + stderr io.Writer + logger printfer + + // TF_LOG environment variable, defaults to TRACE if logPath is set. + log string + + // TF_LOG_CORE environment variable + logCore string + + // TF_LOG_PATH environment variable logPath string + // TF_LOG_PROVIDER environment variable + logProvider string + versionLock sync.Mutex execVersion *version.Version provVersions map[string]*version.Version } // NewTerraform returns a Terraform struct with default values for all fields. -// If a blank execPath is supplied, NewTerraform will attempt to locate an -// appropriate binary on the system PATH. +// If a blank execPath is supplied, NewTerraform will error. +// Use hc-install or output from os.LookPath to get a desirable execPath. func NewTerraform(workingDir string, execPath string) (*Terraform, error) { if workingDir == "" { return nil, fmt.Errorf("Terraform cannot be initialised with empty workdir") @@ -71,7 +82,7 @@ func NewTerraform(workingDir string, execPath string) (*Terraform, error) { } if execPath == "" { - err := fmt.Errorf("NewTerraform: please supply the path to a Terraform executable using execPath, e.g. using the tfinstall package.") + err := fmt.Errorf("NewTerraform: please supply the path to a Terraform executable using execPath, e.g. using the github.com/hashicorp/hc-install module.") return nil, &ErrNoSuitableBinary{ err: err, } @@ -122,10 +133,58 @@ func (tf *Terraform) SetStderr(w io.Writer) { tf.stderr = w } +// SetLog sets the TF_LOG environment variable for Terraform CLI execution. +// This must be combined with a call to SetLogPath to take effect. +// +// This is only compatible with Terraform CLI 0.15.0 or later as setting the +// log level was unreliable in earlier versions. It will default to TRACE when +// SetLogPath is called on versions 0.14.11 and earlier, or if SetLogCore and +// SetLogProvider have not been called before SetLogPath on versions 0.15.0 and +// later. +func (tf *Terraform) SetLog(log string) error { + err := tf.compatible(context.Background(), tf0_15_0, nil) + if err != nil { + return err + } + tf.log = log + return nil +} + +// SetLogCore sets the TF_LOG_CORE environment variable for Terraform CLI +// execution. This must be combined with a call to SetLogPath to take effect. +// +// This is only compatible with Terraform CLI 0.15.0 or later. +func (tf *Terraform) SetLogCore(logCore string) error { + err := tf.compatible(context.Background(), tf0_15_0, nil) + if err != nil { + return err + } + tf.logCore = logCore + return nil +} + // SetLogPath sets the TF_LOG_PATH environment variable for Terraform CLI // execution. func (tf *Terraform) SetLogPath(path string) error { tf.logPath = path + // Prevent setting the log path without enabling logging + if tf.log == "" && tf.logCore == "" && tf.logProvider == "" { + tf.log = "TRACE" + } + return nil +} + +// SetLogProvider sets the TF_LOG_PROVIDER environment variable for Terraform +// CLI execution. This must be combined with a call to SetLogPath to take +// effect. +// +// This is only compatible with Terraform CLI 0.15.0 or later. +func (tf *Terraform) SetLogProvider(logProvider string) error { + err := tf.compatible(context.Background(), tf0_15_0, nil) + if err != nil { + return err + } + tf.logProvider = logProvider return nil } diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/untaint.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/untaint.go new file mode 100644 index 000000000000..bda1272775d0 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/untaint.go @@ -0,0 +1,78 @@ +package tfexec + +import ( + "context" + "fmt" + "os/exec" + "strconv" +) + +type untaintConfig struct { + state string + allowMissing bool + lock bool + lockTimeout string +} + +var defaultUntaintOptions = untaintConfig{ + allowMissing: false, + lock: true, +} + +// OutputOption represents options used in the Output method. +type UntaintOption interface { + configureUntaint(*untaintConfig) +} + +func (opt *StateOption) configureUntaint(conf *untaintConfig) { + conf.state = opt.path +} + +func (opt *AllowMissingOption) configureUntaint(conf *untaintConfig) { + conf.allowMissing = opt.allowMissing +} + +func (opt *LockOption) configureUntaint(conf *untaintConfig) { + conf.lock = opt.lock +} + +func (opt *LockTimeoutOption) configureUntaint(conf *untaintConfig) { + conf.lockTimeout = opt.timeout +} + +// Untaint represents the terraform untaint subcommand. +func (tf *Terraform) Untaint(ctx context.Context, address string, opts ...UntaintOption) error { + err := tf.compatible(ctx, tf0_6_13, nil) + if err != nil { + return fmt.Errorf("untaint was first introduced in Terraform 0.6.13: %w", err) + } + untaintCmd := tf.untaintCmd(ctx, address, opts...) + return tf.runTerraformCmd(ctx, untaintCmd) +} + +func (tf *Terraform) untaintCmd(ctx context.Context, address string, opts ...UntaintOption) *exec.Cmd { + c := defaultUntaintOptions + + for _, o := range opts { + o.configureUntaint(&c) + } + + args := []string{"untaint", "-no-color"} + + if c.lockTimeout != "" { + args = append(args, "-lock-timeout="+c.lockTimeout) + } + + // string opts: only pass if set + if c.state != "" { + args = append(args, "-state="+c.state) + } + + args = append(args, "-lock="+strconv.FormatBool(c.lock)) + if c.allowMissing { + args = append(args, "-allow-missing") + } + args = append(args, address) + + return tf.buildTerraformCmd(ctx, nil, args...) +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/version.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/version.go index d9c57cd07a8e..9978ae28de68 100644 --- a/vendor/github.com/hashicorp/terraform-exec/tfexec/version.go +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/version.go @@ -14,7 +14,12 @@ import ( ) var ( + tf0_4_1 = version.Must(version.NewVersion("0.4.1")) + tf0_5_0 = version.Must(version.NewVersion("0.5.0")) + tf0_6_13 = version.Must(version.NewVersion("0.6.13")) tf0_7_7 = version.Must(version.NewVersion("0.7.7")) + tf0_8_0 = version.Must(version.NewVersion("0.8.0")) + tf0_10_0 = version.Must(version.NewVersion("0.10.0")) tf0_12_0 = version.Must(version.NewVersion("0.12.0")) tf0_13_0 = version.Must(version.NewVersion("0.13.0")) tf0_14_0 = version.Must(version.NewVersion("0.14.0")) diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/workspace_delete.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/workspace_delete.go new file mode 100644 index 000000000000..526772079a38 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/workspace_delete.go @@ -0,0 +1,81 @@ +package tfexec + +import ( + "context" + "fmt" + "os/exec" + "strconv" +) + +type workspaceDeleteConfig struct { + lock bool + lockTimeout string + force bool +} + +var defaultWorkspaceDeleteOptions = workspaceDeleteConfig{ + lock: true, + lockTimeout: "0s", +} + +// WorkspaceDeleteCmdOption represents options that are applicable to the WorkspaceDelete method. +type WorkspaceDeleteCmdOption interface { + configureWorkspaceDelete(*workspaceDeleteConfig) +} + +func (opt *LockOption) configureWorkspaceDelete(conf *workspaceDeleteConfig) { + conf.lock = opt.lock +} + +func (opt *LockTimeoutOption) configureWorkspaceDelete(conf *workspaceDeleteConfig) { + conf.lockTimeout = opt.timeout +} + +func (opt *ForceOption) configureWorkspaceDelete(conf *workspaceDeleteConfig) { + conf.force = opt.force +} + +// WorkspaceDelete represents the workspace delete subcommand to the Terraform CLI. +func (tf *Terraform) WorkspaceDelete(ctx context.Context, workspace string, opts ...WorkspaceDeleteCmdOption) error { + cmd, err := tf.workspaceDeleteCmd(ctx, workspace, opts...) + if err != nil { + return err + } + return tf.runTerraformCmd(ctx, cmd) +} + +func (tf *Terraform) workspaceDeleteCmd(ctx context.Context, workspace string, opts ...WorkspaceDeleteCmdOption) (*exec.Cmd, error) { + c := defaultWorkspaceDeleteOptions + + for _, o := range opts { + switch o.(type) { + case *LockOption, *LockTimeoutOption: + err := tf.compatible(ctx, tf0_12_0, nil) + if err != nil { + return nil, fmt.Errorf("-lock and -lock-timeout were added to workspace delete in Terraform 0.12: %w", err) + } + } + + o.configureWorkspaceDelete(&c) + } + + args := []string{"workspace", "delete", "-no-color"} + + if c.force { + args = append(args, "-force") + } + if c.lockTimeout != "" && c.lockTimeout != defaultWorkspaceDeleteOptions.lockTimeout { + // only pass if not default, so we don't need to worry about the 0.11 version check + args = append(args, "-lock-timeout="+c.lockTimeout) + } + if !c.lock { + // only pass if false, so we don't need to worry about the 0.11 version check + args = append(args, "-lock="+strconv.FormatBool(c.lock)) + } + + args = append(args, workspace) + + cmd := tf.buildTerraformCmd(ctx, nil, args...) + + return cmd, nil +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/workspace_show.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/workspace_show.go new file mode 100644 index 000000000000..7d5a267f1dbd --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfexec/workspace_show.go @@ -0,0 +1,35 @@ +package tfexec + +import ( + "context" + "fmt" + "os/exec" + "strings" +) + +// WorkspaceShow represents the workspace show subcommand to the Terraform CLI. +func (tf *Terraform) WorkspaceShow(ctx context.Context) (string, error) { + workspaceShowCmd, err := tf.workspaceShowCmd(ctx) + if err != nil { + return "", err + } + + var outBuffer strings.Builder + workspaceShowCmd.Stdout = &outBuffer + + err = tf.runTerraformCmd(ctx, workspaceShowCmd) + if err != nil { + return "", err + } + + return strings.TrimSpace(outBuffer.String()), nil +} + +func (tf *Terraform) workspaceShowCmd(ctx context.Context) (*exec.Cmd, error) { + err := tf.compatible(ctx, tf0_10_0, nil) + if err != nil { + return nil, fmt.Errorf("workspace show was first introduced in Terraform 0.10.0: %w", err) + } + + return tf.buildTerraformCmd(ctx, nil, "workspace", "show", "-no-color"), nil +} diff --git a/vendor/github.com/hashicorp/terraform-json/config.go b/vendor/github.com/hashicorp/terraform-json/config.go index e093cfa8bfff..5ebe4bc840c9 100644 --- a/vendor/github.com/hashicorp/terraform-json/config.go +++ b/vendor/github.com/hashicorp/terraform-json/config.go @@ -48,6 +48,9 @@ type ProviderConfig struct { // The name of the provider, ie: "aws". Name string `json:"name,omitempty"` + // The fully-specified name of the provider, ie: "registry.terraform.io/hashicorp/aws". + FullName string `json:"full_name,omitempty"` + // The alias of the provider, ie: "us-east-1". Alias string `json:"alias,omitempty"` diff --git a/vendor/github.com/hashicorp/terraform-json/plan.go b/vendor/github.com/hashicorp/terraform-json/plan.go index 1de5bc82a094..274006a01807 100644 --- a/vendor/github.com/hashicorp/terraform-json/plan.go +++ b/vendor/github.com/hashicorp/terraform-json/plan.go @@ -55,6 +55,19 @@ type Plan struct { // The Terraform configuration used to make the plan. Config *Config `json:"configuration,omitempty"` + + // RelevantAttributes represents any resource instances and their + // attributes which may have contributed to the planned changes + RelevantAttributes []ResourceAttribute `json:"relevant_attributes,omitempty"` +} + +// ResourceAttribute describes a full path to a resource attribute +type ResourceAttribute struct { + // Resource describes resource instance address (e.g. null_resource.foo) + Resource string `json:"resource"` + // Attribute describes the attribute path using a lossy representation + // of cty.Path. (e.g. ["id"] or ["objects", 0, "val"]). + Attribute []json.RawMessage `json:"attribute"` } // Validate checks to ensure that the plan is present, and the diff --git a/vendor/github.com/hashicorp/terraform-json/schemas.go b/vendor/github.com/hashicorp/terraform-json/schemas.go index 2360231d00f4..027224b620ad 100644 --- a/vendor/github.com/hashicorp/terraform-json/schemas.go +++ b/vendor/github.com/hashicorp/terraform-json/schemas.go @@ -223,6 +223,13 @@ type SchemaAttribute struct { Sensitive bool `json:"sensitive,omitempty"` } +// jsonSchemaAttribute describes an attribute within a schema block +// in a middle-step internal representation before marshalled into +// a more useful SchemaAttribute with cty.Type. +// +// This avoid panic on marshalling cty.NilType (from cty upstream) +// which the default Go marshaller cannot ignore because it's a +// not nil-able struct. type jsonSchemaAttribute struct { AttributeType json.RawMessage `json:"type,omitempty"` AttributeNestedType *SchemaNestedAttributeType `json:"nested_type,omitempty"` diff --git a/vendor/github.com/hashicorp/terraform-json/state.go b/vendor/github.com/hashicorp/terraform-json/state.go index bece5c220212..3c3f6a4b0aab 100644 --- a/vendor/github.com/hashicorp/terraform-json/state.go +++ b/vendor/github.com/hashicorp/terraform-json/state.go @@ -7,6 +7,7 @@ import ( "fmt" "github.com/hashicorp/go-version" + "github.com/zclconf/go-cty/cty" ) // StateFormatVersionConstraints defines the versions of the JSON state format @@ -175,4 +176,31 @@ type StateOutput struct { // The value of the output. Value interface{} `json:"value,omitempty"` + + // The type of the output. + Type cty.Type `json:"type,omitempty"` +} + +// jsonStateOutput describes an output value in a middle-step internal +// representation before marshalled into a more useful StateOutput with cty.Type. +// +// This avoid panic on marshalling cty.NilType (from cty upstream) +// which the default Go marshaller cannot ignore because it's a +// not nil-able struct. +type jsonStateOutput struct { + Sensitive bool `json:"sensitive"` + Value interface{} `json:"value,omitempty"` + Type json.RawMessage `json:"type,omitempty"` +} + +func (so *StateOutput) MarshalJSON() ([]byte, error) { + jsonSa := &jsonStateOutput{ + Sensitive: so.Sensitive, + Value: so.Value, + } + if so.Type != cty.NilType { + outputType, _ := so.Type.MarshalJSON() + jsonSa.Type = outputType + } + return json.Marshal(jsonSa) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/context.go b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/context.go new file mode 100644 index 000000000000..38ef4e35e254 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/context.go @@ -0,0 +1,89 @@ +package logging + +import ( + "context" + + "github.com/hashicorp/go-uuid" + "github.com/hashicorp/terraform-plugin-log/tflog" + "github.com/hashicorp/terraform-plugin-log/tfsdklog" +) + +// DataSourceContext injects the data source type into logger contexts. +func DataSourceContext(ctx context.Context, dataSource string) context.Context { + ctx = tfsdklog.With(ctx, KeyDataSourceType, dataSource) + ctx = tfsdklog.SubsystemWith(ctx, SubsystemProto, KeyDataSourceType, dataSource) + ctx = tflog.With(ctx, KeyDataSourceType, dataSource) + + return ctx +} + +// InitContext creates SDK and provider logger contexts. +func InitContext(ctx context.Context, sdkOpts tfsdklog.Options, providerOpts tflog.Options) context.Context { + ctx = tfsdklog.NewRootSDKLogger(ctx, append(tfsdklog.Options{ + tfsdklog.WithLevelFromEnv(EnvTfLogSdk), + }, sdkOpts...)...) + ctx = ProtoSubsystemContext(ctx, sdkOpts) + ctx = tfsdklog.NewRootProviderLogger(ctx, providerOpts...) + + return ctx +} + +// ProtoSubsystemContext adds the proto subsystem to the SDK logger context. +func ProtoSubsystemContext(ctx context.Context, sdkOpts tfsdklog.Options) context.Context { + ctx = tfsdklog.NewSubsystem(ctx, SubsystemProto, append(tfsdklog.Options{ + // All calls are through the Protocol* helper functions + tfsdklog.WithAdditionalLocationOffset(1), + tfsdklog.WithLevelFromEnv(EnvTfLogSdkProto), + }, sdkOpts...)...) + + return ctx +} + +// ProtocolVersionContext injects the protocol version into logger contexts. +func ProtocolVersionContext(ctx context.Context, protocolVersion string) context.Context { + ctx = tfsdklog.SubsystemWith(ctx, SubsystemProto, KeyProtocolVersion, protocolVersion) + + return ctx +} + +// ProviderAddressContext injects the provider address into logger contexts. +func ProviderAddressContext(ctx context.Context, providerAddress string) context.Context { + ctx = tfsdklog.With(ctx, KeyProviderAddress, providerAddress) + ctx = tfsdklog.SubsystemWith(ctx, SubsystemProto, KeyProviderAddress, providerAddress) + ctx = tflog.With(ctx, KeyProviderAddress, providerAddress) + + return ctx +} + +// RequestIdContext injects a unique request ID into logger contexts. +func RequestIdContext(ctx context.Context) context.Context { + reqID, err := uuid.GenerateUUID() + + if err != nil { + reqID = "unable to assign request ID: " + err.Error() + } + + ctx = tfsdklog.With(ctx, KeyRequestID, reqID) + ctx = tfsdklog.SubsystemWith(ctx, SubsystemProto, KeyRequestID, reqID) + ctx = tflog.With(ctx, KeyRequestID, reqID) + + return ctx +} + +// ResourceContext injects the resource type into logger contexts. +func ResourceContext(ctx context.Context, resource string) context.Context { + ctx = tfsdklog.With(ctx, KeyResourceType, resource) + ctx = tfsdklog.SubsystemWith(ctx, SubsystemProto, KeyResourceType, resource) + ctx = tflog.With(ctx, KeyResourceType, resource) + + return ctx +} + +// RpcContext injects the RPC name into logger contexts. +func RpcContext(ctx context.Context, rpc string) context.Context { + ctx = tfsdklog.With(ctx, KeyRPC, rpc) + ctx = tfsdklog.SubsystemWith(ctx, SubsystemProto, KeyRPC, rpc) + ctx = tflog.With(ctx, KeyRPC, rpc) + + return ctx +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/doc.go b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/doc.go new file mode 100644 index 000000000000..cc1a033e6141 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/doc.go @@ -0,0 +1,2 @@ +// Package logging contains shared environment variable and log functionality. +package logging diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/environment_variables.go b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/environment_variables.go new file mode 100644 index 000000000000..49b8072c8c88 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/environment_variables.go @@ -0,0 +1,22 @@ +package logging + +// Environment variables. +const ( + // EnvTfLogProvider is the prefix of the environment variable that sets the + // logging level of the root provider logger for the provider being served. + // The suffix is an underscore and the parsed provider name. For example, + // registry.terraform.io/hashicorp/example becomes TF_LOG_PROVIDER_EXAMPLE. + EnvTfLogProvider = "TF_LOG_PROVIDER" + + // EnvTfLogSdk is an environment variable that sets the root logging level + // of SDK loggers. + EnvTfLogSdk = "TF_LOG_SDK" + + // EnvTfLogSdkProto is an environment variable that sets the logging level + // of SDK protocol loggers. Infers root SDK logging level, if unset. + EnvTfLogSdkProto = "TF_LOG_SDK_PROTO" + + // EnvTfLogSdkProtoDataDir is an environment variable that sets the + // directory to write raw protocol data files for debugging purposes. + EnvTfLogSdkProtoDataDir = "TF_LOG_SDK_PROTO_DATA_DIR" +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/keys.go b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/keys.go new file mode 100644 index 000000000000..ce803d752bd6 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/keys.go @@ -0,0 +1,53 @@ +package logging + +// Global logging keys attached to all requests. +// +// Practitioners or tooling reading logs may be depending on these keys, so be +// conscious of that when changing them. +const ( + // Attribute of the diagnostic being logged. + KeyDiagnosticAttribute = "diagnostic_attribute" + + // Number of the error diagnostics. + KeyDiagnosticErrorCount = "diagnostic_error_count" + + // Severity of the diagnostic being logged. + KeyDiagnosticSeverity = "diagnostic_severity" + + // Detail of the diagnostic being logged. + KeyDiagnosticDetail = "diagnostic_detail" + + // Summary of the diagnostic being logged. + KeyDiagnosticSummary = "diagnostic_summary" + + // Number of the warning diagnostics. + KeyDiagnosticWarningCount = "diagnostic_warning_count" + + // Underlying error string + KeyError = "error" + + // Duration in milliseconds for the RPC request + KeyRequestDurationMs = "tf_req_duration_ms" + + // A unique ID for the RPC request + KeyRequestID = "tf_req_id" + + // The full address of the provider, such as + // registry.terraform.io/hashicorp/random + KeyProviderAddress = "tf_provider_addr" + + // The RPC being run, such as "ApplyResourceChange" + KeyRPC = "tf_rpc" + + // The type of resource being operated on, such as "random_pet" + KeyResourceType = "tf_resource_type" + + // The type of data source being operated on, such as "archive_file" + KeyDataSourceType = "tf_data_source_type" + + // Path to protocol data file, such as "/tmp/example.json" + KeyProtocolDataFile = "tf_proto_data_file" + + // The protocol version being used, as a string, such as "6" + KeyProtocolVersion = "tf_proto_version" +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/protocol.go b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/protocol.go new file mode 100644 index 000000000000..21a392a3caa7 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/protocol.go @@ -0,0 +1,27 @@ +package logging + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-log/tfsdklog" +) + +const ( + // SubsystemProto is the tfsdklog subsystem name for protocol logging. + SubsystemProto = "proto" +) + +// ProtocolError emits a protocol subsystem log at ERROR level. +func ProtocolError(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemError(ctx, SubsystemProto, msg, additionalFields...) +} + +// ProtocolWarn emits a protocol subsystem log at WARN level. +func ProtocolWarn(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemWarn(ctx, SubsystemProto, msg, additionalFields...) +} + +// ProtocolTrace emits a protocol subsystem log at TRACE level. +func ProtocolTrace(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemTrace(ctx, SubsystemProto, msg, additionalFields...) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/protocol_data.go b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/protocol_data.go new file mode 100644 index 000000000000..630358232077 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/protocol_data.go @@ -0,0 +1,108 @@ +package logging + +import ( + "context" + "fmt" + "os" + "path" + "sync" + "time" + + "github.com/hashicorp/terraform-plugin-go/tfprotov5" + "github.com/hashicorp/terraform-plugin-go/tfprotov6" +) + +const ( + // fileExtEmpty is the file extension for empty data. + // Empty data may be expected, depending on the RPC. + fileExtEmpty = "empty" + + // fileExtJson is the file extension for JSON data. + fileExtJson = "json" + + // fileExtMsgpack is the file extension for MessagePack data. + fileExtMsgpack = "msgpack" +) + +var protocolDataSkippedLog sync.Once + +// ProtocolData emits raw protocol data to a file, if given a directory. +// +// The directory must exist and be writable, prior to invoking this function. +// +// File names are in the format: {TIME}_{RPC}_{MESSAGE}_{FIELD}.{EXT} +func ProtocolData(ctx context.Context, dataDir string, rpc string, message string, field string, data interface{}) { + if dataDir == "" { + // Write a log, only once, that explains how to enable this functionality. + protocolDataSkippedLog.Do(func() { + ProtocolTrace(ctx, "Skipping protocol data file writing because no data directory is set. "+ + fmt.Sprintf("Use the %s environment variable to enable this functionality.", EnvTfLogSdkProtoDataDir)) + }) + + return + } + + var fileContents []byte + var fileExtension string + + switch data := data.(type) { + case *tfprotov5.DynamicValue: + fileExtension, fileContents = protocolDataDynamicValue5(ctx, data) + case *tfprotov6.DynamicValue: + fileExtension, fileContents = protocolDataDynamicValue6(ctx, data) + default: + ProtocolError(ctx, fmt.Sprintf("Skipping unknown protocol data type: %T", data)) + return + } + + fileName := fmt.Sprintf("%d_%s_%s_%s.%s", time.Now().Unix(), rpc, message, field, fileExtension) + filePath := path.Join(dataDir, fileName) + logFields := map[string]interface{}{KeyProtocolDataFile: filePath} // should not be persisted using With() + + ProtocolTrace(ctx, "Writing protocol data file", logFields) + + err := os.WriteFile(filePath, fileContents, 0644) + + if err != nil { + ProtocolError(ctx, fmt.Sprintf("Unable to write protocol data file: %s", err), logFields) + return + } + + ProtocolTrace(ctx, "Wrote protocol data file", logFields) +} + +func protocolDataDynamicValue5(_ context.Context, value *tfprotov5.DynamicValue) (string, []byte) { + if value == nil { + return fileExtEmpty, nil + } + + // (tfprotov5.DynamicValue).Unmarshal() prefers JSON first, so prefer to + // output JSON if found. + if len(value.JSON) > 0 { + return fileExtJson, value.JSON + } + + if len(value.MsgPack) > 0 { + return fileExtMsgpack, value.MsgPack + } + + return fileExtEmpty, nil +} + +func protocolDataDynamicValue6(_ context.Context, value *tfprotov6.DynamicValue) (string, []byte) { + if value == nil { + return fileExtEmpty, nil + } + + // (tfprotov6.DynamicValue).Unmarshal() prefers JSON first, so prefer to + // output JSON if found. + if len(value.JSON) > 0 { + return fileExtJson, value.JSON + } + + if len(value.MsgPack) > 0 { + return fileExtMsgpack, value.MsgPack + } + + return fileExtEmpty, nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/provider.go b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/provider.go new file mode 100644 index 000000000000..b40763c6e178 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/internal/logging/provider.go @@ -0,0 +1,18 @@ +package logging + +import ( + "log" + "strings" + + tfaddr "github.com/hashicorp/terraform-registry-address" +) + +func ProviderLoggerName(providerAddress string) string { + provider, err := tfaddr.ParseProviderSource(providerAddress) + if err != nil { + log.Printf("[ERROR] Error parsing provider name %q: %s", providerAddress, err) + return "" + } + + return strings.ReplaceAll(provider.Type, "-", "_") +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag/diagnostics.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag/diagnostics.go new file mode 100644 index 000000000000..1032f7d4fae8 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag/diagnostics.go @@ -0,0 +1,82 @@ +package diag + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-go/internal/logging" + "github.com/hashicorp/terraform-plugin-go/tfprotov5" +) + +// Diagnostics is a collection of Diagnostic. +type Diagnostics []*tfprotov5.Diagnostic + +// ErrorCount returns the number of error severity diagnostics. +func (d Diagnostics) ErrorCount() int { + var result int + + for _, diagnostic := range d { + if diagnostic == nil { + continue + } + + if diagnostic.Severity != tfprotov5.DiagnosticSeverityError { + continue + } + + result++ + } + + return result +} + +// Log will log every diagnostic: +// +// - Error severity at ERROR level +// - Warning severity at WARN level +// - Invalid/Unknown severity at WARN level +// +func (d Diagnostics) Log(ctx context.Context) { + for _, diagnostic := range d { + if diagnostic == nil { + continue + } + + diagnosticFields := map[string]interface{}{ + logging.KeyDiagnosticDetail: diagnostic.Detail, + logging.KeyDiagnosticSeverity: diagnostic.Severity.String(), + logging.KeyDiagnosticSummary: diagnostic.Summary, + } + + if diagnostic.Attribute != nil { + diagnosticFields[logging.KeyDiagnosticAttribute] = diagnostic.Attribute.String() + } + + switch diagnostic.Severity { + case tfprotov5.DiagnosticSeverityError: + logging.ProtocolError(ctx, "Response contains error diagnostic", diagnosticFields) + case tfprotov5.DiagnosticSeverityWarning: + logging.ProtocolWarn(ctx, "Response contains warning diagnostic", diagnosticFields) + default: + logging.ProtocolWarn(ctx, "Response contains unknown diagnostic", diagnosticFields) + } + } +} + +// WarningCount returns the number of warning severity diagnostics. +func (d Diagnostics) WarningCount() int { + var result int + + for _, diagnostic := range d { + if diagnostic == nil { + continue + } + + if diagnostic.Severity != tfprotov5.DiagnosticSeverityWarning { + continue + } + + result++ + } + + return result +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag/doc.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag/doc.go new file mode 100644 index 000000000000..0c73dab12fe6 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag/doc.go @@ -0,0 +1,3 @@ +// Package diag contains diagnostics helpers. These implementations are +// intentionally outside the public API. +package diag diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/context_keys.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/context_keys.go new file mode 100644 index 000000000000..cc72fe4bbf67 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/context_keys.go @@ -0,0 +1,8 @@ +package tf5serverlogging + +// Context key types. +// Reference: https://staticcheck.io/docs/checks/#SA1029 + +// ContextKeyDownstreamRequestStartTime is a context.Context key to store the +// time.Time when the server began a downstream request. +type ContextKeyDownstreamRequestStartTime struct{} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/doc.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/doc.go new file mode 100644 index 000000000000..e77a831c03ea --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/doc.go @@ -0,0 +1,3 @@ +// Package tf5serverlogging contains logging functionality specific to +// tf5server and tfprotov5 types. +package tf5serverlogging diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/downstream_request.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/downstream_request.go new file mode 100644 index 000000000000..eeec76e8c939 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging/downstream_request.go @@ -0,0 +1,40 @@ +package tf5serverlogging + +import ( + "context" + "time" + + "github.com/hashicorp/terraform-plugin-go/internal/logging" + "github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag" +) + +// DownstreamRequest sets a request duration start time context key and +// generates a TRACE "Sending request downstream" log. +func DownstreamRequest(ctx context.Context) context.Context { + requestStart := time.Now() + ctx = context.WithValue(ctx, ContextKeyDownstreamRequestStartTime{}, requestStart) + + logging.ProtocolTrace(ctx, "Sending request downstream") + + return ctx +} + +// DownstreamResponse generates the following logging: +// +// - TRACE "Received downstream response" log with request duration and +// diagnostic severity counts +// - Per-diagnostic logs +// +func DownstreamResponse(ctx context.Context, diagnostics diag.Diagnostics) { + responseFields := map[string]interface{}{ + logging.KeyDiagnosticErrorCount: diagnostics.ErrorCount(), + logging.KeyDiagnosticWarningCount: diagnostics.WarningCount(), + } + + if requestStart, ok := ctx.Value(ContextKeyDownstreamRequestStartTime{}).(time.Time); ok { + responseFields[logging.KeyRequestDurationMs] = time.Since(requestStart).Milliseconds() + } + + logging.ProtocolTrace(ctx, "Received downstream response", responseFields) + diagnostics.Log(ctx) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/tfplugin5.pb.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/tfplugin5.pb.go index 793eed7a81e8..326a58bba9e8 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/tfplugin5.pb.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/tfplugin5.pb.go @@ -19,14 +19,13 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 -// protoc v3.13.0 +// protoc-gen-go v1.28.0 +// protoc v3.19.4 // source: tfplugin5.proto package tfplugin5 import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -40,10 +39,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type StringKind int32 const ( diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/tfplugin5_grpc.pb.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/tfplugin5_grpc.pb.go index 2a1c19ad1411..ddbdea31e713 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/tfplugin5_grpc.pb.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/tfplugin5_grpc.pb.go @@ -1,4 +1,8 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.2.0 +// - protoc v3.19.4 +// source: tfplugin5.proto package tfplugin5 @@ -11,6 +15,7 @@ import ( // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. const _ = grpc.SupportPackageIsVersion7 // ProviderClient is the client API for Provider service. @@ -223,8 +228,8 @@ type UnsafeProviderServer interface { mustEmbedUnimplementedProviderServer() } -func RegisterProviderServer(s *grpc.Server, srv ProviderServer) { - s.RegisterService(&_Provider_serviceDesc, srv) +func RegisterProviderServer(s grpc.ServiceRegistrar, srv ProviderServer) { + s.RegisterService(&Provider_ServiceDesc, srv) } func _Provider_GetSchema_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { @@ -443,7 +448,10 @@ func _Provider_Stop_Handler(srv interface{}, ctx context.Context, dec func(inter return interceptor(ctx, in, info, handler) } -var _Provider_serviceDesc = grpc.ServiceDesc{ +// Provider_ServiceDesc is the grpc.ServiceDesc for Provider service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Provider_ServiceDesc = grpc.ServiceDesc{ ServiceName: "tfplugin5.Provider", HandlerType: (*ProviderServer)(nil), Methods: []grpc.MethodDesc{ @@ -537,7 +545,7 @@ func (c *provisionerClient) ValidateProvisionerConfig(ctx context.Context, in *V } func (c *provisionerClient) ProvisionResource(ctx context.Context, in *ProvisionResource_Request, opts ...grpc.CallOption) (Provisioner_ProvisionResourceClient, error) { - stream, err := c.cc.NewStream(ctx, &_Provisioner_serviceDesc.Streams[0], "/tfplugin5.Provisioner/ProvisionResource", opts...) + stream, err := c.cc.NewStream(ctx, &Provisioner_ServiceDesc.Streams[0], "/tfplugin5.Provisioner/ProvisionResource", opts...) if err != nil { return nil, err } @@ -613,8 +621,8 @@ type UnsafeProvisionerServer interface { mustEmbedUnimplementedProvisionerServer() } -func RegisterProvisionerServer(s *grpc.Server, srv ProvisionerServer) { - s.RegisterService(&_Provisioner_serviceDesc, srv) +func RegisterProvisionerServer(s grpc.ServiceRegistrar, srv ProvisionerServer) { + s.RegisterService(&Provisioner_ServiceDesc, srv) } func _Provisioner_GetSchema_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { @@ -692,7 +700,10 @@ func _Provisioner_Stop_Handler(srv interface{}, ctx context.Context, dec func(in return interceptor(ctx, in, info, handler) } -var _Provisioner_serviceDesc = grpc.ServiceDesc{ +// Provisioner_ServiceDesc is the grpc.ServiceDesc for Provisioner service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Provisioner_ServiceDesc = grpc.ServiceDesc{ ServiceName: "tfplugin5.Provisioner", HandlerType: (*ProvisionerServer)(nil), Methods: []grpc.MethodDesc{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/resource.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/resource.go index c3fdd6ce4371..b86a045e957c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/resource.go @@ -98,6 +98,9 @@ type UpgradeResourceStateResponse struct { // // The state should be represented as a tftypes.Object, with each // attribute and nested block getting its own key and value. + // + // Terraform CLI 0.12 through 0.14 require the Msgpack field to be + // populated or an EOF error will be returned. UpgradedState *DynamicValue // Diagnostics report errors or warnings related to upgrading the @@ -125,6 +128,9 @@ type ReadResourceRequest struct { // Private is any provider-defined private state stored with the // resource. It is used for keeping state with the resource that is not // meant to be included when calculating diffs. + // + // To ensure private state data is preserved, copy any necessary data to + // the ReadResourceResponse type Private field. Private []byte // ProviderMeta supplies the provider metadata configuration for the @@ -212,6 +218,9 @@ type PlanResourceChangeRequest struct { // PriorPrivate is any provider-defined private state stored with the // resource. It is used for keeping state with the resource that is not // meant to be included when calculating diffs. + // + // To ensure private state data is preserved, copy any necessary data to + // the PlanResourceChangeResponse type PlannedPrivate field. PriorPrivate []byte // ProviderMeta supplies the provider metadata configuration for the @@ -280,6 +289,10 @@ type PlanResourceChangeResponse struct { // like sent with requests for this resource. This state will be // associated with the resource, but will not be considered when // calculating diffs. + // + // This private state data will be sent in the ApplyResourceChange RPC, in + // relation to the types of this package, the ApplyResourceChangeRequest + // type PlannedPrivate field. PlannedPrivate []byte // Diagnostics report errors or warnings related to determining the @@ -341,6 +354,13 @@ type ApplyResourceChangeRequest struct { // PlannedPrivate is any provider-defined private state stored with the // resource. It is used for keeping state with the resource that is not // meant to be included when calculating diffs. + // + // This private state data is sourced from the PlanResourceChange RPC, in + // relation to the types in this package, the PlanResourceChangeResponse + // type PlannedPrivate field. + // + // To ensure private state data is preserved, copy any necessary data to + // the ApplyResourceChangeResponse type Private field. PlannedPrivate []byte // ProviderMeta supplies the provider metadata configuration for the diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/schema.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/schema.go index 5f1acc34d045..b0b6dff28430 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/schema.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/schema.go @@ -68,6 +68,19 @@ type Schema struct { Block *SchemaBlock } +// ValueType returns the tftypes.Type for a Schema. +// +// If Schema is missing, an empty Object is returned. +func (s *Schema) ValueType() tftypes.Type { + if s == nil { + return tftypes.Object{ + AttributeTypes: map[string]tftypes.Type{}, + } + } + + return s.Block.ValueType() +} + // SchemaBlock represents a block in a schema. Blocks are how Terraform creates // groupings of attributes. In configurations, they don't use the equals sign // and use dynamic instead of list comprehensions. @@ -105,6 +118,51 @@ type SchemaBlock struct { Deprecated bool } +// ValueType returns the tftypes.Type for a SchemaBlock. +// +// If SchemaBlock is missing, an empty Object is returned. +func (s *SchemaBlock) ValueType() tftypes.Type { + if s == nil { + return tftypes.Object{ + AttributeTypes: map[string]tftypes.Type{}, + } + } + + attributeTypes := map[string]tftypes.Type{} + + for _, attribute := range s.Attributes { + if attribute == nil { + continue + } + + attributeType := attribute.ValueType() + + if attributeType == nil { + continue + } + + attributeTypes[attribute.Name] = attributeType + } + + for _, block := range s.BlockTypes { + if block == nil { + continue + } + + blockType := block.ValueType() + + if blockType == nil { + continue + } + + attributeTypes[block.TypeName] = blockType + } + + return tftypes.Object{ + AttributeTypes: attributeTypes, + } +} + // SchemaAttribute represents a single attribute within a schema block. // Attributes are the fields users can set in configuration using the equals // sign, can assign to variables, can interpolate, and can use list @@ -162,6 +220,17 @@ type SchemaAttribute struct { Deprecated bool } +// ValueType returns the tftypes.Type for a SchemaAttribute. +// +// If SchemaAttribute is missing, nil is returned. +func (s *SchemaAttribute) ValueType() tftypes.Type { + if s == nil { + return nil + } + + return s.Type +} + // SchemaNestedBlock is a nested block within another block. See SchemaBlock // for more information on blocks. type SchemaNestedBlock struct { @@ -198,6 +267,39 @@ type SchemaNestedBlock struct { MaxItems int64 } +// ValueType returns the tftypes.Type for a SchemaNestedBlock. +// +// If SchemaNestedBlock is missing or the Nesting mode is invalid, nil is +// returned. +func (s *SchemaNestedBlock) ValueType() tftypes.Type { + if s == nil { + return nil + } + + blockType := s.Block.ValueType() + + switch s.Nesting { + case SchemaNestedBlockNestingModeGroup: + return blockType + case SchemaNestedBlockNestingModeList: + return tftypes.List{ + ElementType: blockType, + } + case SchemaNestedBlockNestingModeMap: + return tftypes.Map{ + ElementType: blockType, + } + case SchemaNestedBlockNestingModeSet: + return tftypes.Set{ + ElementType: blockType, + } + case SchemaNestedBlockNestingModeSingle: + return blockType + default: + return nil + } +} + // SchemaNestedBlockNestingMode indicates the nesting mode for // SchemaNestedBlocks. The nesting mode determines the number of instances of // the block allowed, how many labels the block expects, and the data structure diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/tf5server/server.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/tf5server/server.go index 47426ada4912..3b48ae6c9823 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/tf5server/server.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/tf5server/server.go @@ -2,51 +2,83 @@ package tf5server import ( "context" + "encoding/json" "errors" - "log" + "fmt" + "os" + "os/signal" "regexp" + "runtime" "strings" "sync" + "time" + "github.com/hashicorp/terraform-plugin-go/internal/logging" "github.com/hashicorp/terraform-plugin-go/tfprotov5" "github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/fromproto" + "github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging" "github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5" "github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/toproto" + "google.golang.org/grpc" "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-plugin" - "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-log/tfsdklog" - tfaddr "github.com/hashicorp/terraform-registry-address" testing "github.com/mitchellh/go-testing-interface" ) -const tflogSubsystemName = "proto" - -// Global logging keys attached to all requests. -// -// Practitioners or tooling reading logs may be depending on these keys, so be -// conscious of that when changing them. const ( - // A unique ID for the RPC request - logKeyRequestID = "tf_req_id" - - // The full address of the provider, such as - // registry.terraform.io/hashicorp/random - logKeyProviderAddress = "tf_provider_addr" - - // The RPC being run, such as "ApplyResourceChange" - logKeyRPC = "tf_rpc" + // protocolVersionMajor represents the major version number of the protocol + // being served. This is used during the plugin handshake to validate the + // server and client are compatible. + // + // In the future, it may be possible to include this information directly + // in the protocol buffers rather than recreating a constant here. + protocolVersionMajor uint = 5 + + // protocolVersionMinor represents the minor version number of the protocol + // being served. Backwards compatible additions are possible in the + // protocol definitions, which is when this may be increased. While it is + // not used in plugin negotiation, it can be helpful to include this value + // for debugging, such as in logs. + // + // In the future, it may be possible to include this information directly + // in the protocol buffers rather than recreating a constant here. + protocolVersionMinor uint = 2 +) - // The type of resource being operated on, such as "random_pet" - logKeyResourceType = "tf_resource_type" +// protocolVersion represents the combined major and minor version numbers of +// the protocol being served. +var protocolVersion string = fmt.Sprintf("%d.%d", protocolVersionMajor, protocolVersionMinor) - // The type of data source being operated on, such as "archive_file" - logKeyDataSourceType = "tf_data_source_type" +const ( + // envTfReattachProviders is the environment variable used by Terraform CLI + // to directly connect to already running provider processes, such as those + // being inspected by debugging processes. When connecting to providers in + // this manner, Terraform CLI disables certain plugin handshake checks and + // will not stop the provider process. + envTfReattachProviders = "TF_REATTACH_PROVIDERS" +) - // The protocol version being used, as a string, such as "5" - logKeyProtocolVersion = "tf_proto_version" +const ( + // grpcMaxMessageSize is the maximum gRPC send and receive message sizes + // for the server. + // + // This 256MB value is arbitrarily raised from the default message sizes of + // 4MB to account for advanced use cases, but arbitrarily lowered from + // MaxInt32 (or similar) to prevent incorrect server implementations from + // exhausting resources in common execution environments. Receiving a gRPC + // message size error is preferable for troubleshooting over determining + // why an execution environment may have terminated the process via its + // memory management processes, such as oom-killer on Linux. + // + // This value is kept as constant over allowing server configurability + // since there are many factors that influence message size, such as + // Terraform configuration and state data. If larger message size use + // cases appear, other gRPC options should be explored, such as + // implementing streaming RPCs and messages. + grpcMaxMessageSize = 256 << 20 ) // ServeOpt is an interface for defining options that can be passed to the @@ -65,6 +97,10 @@ type ServeConfig struct { debugCh chan *plugin.ReattachConfig debugCloseCh chan struct{} + managedDebug bool + managedDebugReattachConfigTimeout time.Duration + managedDebugStopSignals []os.Signal + disableLogInitStderr bool disableLogLocation bool useLoggingSink testing.T @@ -79,8 +115,17 @@ func (s serveConfigFunc) ApplyServeOpt(in *ServeConfig) error { // WithDebug returns a ServeOpt that will set the server into debug mode, using // the passed options to populate the go-plugin ServeTestConfig. +// +// This is an advanced ServeOpt that assumes the caller will fully manage the +// reattach configuration and server lifecycle. Refer to WithManagedDebug for a +// ServeOpt that handles common use cases, such as implementing provider main +// functions. func WithDebug(ctx context.Context, config chan *plugin.ReattachConfig, closeCh chan struct{}) ServeOpt { return serveConfigFunc(func(in *ServeConfig) error { + if in.managedDebug { + return errors.New("cannot set both WithDebug and WithManagedDebug") + } + in.debugCtx = ctx in.debugCh = config in.debugCloseCh = closeCh @@ -88,6 +133,47 @@ func WithDebug(ctx context.Context, config chan *plugin.ReattachConfig, closeCh }) } +// WithManagedDebug returns a ServeOpt that will start the server in debug +// mode, managing the reattach configuration handling and server lifecycle. +// Reattach configuration is output to stdout with human friendly instructions. +// By default, the server can be stopped with os.Interrupt (SIGINT; ctrl-c). +// +// Refer to the optional WithManagedDebugStopSignals and +// WithManagedDebugReattachConfigTimeout ServeOpt for additional configuration. +// +// The reattach configuration output of this handling is not protected by +// compatibility guarantees. Use the WithDebug ServeOpt for advanced use cases. +func WithManagedDebug() ServeOpt { + return serveConfigFunc(func(in *ServeConfig) error { + if in.debugCh != nil { + return errors.New("cannot set both WithDebug and WithManagedDebug") + } + + in.managedDebug = true + return nil + }) +} + +// WithManagedDebugStopSignals returns a ServeOpt that will set the stop signals for a +// debug managed process (WithManagedDebug). When not configured, os.Interrupt +// (SIGINT; Ctrl-c) will stop the process. +func WithManagedDebugStopSignals(signals []os.Signal) ServeOpt { + return serveConfigFunc(func(in *ServeConfig) error { + in.managedDebugStopSignals = signals + return nil + }) +} + +// WithManagedDebugReattachConfigTimeout returns a ServeOpt that will set the timeout +// for a debug managed process to start and return its reattach configuration. +// When not configured, 2 seconds is the default. +func WithManagedDebugReattachConfigTimeout(timeout time.Duration) ServeOpt { + return serveConfigFunc(func(in *ServeConfig) error { + in.managedDebugReattachConfigTimeout = timeout + return nil + }) +} + // WithGoPluginLogger returns a ServeOpt that will set the logger that // go-plugin should use to log messages. func WithGoPluginLogger(logger hclog.Logger) ServeOpt { @@ -152,29 +238,68 @@ func WithLogEnvVarName(name string) ServeOpt { // modify the logger that go-plugin is using, ServeOpts can be specified to // support that. func Serve(name string, serverFactory func() tfprotov5.ProviderServer, opts ...ServeOpt) error { - var conf ServeConfig + // Defaults + conf := ServeConfig{ + managedDebugReattachConfigTimeout: 2 * time.Second, + managedDebugStopSignals: []os.Signal{os.Interrupt}, + } + for _, opt := range opts { err := opt.ApplyServeOpt(&conf) if err != nil { return err } } + serveConfig := &plugin.ServeConfig{ HandshakeConfig: plugin.HandshakeConfig{ - ProtocolVersion: 5, + ProtocolVersion: protocolVersionMajor, MagicCookieKey: "TF_PLUGIN_MAGIC_COOKIE", MagicCookieValue: "d602bf8f470bc67ca7faa0386276bbdd4330efaf76d1a219cb4d6991ca9872b2", }, Plugins: plugin.PluginSet{ "provider": &GRPCProviderPlugin{ + Name: name, + Opts: opts, GRPCProvider: serverFactory, }, }, - GRPCServer: plugin.DefaultGRPCServer, + GRPCServer: func(opts []grpc.ServerOption) *grpc.Server { + opts = append(opts, grpc.MaxRecvMsgSize(grpcMaxMessageSize)) + opts = append(opts, grpc.MaxSendMsgSize(grpcMaxMessageSize)) + + return grpc.NewServer(opts...) + }, } + if conf.logger != nil { serveConfig.Logger = conf.logger } + + if conf.managedDebug { + ctx, cancel := context.WithCancel(context.Background()) + signalCh := make(chan os.Signal, len(conf.managedDebugStopSignals)) + + signal.Notify(signalCh, conf.managedDebugStopSignals...) + + defer func() { + signal.Stop(signalCh) + cancel() + }() + + go func() { + select { + case <-signalCh: + cancel() + case <-ctx.Done(): + } + }() + + conf.debugCh = make(chan *plugin.ReattachConfig) + conf.debugCloseCh = make(chan struct{}) + conf.debugCtx = ctx + } + if conf.debugCh != nil { serveConfig.Test = &plugin.ServeTestConfig{ Context: conf.debugCtx, @@ -182,7 +307,78 @@ func Serve(name string, serverFactory func() tfprotov5.ProviderServer, opts ...S CloseCh: conf.debugCloseCh, } } - plugin.Serve(serveConfig) + + if !conf.managedDebug { + plugin.Serve(serveConfig) + return nil + } + + go plugin.Serve(serveConfig) + + var pluginReattachConfig *plugin.ReattachConfig + + select { + case pluginReattachConfig = <-conf.debugCh: + case <-time.After(conf.managedDebugReattachConfigTimeout): + return errors.New("timeout waiting on reattach configuration") + } + + if pluginReattachConfig == nil { + return errors.New("nil reattach configuration received") + } + + // Duplicate implementation is required because the go-plugin + // ReattachConfig.Addr implementation is not friendly for JSON encoding + // and to avoid importing terraform-exec. + type reattachConfigAddr struct { + Network string + String string + } + + type reattachConfig struct { + Protocol string + ProtocolVersion int + Pid int + Test bool + Addr reattachConfigAddr + } + + reattachBytes, err := json.Marshal(map[string]reattachConfig{ + name: { + Protocol: string(pluginReattachConfig.Protocol), + ProtocolVersion: pluginReattachConfig.ProtocolVersion, + Pid: pluginReattachConfig.Pid, + Test: pluginReattachConfig.Test, + Addr: reattachConfigAddr{ + Network: pluginReattachConfig.Addr.Network(), + String: pluginReattachConfig.Addr.String(), + }, + }, + }) + + if err != nil { + return fmt.Errorf("Error building reattach string: %w", err) + } + + reattachStr := string(reattachBytes) + + // This is currently intended to be executed via provider main function and + // human friendly, so output directly to stdout. + fmt.Printf("Provider started. To attach Terraform CLI, set the %s environment variable with the following:\n\n", envTfReattachProviders) + + switch runtime.GOOS { + case "windows": + fmt.Printf("\tCommand Prompt:\tset \"%s=%s\"\n", envTfReattachProviders, reattachStr) + fmt.Printf("\tPowerShell:\t$env:%s='%s'\n", envTfReattachProviders, strings.ReplaceAll(reattachStr, `'`, `''`)) + default: + fmt.Printf("\t%s='%s'\n", envTfReattachProviders, strings.ReplaceAll(reattachStr, `'`, `'"'"'`)) + } + + fmt.Println("") + + // Wait for the server to be done. + <-conf.debugCloseCh + return nil } @@ -198,6 +394,13 @@ type server struct { useTFLogSink bool testHandle testing.T name string + + // protocolDataDir is a directory to store raw protocol data files for + // debugging purposes. + protocolDataDir string + + // protocolVersion is the protocol version for the server. + protocolVersion string } func mergeStop(ctx context.Context, cancel context.CancelFunc, stopCh chan struct{}) { @@ -230,50 +433,11 @@ func (s *server) loggingContext(ctx context.Context) context.Context { ctx = tfsdklog.RegisterTestSink(ctx, s.testHandle) } - // generate a request ID - reqID, err := uuid.GenerateUUID() - if err != nil { - reqID = "unable to assign request ID: " + err.Error() - } - - // set up the logger SDK loggers are derived from - ctx = tfsdklog.NewRootSDKLogger(ctx, append(tfsdklog.Options{ - tfsdklog.WithLevelFromEnv("TF_LOG_SDK"), - }, s.tflogSDKOpts...)...) - ctx = tfsdklog.With(ctx, logKeyRequestID, reqID) - ctx = tfsdklog.With(ctx, logKeyProviderAddress, s.name) - - // set up our protocol-level subsystem logger - ctx = tfsdklog.NewSubsystem(ctx, tflogSubsystemName, append(tfsdklog.Options{ - tfsdklog.WithLevelFromEnv("TF_LOG_SDK_PROTO"), - }, s.tflogSDKOpts...)...) - ctx = tfsdklog.SubsystemWith(ctx, tflogSubsystemName, logKeyProtocolVersion, "5") - - // set up the provider logger - ctx = tfsdklog.NewRootProviderLogger(ctx, s.tflogOpts...) - ctx = tflog.With(ctx, logKeyRequestID, reqID) - ctx = tflog.With(ctx, logKeyProviderAddress, s.name) - return ctx -} - -func rpcLoggingContext(ctx context.Context, rpc string) context.Context { - ctx = tfsdklog.With(ctx, logKeyRPC, rpc) - ctx = tfsdklog.SubsystemWith(ctx, tflogSubsystemName, logKeyRPC, rpc) - ctx = tflog.With(ctx, logKeyRPC, rpc) - return ctx -} + ctx = logging.InitContext(ctx, s.tflogSDKOpts, s.tflogOpts) + ctx = logging.RequestIdContext(ctx) + ctx = logging.ProviderAddressContext(ctx, s.name) + ctx = logging.ProtocolVersionContext(ctx, s.protocolVersion) -func resourceLoggingContext(ctx context.Context, resource string) context.Context { - ctx = tfsdklog.With(ctx, logKeyResourceType, resource) - ctx = tfsdklog.SubsystemWith(ctx, tflogSubsystemName, logKeyResourceType, resource) - ctx = tflog.With(ctx, logKeyResourceType, resource) - return ctx -} - -func dataSourceLoggingContext(ctx context.Context, dataSource string) context.Context { - ctx = tfsdklog.With(ctx, logKeyDataSourceType, dataSource) - ctx = tfsdklog.SubsystemWith(ctx, tflogSubsystemName, logKeyDataSourceType, dataSource) - ctx = tflog.With(ctx, logKeyDataSourceType, dataSource) return ctx } @@ -301,98 +465,103 @@ func New(name string, serve tfprotov5.ProviderServer, opts ...ServeOpt) tfplugin } envVar := conf.envVar if envVar == "" { - addr, err := tfaddr.ParseRawProviderSourceString(name) - if err != nil { - log.Printf("[ERROR] Error parsing provider name %q: %s", name, err) - } else { - envVar = addr.Type - } + envVar = logging.ProviderLoggerName(name) } - envVar = strings.ReplaceAll(envVar, "-", "_") if envVar != "" { - options = append(options, tfsdklog.WithLogName(envVar), tflog.WithLevelFromEnv("TF_LOG_PROVIDER", envVar)) + options = append(options, tfsdklog.WithLogName(envVar), tflog.WithLevelFromEnv(logging.EnvTfLogProvider, envVar)) } return &server{ - downstream: serve, - stopCh: make(chan struct{}), - tflogOpts: options, - tflogSDKOpts: sdkOptions, - name: name, - useTFLogSink: conf.useLoggingSink != nil, - testHandle: conf.useLoggingSink, + downstream: serve, + stopCh: make(chan struct{}), + tflogOpts: options, + tflogSDKOpts: sdkOptions, + name: name, + useTFLogSink: conf.useLoggingSink != nil, + testHandle: conf.useLoggingSink, + protocolDataDir: os.Getenv(logging.EnvTfLogSdkProtoDataDir), + protocolVersion: protocolVersion, } } func (s *server) GetSchema(ctx context.Context, req *tfplugin5.GetProviderSchema_Request) (*tfplugin5.GetProviderSchema_Response, error) { - ctx = rpcLoggingContext(s.loggingContext(ctx), "GetSchema") + rpc := "GetProviderSchema" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.GetProviderSchemaRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.GetProviderSchema(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) ret, err := toproto.GetProviderSchema_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) PrepareProviderConfig(ctx context.Context, req *tfplugin5.PrepareProviderConfig_Request) (*tfplugin5.PrepareProviderConfig_Response, error) { - ctx = rpcLoggingContext(s.loggingContext(ctx), "PrepareProviderConfig") + rpc := "PrepareProviderConfig" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.PrepareProviderConfigRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.PrepareProviderConfig(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "PreparedConfig", resp.PreparedConfig) ret, err := toproto.PrepareProviderConfig_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) Configure(ctx context.Context, req *tfplugin5.Configure_Request) (*tfplugin5.Configure_Response, error) { - ctx = rpcLoggingContext(s.loggingContext(ctx), "Configure") + rpc := "Configure" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ConfigureProviderRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ConfigureProvider(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) ret, err := toproto.Configure_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil @@ -412,228 +581,276 @@ func (s *server) stop() { } func (s *server) Stop(ctx context.Context, req *tfplugin5.Stop_Request) (*tfplugin5.Stop_Response, error) { - ctx = rpcLoggingContext(s.loggingContext(ctx), "Stop") + rpc := "Stop" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.StopProviderRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.StopProvider(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Closing all our contexts") + tf5serverlogging.DownstreamResponse(ctx, nil) + logging.ProtocolTrace(ctx, "Closing all our contexts") s.stop() - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Closed all our contexts") + logging.ProtocolTrace(ctx, "Closed all our contexts") ret, err := toproto.Stop_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ValidateDataSourceConfig(ctx context.Context, req *tfplugin5.ValidateDataSourceConfig_Request) (*tfplugin5.ValidateDataSourceConfig_Response, error) { - ctx = dataSourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ValidateDataSourceConfig"), req.TypeName) + rpc := "ValidateDataSourceConfig" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.DataSourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ValidateDataSourceConfigRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ValidateDataSourceConfig(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) ret, err := toproto.ValidateDataSourceConfig_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ReadDataSource(ctx context.Context, req *tfplugin5.ReadDataSource_Request) (*tfplugin5.ReadDataSource_Response, error) { - ctx = dataSourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ReadDataSource"), req.TypeName) + rpc := "ReadDataSource" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.DataSourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ReadDataSourceRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "ProviderMeta", r.ProviderMeta) + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ReadDataSource(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "State", resp.State) ret, err := toproto.ReadDataSource_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ValidateResourceTypeConfig(ctx context.Context, req *tfplugin5.ValidateResourceTypeConfig_Request) (*tfplugin5.ValidateResourceTypeConfig_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ValidateResourceTypeConfig"), req.TypeName) + rpc := "ValidateResourceTypeConfig" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ValidateResourceTypeConfigRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ValidateResourceTypeConfig(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) ret, err := toproto.ValidateResourceTypeConfig_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) UpgradeResourceState(ctx context.Context, req *tfplugin5.UpgradeResourceState_Request) (*tfplugin5.UpgradeResourceState_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "UpgradeResourceState"), req.TypeName) + rpc := "UpgradeResourceState" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.UpgradeResourceStateRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.UpgradeResourceState(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "UpgradedState", resp.UpgradedState) ret, err := toproto.UpgradeResourceState_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ReadResource(ctx context.Context, req *tfplugin5.ReadResource_Request) (*tfplugin5.ReadResource_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ReadResource"), req.TypeName) + rpc := "ReadResource" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ReadResourceRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "CurrentState", r.CurrentState) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "ProviderMeta", r.ProviderMeta) + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ReadResource(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "NewState", resp.NewState) ret, err := toproto.ReadResource_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) PlanResourceChange(ctx context.Context, req *tfplugin5.PlanResourceChange_Request) (*tfplugin5.PlanResourceChange_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "PlanResourceChange"), req.TypeName) + rpc := "PlanResourceChange" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.PlanResourceChangeRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "PriorState", r.PriorState) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "ProposedNewState", r.ProposedNewState) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "ProviderMeta", r.ProviderMeta) + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.PlanResourceChange(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "PlannedState", resp.PlannedState) ret, err := toproto.PlanResourceChange_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ApplyResourceChange(ctx context.Context, req *tfplugin5.ApplyResourceChange_Request) (*tfplugin5.ApplyResourceChange_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ApplyResourceChange"), req.TypeName) + rpc := "ApplyResourceChange" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ApplyResourceChangeRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "PlannedState", r.PlannedState) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ApplyResourceChange(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "NewState", resp.NewState) ret, err := toproto.ApplyResourceChange_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ImportResourceState(ctx context.Context, req *tfplugin5.ImportResourceState_Request) (*tfplugin5.ImportResourceState_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ImportResourceState"), req.TypeName) + rpc := "ImportResourceState" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ImportResourceStateRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + ctx = tf5serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ImportResourceState(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf5serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + for _, importedResource := range resp.ImportedResources { + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response_ImportedResource", "State", importedResource.State) + } ret, err := toproto.ImportResourceState_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag/diagnostics.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag/diagnostics.go new file mode 100644 index 000000000000..543a36232fa5 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag/diagnostics.go @@ -0,0 +1,82 @@ +package diag + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-go/internal/logging" + "github.com/hashicorp/terraform-plugin-go/tfprotov6" +) + +// Diagnostics is a collection of Diagnostic. +type Diagnostics []*tfprotov6.Diagnostic + +// ErrorCount returns the number of error severity diagnostics. +func (d Diagnostics) ErrorCount() int { + var result int + + for _, diagnostic := range d { + if diagnostic == nil { + continue + } + + if diagnostic.Severity != tfprotov6.DiagnosticSeverityError { + continue + } + + result++ + } + + return result +} + +// Log will log every diagnostic: +// +// - Error severity at ERROR level +// - Warning severity at WARN level +// - Invalid/Unknown severity at WARN level +// +func (d Diagnostics) Log(ctx context.Context) { + for _, diagnostic := range d { + if diagnostic == nil { + continue + } + + diagnosticFields := map[string]interface{}{ + logging.KeyDiagnosticDetail: diagnostic.Detail, + logging.KeyDiagnosticSeverity: diagnostic.Severity.String(), + logging.KeyDiagnosticSummary: diagnostic.Summary, + } + + if diagnostic.Attribute != nil { + diagnosticFields[logging.KeyDiagnosticAttribute] = diagnostic.Attribute.String() + } + + switch diagnostic.Severity { + case tfprotov6.DiagnosticSeverityError: + logging.ProtocolError(ctx, "Response contains error diagnostic", diagnosticFields) + case tfprotov6.DiagnosticSeverityWarning: + logging.ProtocolWarn(ctx, "Response contains warning diagnostic", diagnosticFields) + default: + logging.ProtocolWarn(ctx, "Response contains unknown diagnostic", diagnosticFields) + } + } +} + +// WarningCount returns the number of warning severity diagnostics. +func (d Diagnostics) WarningCount() int { + var result int + + for _, diagnostic := range d { + if diagnostic == nil { + continue + } + + if diagnostic.Severity != tfprotov6.DiagnosticSeverityWarning { + continue + } + + result++ + } + + return result +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag/doc.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag/doc.go new file mode 100644 index 000000000000..0c73dab12fe6 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag/doc.go @@ -0,0 +1,3 @@ +// Package diag contains diagnostics helpers. These implementations are +// intentionally outside the public API. +package diag diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto/resource.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto/resource.go index 1f8deed34c01..94addd801251 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto/resource.go @@ -103,7 +103,8 @@ func PlanResourceChangeRequest(in *tfplugin6.PlanResourceChange_Request) (*tfpro func PlanResourceChangeResponse(in *tfplugin6.PlanResourceChange_Response) (*tfprotov6.PlanResourceChangeResponse, error) { resp := &tfprotov6.PlanResourceChangeResponse{ - PlannedPrivate: in.PlannedPrivate, + PlannedPrivate: in.PlannedPrivate, + UnsafeToUseLegacyTypeSystem: in.LegacyTypeSystem, } attributePaths, err := AttributePaths(in.RequiresReplace) if err != nil { @@ -143,7 +144,8 @@ func ApplyResourceChangeRequest(in *tfplugin6.ApplyResourceChange_Request) (*tfp func ApplyResourceChangeResponse(in *tfplugin6.ApplyResourceChange_Response) (*tfprotov6.ApplyResourceChangeResponse, error) { resp := &tfprotov6.ApplyResourceChangeResponse{ - Private: in.Private, + Private: in.Private, + UnsafeToUseLegacyTypeSystem: in.LegacyTypeSystem, } diags, err := Diagnostics(in.Diagnostics) if err != nil { diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto/schema.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto/schema.go index 388a0193cf2e..db720246f510 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto/schema.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto/schema.go @@ -131,9 +131,7 @@ func SchemaObjectNestingMode(in tfplugin6.Schema_Object_NestingMode) tfprotov6.S func SchemaObject(in *tfplugin6.Schema_Object) (*tfprotov6.SchemaObject, error) { resp := &tfprotov6.SchemaObject{ - Nesting: SchemaObjectNestingMode(in.Nesting), - MinItems: in.MinItems, - MaxItems: in.MaxItems, + Nesting: SchemaObjectNestingMode(in.Nesting), } attrs, err := SchemaAttributes(in.Attributes) diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/context_keys.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/context_keys.go new file mode 100644 index 000000000000..15386cd2cc2d --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/context_keys.go @@ -0,0 +1,8 @@ +package tf6serverlogging + +// Context key types. +// Reference: https://staticcheck.io/docs/checks/#SA1029 + +// ContextKeyDownstreamRequestStartTime is a context.Context key to store the +// time.Time when the server began a downstream request. +type ContextKeyDownstreamRequestStartTime struct{} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/doc.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/doc.go new file mode 100644 index 000000000000..167a61825acd --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/doc.go @@ -0,0 +1,3 @@ +// Package tf5serverlogging contains logging functionality specific to +// tf5server and tfprotov5 types. +package tf6serverlogging diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/downstream_request.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/downstream_request.go new file mode 100644 index 000000000000..c47df9b457fe --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging/downstream_request.go @@ -0,0 +1,40 @@ +package tf6serverlogging + +import ( + "context" + "time" + + "github.com/hashicorp/terraform-plugin-go/internal/logging" + "github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag" +) + +// DownstreamRequest sets a request duration start time context key and +// generates a TRACE "Sending request downstream" log. +func DownstreamRequest(ctx context.Context) context.Context { + requestStart := time.Now() + ctx = context.WithValue(ctx, ContextKeyDownstreamRequestStartTime{}, requestStart) + + logging.ProtocolTrace(ctx, "Sending request downstream") + + return ctx +} + +// DownstreamResponse generates the following logging: +// +// - TRACE "Received downstream response" log with request duration and +// diagnostic severity counts +// - Per-diagnostic logs +// +func DownstreamResponse(ctx context.Context, diagnostics diag.Diagnostics) { + responseFields := map[string]interface{}{ + logging.KeyDiagnosticErrorCount: diagnostics.ErrorCount(), + logging.KeyDiagnosticWarningCount: diagnostics.WarningCount(), + } + + if requestStart, ok := ctx.Value(ContextKeyDownstreamRequestStartTime{}).(time.Time); ok { + responseFields[logging.KeyRequestDurationMs] = time.Since(requestStart).Milliseconds() + } + + logging.ProtocolTrace(ctx, "Received downstream response", responseFields) + diagnostics.Log(ctx) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6.pb.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6.pb.go index 332ece40ec8f..a61e1875c5af 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6.pb.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6.pb.go @@ -1,6 +1,6 @@ -// Terraform Plugin RPC protocol version 6.0 +// Terraform Plugin RPC protocol version 6.2 // -// This file defines version 6.0 of the RPC protocol. To implement a plugin +// This file defines version 6.2 of the RPC protocol. To implement a plugin // against this protocol, copy this definition into your own codebase and // use protoc to generate stubs for your target language. // @@ -19,14 +19,13 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.23.0 -// protoc v3.15.6 +// protoc-gen-go v1.28.0 +// protoc v3.19.4 // source: tfplugin6.proto package tfplugin6 import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -40,10 +39,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type StringKind int32 const ( @@ -1476,8 +1471,13 @@ type Schema_Object struct { Attributes []*Schema_Attribute `protobuf:"bytes,1,rep,name=attributes,proto3" json:"attributes,omitempty"` Nesting Schema_Object_NestingMode `protobuf:"varint,3,opt,name=nesting,proto3,enum=tfplugin6.Schema_Object_NestingMode" json:"nesting,omitempty"` - MinItems int64 `protobuf:"varint,4,opt,name=min_items,json=minItems,proto3" json:"min_items,omitempty"` - MaxItems int64 `protobuf:"varint,5,opt,name=max_items,json=maxItems,proto3" json:"max_items,omitempty"` + // MinItems and MaxItems were never used in the protocol, and have no + // effect on validation. + // + // Deprecated: Do not use. + MinItems int64 `protobuf:"varint,4,opt,name=min_items,json=minItems,proto3" json:"min_items,omitempty"` + // Deprecated: Do not use. + MaxItems int64 `protobuf:"varint,5,opt,name=max_items,json=maxItems,proto3" json:"max_items,omitempty"` } func (x *Schema_Object) Reset() { @@ -1526,6 +1526,7 @@ func (x *Schema_Object) GetNesting() Schema_Object_NestingMode { return Schema_Object_INVALID } +// Deprecated: Do not use. func (x *Schema_Object) GetMinItems() int64 { if x != nil { return x.MinItems @@ -1533,6 +1534,7 @@ func (x *Schema_Object) GetMinItems() int64 { return 0 } +// Deprecated: Do not use. func (x *Schema_Object) GetMaxItems() int64 { if x != nil { return x.MaxItems @@ -2417,6 +2419,18 @@ type PlanResourceChange_Response struct { RequiresReplace []*AttributePath `protobuf:"bytes,2,rep,name=requires_replace,json=requiresReplace,proto3" json:"requires_replace,omitempty"` PlannedPrivate []byte `protobuf:"bytes,3,opt,name=planned_private,json=plannedPrivate,proto3" json:"planned_private,omitempty"` Diagnostics []*Diagnostic `protobuf:"bytes,4,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` + // This may be set only by the helper/schema "SDK" in the main Terraform + // repository, to request that Terraform Core >=0.12 permit additional + // inconsistencies that can result from the legacy SDK type system + // and its imprecise mapping to the >=0.12 type system. + // The change in behavior implied by this flag makes sense only for the + // specific details of the legacy SDK type system, and are not a general + // mechanism to avoid proper type handling in providers. + // + // ==== DO NOT USE THIS ==== + // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== + // ==== DO NOT USE THIS ==== + LegacyTypeSystem bool `protobuf:"varint,5,opt,name=legacy_type_system,json=legacyTypeSystem,proto3" json:"legacy_type_system,omitempty"` } func (x *PlanResourceChange_Response) Reset() { @@ -2479,6 +2493,13 @@ func (x *PlanResourceChange_Response) GetDiagnostics() []*Diagnostic { return nil } +func (x *PlanResourceChange_Response) GetLegacyTypeSystem() bool { + if x != nil { + return x.LegacyTypeSystem + } + return false +} + type ApplyResourceChange_Request struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2574,6 +2595,18 @@ type ApplyResourceChange_Response struct { NewState *DynamicValue `protobuf:"bytes,1,opt,name=new_state,json=newState,proto3" json:"new_state,omitempty"` Private []byte `protobuf:"bytes,2,opt,name=private,proto3" json:"private,omitempty"` Diagnostics []*Diagnostic `protobuf:"bytes,3,rep,name=diagnostics,proto3" json:"diagnostics,omitempty"` + // This may be set only by the helper/schema "SDK" in the main Terraform + // repository, to request that Terraform Core >=0.12 permit additional + // inconsistencies that can result from the legacy SDK type system + // and its imprecise mapping to the >=0.12 type system. + // The change in behavior implied by this flag makes sense only for the + // specific details of the legacy SDK type system, and are not a general + // mechanism to avoid proper type handling in providers. + // + // ==== DO NOT USE THIS ==== + // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== + // ==== DO NOT USE THIS ==== + LegacyTypeSystem bool `protobuf:"varint,4,opt,name=legacy_type_system,json=legacyTypeSystem,proto3" json:"legacy_type_system,omitempty"` } func (x *ApplyResourceChange_Response) Reset() { @@ -2629,6 +2662,13 @@ func (x *ApplyResourceChange_Response) GetDiagnostics() []*Diagnostic { return nil } +func (x *ApplyResourceChange_Response) GetLegacyTypeSystem() bool { + if x != nil { + return x.LegacyTypeSystem + } + return false +} + type ImportResourceState_Request struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2970,7 +3010,7 @@ var file_tfplugin6_proto_rawDesc = []byte{ 0x74, 0x6d, 0x61, 0x70, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, - 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x8d, 0x0a, 0x0a, 0x06, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, + 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x95, 0x0a, 0x0a, 0x06, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2d, 0x0a, 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, @@ -3035,7 +3075,7 @@ var file_tfplugin6_proto_rawDesc = []byte{ 0x53, 0x49, 0x4e, 0x47, 0x4c, 0x45, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x4c, 0x49, 0x53, 0x54, 0x10, 0x02, 0x12, 0x07, 0x0a, 0x03, 0x53, 0x45, 0x54, 0x10, 0x03, 0x12, 0x07, 0x0a, 0x03, 0x4d, 0x41, 0x50, 0x10, 0x04, 0x12, 0x09, 0x0a, 0x05, 0x47, 0x52, 0x4f, 0x55, 0x50, 0x10, 0x05, 0x1a, - 0x83, 0x02, 0x0a, 0x06, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x3b, 0x0a, 0x0a, 0x61, 0x74, + 0x8b, 0x02, 0x0a, 0x06, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x3b, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2e, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, @@ -3043,328 +3083,334 @@ var file_tfplugin6_proto_rawDesc = []byte{ 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2e, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x2e, 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x4d, 0x6f, 0x64, 0x65, 0x52, 0x07, - 0x6e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x1b, 0x0a, 0x09, 0x6d, 0x69, 0x6e, 0x5f, 0x69, - 0x74, 0x65, 0x6d, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x6d, 0x69, 0x6e, 0x49, - 0x74, 0x65, 0x6d, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x6d, 0x61, 0x78, 0x5f, 0x69, 0x74, 0x65, 0x6d, - 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x6d, 0x61, 0x78, 0x49, 0x74, 0x65, 0x6d, - 0x73, 0x22, 0x42, 0x0a, 0x0b, 0x4e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x4d, 0x6f, 0x64, 0x65, - 0x12, 0x0b, 0x0a, 0x07, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, - 0x06, 0x53, 0x49, 0x4e, 0x47, 0x4c, 0x45, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x4c, 0x49, 0x53, - 0x54, 0x10, 0x02, 0x12, 0x07, 0x0a, 0x03, 0x53, 0x45, 0x54, 0x10, 0x03, 0x12, 0x07, 0x0a, 0x03, - 0x4d, 0x41, 0x50, 0x10, 0x04, 0x22, 0xd0, 0x04, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, - 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x1a, 0x09, 0x0a, 0x07, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0xaf, 0x04, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x2d, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, - 0x36, 0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, - 0x65, 0x72, 0x12, 0x65, 0x0a, 0x10, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x73, - 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3a, 0x2e, 0x74, - 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x76, - 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x63, 0x68, 0x65, - 0x6d, 0x61, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x12, 0x6c, 0x0a, 0x13, 0x64, 0x61, 0x74, - 0x61, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, - 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3c, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, - 0x6e, 0x36, 0x2e, 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, - 0x68, 0x65, 0x6d, 0x61, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x44, 0x61, - 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x45, - 0x6e, 0x74, 0x72, 0x79, 0x52, 0x11, 0x64, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, - 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, - 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, - 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, - 0x12, 0x36, 0x0a, 0x0d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x74, - 0x61, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, - 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x52, 0x0c, 0x70, 0x72, 0x6f, 0x76, - 0x69, 0x64, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, 0x1a, 0x55, 0x0a, 0x14, 0x52, 0x65, 0x73, 0x6f, + 0x6e, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x1f, 0x0a, 0x09, 0x6d, 0x69, 0x6e, 0x5f, 0x69, + 0x74, 0x65, 0x6d, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x42, 0x02, 0x18, 0x01, 0x52, 0x08, + 0x6d, 0x69, 0x6e, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x1f, 0x0a, 0x09, 0x6d, 0x61, 0x78, 0x5f, + 0x69, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x42, 0x02, 0x18, 0x01, 0x52, + 0x08, 0x6d, 0x61, 0x78, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x22, 0x42, 0x0a, 0x0b, 0x4e, 0x65, 0x73, + 0x74, 0x69, 0x6e, 0x67, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x49, 0x4e, 0x56, 0x41, + 0x4c, 0x49, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x53, 0x49, 0x4e, 0x47, 0x4c, 0x45, 0x10, + 0x01, 0x12, 0x08, 0x0a, 0x04, 0x4c, 0x49, 0x53, 0x54, 0x10, 0x02, 0x12, 0x07, 0x0a, 0x03, 0x53, + 0x45, 0x54, 0x10, 0x03, 0x12, 0x07, 0x0a, 0x03, 0x4d, 0x41, 0x50, 0x10, 0x04, 0x22, 0xd0, 0x04, + 0x0a, 0x11, 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, 0x68, + 0x65, 0x6d, 0x61, 0x1a, 0x09, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0xaf, + 0x04, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2d, 0x0a, 0x08, 0x70, + 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, + 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, + 0x52, 0x08, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, 0x65, 0x0a, 0x10, 0x72, 0x65, + 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x18, 0x02, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3a, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, + 0x2e, 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, 0x68, 0x65, + 0x6d, 0x61, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, - 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, - 0x65, 0x79, 0x12, 0x27, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x63, - 0x68, 0x65, 0x6d, 0x61, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, - 0x57, 0x0a, 0x16, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x63, 0x68, - 0x65, 0x6d, 0x61, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x27, 0x0a, 0x05, 0x76, - 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x66, 0x70, - 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x52, 0x05, 0x76, - 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x99, 0x01, 0x0a, 0x16, 0x56, 0x61, 0x6c, - 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x43, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x1a, 0x3a, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2f, - 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, - 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, - 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, - 0x43, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, - 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, - 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, - 0x74, 0x69, 0x63, 0x73, 0x22, 0x90, 0x02, 0x0a, 0x14, 0x55, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, - 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x1a, 0x72, 0x0a, - 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, - 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, - 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, - 0x30, 0x0a, 0x09, 0x72, 0x61, 0x77, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x52, - 0x61, 0x77, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x08, 0x72, 0x61, 0x77, 0x53, 0x74, 0x61, 0x74, - 0x65, 0x1a, 0x83, 0x01, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3e, - 0x0a, 0x0e, 0x75, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x64, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, + 0x52, 0x0f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, + 0x73, 0x12, 0x6c, 0x0a, 0x13, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x5f, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3c, + 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x47, 0x65, 0x74, 0x50, 0x72, + 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2e, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x11, 0x64, 0x61, + 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x12, + 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x04, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, + 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, + 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x12, 0x36, 0x0a, 0x0d, 0x70, 0x72, 0x6f, 0x76, + 0x69, 0x64, 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x11, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x63, 0x68, 0x65, + 0x6d, 0x61, 0x52, 0x0c, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, + 0x1a, 0x55, 0x0a, 0x14, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x63, 0x68, 0x65, + 0x6d, 0x61, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x27, 0x0a, 0x05, 0x76, 0x61, + 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x66, 0x70, 0x6c, + 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x52, 0x05, 0x76, 0x61, + 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x57, 0x0a, 0x16, 0x44, 0x61, 0x74, 0x61, 0x53, + 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x73, 0x45, 0x6e, 0x74, 0x72, + 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, + 0x6b, 0x65, 0x79, 0x12, 0x27, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, + 0x63, 0x68, 0x65, 0x6d, 0x61, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, + 0x22, 0x99, 0x01, 0x0a, 0x16, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, + 0x76, 0x69, 0x64, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x3a, 0x0a, 0x07, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x0d, 0x75, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x64, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x37, - 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x02, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, - 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, - 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0xb6, 0x01, 0x0a, 0x16, 0x56, 0x61, 0x6c, 0x69, - 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x1a, 0x57, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, - 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, - 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x43, 0x0a, 0x08, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, - 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, - 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, - 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, - 0x22, 0xba, 0x01, 0x0a, 0x1a, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, - 0x61, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, - 0x57, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, - 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, - 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, - 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x43, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, - 0x69, 0x63, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, - 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, - 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0xc1, 0x01, - 0x0a, 0x11, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, - 0x64, 0x65, 0x72, 0x1a, 0x67, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2b, - 0x0a, 0x11, 0x74, 0x65, 0x72, 0x72, 0x61, 0x66, 0x6f, 0x72, 0x6d, 0x5f, 0x76, 0x65, 0x72, 0x73, - 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x74, 0x65, 0x72, 0x72, 0x61, - 0x66, 0x6f, 0x72, 0x6d, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2f, 0x0a, 0x06, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, - 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x43, 0x0a, 0x08, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, - 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, - 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, - 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, - 0x73, 0x22, 0xe3, 0x02, 0x0a, 0x0c, 0x52, 0x65, 0x61, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x1a, 0xbc, 0x01, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, - 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x63, - 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, + 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x43, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, + 0x63, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, + 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, + 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0x90, 0x02, 0x0a, + 0x14, 0x55, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x53, 0x74, 0x61, 0x74, 0x65, 0x1a, 0x72, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, + 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, + 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x30, 0x0a, 0x09, 0x72, 0x61, 0x77, 0x5f, 0x73, + 0x74, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x74, 0x66, 0x70, + 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x52, 0x61, 0x77, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, + 0x08, 0x72, 0x61, 0x77, 0x53, 0x74, 0x61, 0x74, 0x65, 0x1a, 0x83, 0x01, 0x0a, 0x08, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3e, 0x0a, 0x0e, 0x75, 0x70, 0x67, 0x72, 0x61, 0x64, + 0x65, 0x64, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, + 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, + 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0d, 0x75, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, + 0x64, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, + 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, + 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, + 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, + 0xb6, 0x01, 0x0a, 0x16, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x6f, + 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x57, 0x0a, 0x07, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, + 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, + 0x6d, 0x65, 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, - 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x63, 0x75, 0x72, - 0x72, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x72, 0x69, - 0x76, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x72, 0x69, 0x76, - 0x61, 0x74, 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x5f, - 0x6d, 0x65, 0x74, 0x61, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, + 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x67, 0x1a, 0x43, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, + 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x01, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, + 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, + 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0xba, 0x01, 0x0a, 0x1a, 0x56, 0x61, 0x6c, + 0x69, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, + 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x57, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, + 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, + 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x1a, 0x43, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x0b, + 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, + 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, + 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0xc1, 0x01, 0x0a, 0x11, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x75, 0x72, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x1a, 0x67, 0x0a, 0x07, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2b, 0x0a, 0x11, 0x74, 0x65, 0x72, 0x72, 0x61, 0x66, + 0x6f, 0x72, 0x6d, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x10, 0x74, 0x65, 0x72, 0x72, 0x61, 0x66, 0x6f, 0x72, 0x6d, 0x56, 0x65, 0x72, 0x73, + 0x69, 0x6f, 0x6e, 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, + 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x43, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, + 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, + 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, + 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0xe3, 0x02, 0x0a, 0x0c, 0x52, 0x65, + 0x61, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x1a, 0xbc, 0x01, 0x0a, 0x07, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, + 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, + 0x61, 0x6d, 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x73, + 0x74, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x4d, 0x65, 0x74, - 0x61, 0x1a, 0x93, 0x01, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x34, - 0x0a, 0x09, 0x6e, 0x65, 0x77, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, - 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x6e, 0x65, 0x77, 0x53, - 0x74, 0x61, 0x74, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, - 0x69, 0x63, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, - 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, - 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x12, 0x18, 0x0a, - 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, - 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x22, 0xc4, 0x04, 0x0a, 0x12, 0x50, 0x6c, 0x61, 0x6e, - 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x1a, 0xbb, - 0x02, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, - 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, - 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x38, 0x0a, 0x0b, 0x70, 0x72, 0x69, 0x6f, 0x72, - 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, - 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x53, 0x74, 0x61, 0x74, - 0x65, 0x12, 0x45, 0x0a, 0x12, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x65, 0x64, 0x5f, 0x6e, 0x65, - 0x77, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, - 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, - 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x10, 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x65, 0x64, - 0x4e, 0x65, 0x77, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, - 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x23, 0x0a, 0x0d, 0x70, 0x72, 0x69, - 0x6f, 0x72, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x0c, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x12, 0x3c, - 0x0a, 0x0d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x18, - 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, - 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, - 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, 0x1a, 0xef, 0x01, 0x0a, - 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x70, 0x6c, 0x61, - 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, - 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x70, 0x6c, 0x61, 0x6e, 0x6e, - 0x65, 0x64, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x43, 0x0a, 0x10, 0x72, 0x65, 0x71, 0x75, 0x69, - 0x72, 0x65, 0x73, 0x5f, 0x72, 0x65, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x18, 0x02, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x18, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x41, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x50, 0x61, 0x74, 0x68, 0x52, 0x0f, 0x72, 0x65, 0x71, - 0x75, 0x69, 0x72, 0x65, 0x73, 0x52, 0x65, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x12, 0x27, 0x0a, 0x0f, - 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x18, - 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x50, 0x72, - 0x69, 0x76, 0x61, 0x74, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, - 0x74, 0x69, 0x63, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, - 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, - 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0xe4, - 0x03, 0x0a, 0x13, 0x41, 0x70, 0x70, 0x6c, 0x79, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x1a, 0xb6, 0x02, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x61, 0x74, + 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x0c, 0x52, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x70, + 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x18, 0x04, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, + 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x70, 0x72, 0x6f, + 0x76, 0x69, 0x64, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, 0x1a, 0x93, 0x01, 0x0a, 0x08, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x34, 0x0a, 0x09, 0x6e, 0x65, 0x77, 0x5f, 0x73, 0x74, + 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, + 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, + 0x75, 0x65, 0x52, 0x08, 0x6e, 0x65, 0x77, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x37, 0x0a, 0x0b, + 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, + 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, + 0x73, 0x74, 0x69, 0x63, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x22, + 0xf2, 0x04, 0x0a, 0x12, 0x50, 0x6c, 0x61, 0x6e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x1a, 0xbb, 0x02, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x38, 0x0a, 0x0b, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x70, - 0x72, 0x69, 0x6f, 0x72, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x70, 0x6c, 0x61, - 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, + 0x72, 0x69, 0x6f, 0x72, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x45, 0x0a, 0x12, 0x70, 0x72, 0x6f, + 0x70, 0x6f, 0x73, 0x65, 0x64, 0x5f, 0x6e, 0x65, 0x77, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, + 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x10, + 0x70, 0x72, 0x6f, 0x70, 0x6f, 0x73, 0x65, 0x64, 0x4e, 0x65, 0x77, 0x53, 0x74, 0x61, 0x74, 0x65, + 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, - 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x70, 0x6c, 0x61, 0x6e, 0x6e, - 0x65, 0x64, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, - 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x27, 0x0a, 0x0f, 0x70, 0x6c, 0x61, 0x6e, - 0x6e, 0x65, 0x64, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, - 0x0c, 0x52, 0x0e, 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, - 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x5f, 0x6d, 0x65, - 0x74, 0x61, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, + 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x12, 0x23, 0x0a, 0x0d, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, + 0x74, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x50, + 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, + 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, + 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, + 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, + 0x4d, 0x65, 0x74, 0x61, 0x1a, 0x9d, 0x02, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x73, 0x74, 0x61, + 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x0c, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, 0x1a, - 0x93, 0x01, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x34, 0x0a, 0x09, - 0x6e, 0x65, 0x77, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, - 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x6e, 0x65, 0x77, 0x53, 0x74, 0x61, - 0x74, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x12, 0x37, 0x0a, 0x0b, - 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, - 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, - 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0xed, 0x02, 0x0a, 0x13, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, - 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x1a, 0x36, 0x0a, + 0x65, 0x52, 0x0c, 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, + 0x43, 0x0a, 0x10, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x73, 0x5f, 0x72, 0x65, 0x70, 0x6c, + 0x61, 0x63, 0x65, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x74, 0x66, 0x70, 0x6c, + 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x50, + 0x61, 0x74, 0x68, 0x52, 0x0f, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x73, 0x52, 0x65, 0x70, + 0x6c, 0x61, 0x63, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x5f, + 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x70, + 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x12, 0x37, 0x0a, + 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x04, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, + 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, + 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x12, 0x2c, 0x0a, 0x12, 0x6c, 0x65, 0x67, 0x61, 0x63, 0x79, + 0x5f, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x18, 0x05, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x10, 0x6c, 0x65, 0x67, 0x61, 0x63, 0x79, 0x54, 0x79, 0x70, 0x65, 0x53, 0x79, + 0x73, 0x74, 0x65, 0x6d, 0x22, 0x92, 0x04, 0x0a, 0x13, 0x41, 0x70, 0x70, 0x6c, 0x79, 0x52, 0x65, + 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x1a, 0xb6, 0x02, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, - 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x02, 0x69, 0x64, 0x1a, 0x78, 0x0a, 0x10, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x65, - 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, - 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, - 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2d, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, - 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, - 0x73, 0x74, 0x61, 0x74, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x1a, - 0xa3, 0x01, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x5e, 0x0a, 0x12, - 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, - 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x73, 0x6f, 0x75, - 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x65, - 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x11, 0x69, 0x6d, 0x70, 0x6f, 0x72, - 0x74, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x12, 0x37, 0x0a, 0x0b, - 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, - 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, - 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0x9c, 0x02, 0x0a, 0x0e, 0x52, 0x65, 0x61, 0x64, 0x44, 0x61, - 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x1a, 0x95, 0x01, 0x0a, 0x07, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, - 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, - 0x65, 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, - 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x12, 0x3c, 0x0a, 0x0d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x5f, 0x6d, - 0x65, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, + 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x38, 0x0a, 0x0b, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x5f, 0x73, + 0x74, 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, + 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, + 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, + 0x3c, 0x0a, 0x0d, 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, + 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, + 0x0c, 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x2f, 0x0a, + 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, + 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, + 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x27, + 0x0a, 0x0f, 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, + 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x70, 0x6c, 0x61, 0x6e, 0x6e, 0x65, 0x64, + 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x12, 0x3c, 0x0a, 0x0d, 0x70, 0x72, 0x6f, 0x76, 0x69, + 0x64, 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, + 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, + 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, + 0x72, 0x4d, 0x65, 0x74, 0x61, 0x1a, 0xc1, 0x01, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x34, 0x0a, 0x09, 0x6e, 0x65, 0x77, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, + 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, + 0x6e, 0x65, 0x77, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x72, 0x69, 0x76, + 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, + 0x74, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, + 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, + 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, + 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x12, 0x2c, 0x0a, 0x12, 0x6c, + 0x65, 0x67, 0x61, 0x63, 0x79, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, + 0x6d, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x10, 0x6c, 0x65, 0x67, 0x61, 0x63, 0x79, 0x54, + 0x79, 0x70, 0x65, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x22, 0xed, 0x02, 0x0a, 0x13, 0x49, 0x6d, + 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, + 0x65, 0x1a, 0x36, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, + 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x1a, 0x78, 0x0a, 0x10, 0x49, 0x6d, 0x70, + 0x6f, 0x72, 0x74, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x1b, 0x0a, + 0x09, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x08, 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2d, 0x0a, 0x05, 0x73, 0x74, + 0x61, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x52, 0x0c, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, - 0x1a, 0x72, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2d, 0x0a, 0x05, - 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, - 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x12, 0x37, 0x0a, 0x0b, 0x64, - 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x69, 0x61, - 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, - 0x74, 0x69, 0x63, 0x73, 0x2a, 0x25, 0x0a, 0x0a, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x4b, 0x69, - 0x6e, 0x64, 0x12, 0x09, 0x0a, 0x05, 0x50, 0x4c, 0x41, 0x49, 0x4e, 0x10, 0x00, 0x12, 0x0c, 0x0a, - 0x08, 0x4d, 0x41, 0x52, 0x4b, 0x44, 0x4f, 0x57, 0x4e, 0x10, 0x01, 0x32, 0xcc, 0x09, 0x0a, 0x08, - 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, 0x60, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x50, - 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x12, 0x24, 0x2e, - 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, - 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2e, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x25, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, + 0x75, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x72, 0x69, + 0x76, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x72, 0x69, 0x76, + 0x61, 0x74, 0x65, 0x1a, 0xa3, 0x01, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x5e, 0x0a, 0x12, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x73, + 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x74, + 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x52, + 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x49, 0x6d, 0x70, + 0x6f, 0x72, 0x74, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x11, 0x69, + 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, + 0x12, 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, + 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, + 0x36, 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, + 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x22, 0x9c, 0x02, 0x0a, 0x0e, 0x52, 0x65, + 0x61, 0x64, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x1a, 0x95, 0x01, 0x0a, + 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x79, 0x70, 0x65, + 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x79, 0x70, + 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2f, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, + 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x3c, 0x0a, 0x0d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, + 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, + 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, 0x6d, 0x69, + 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, + 0x4d, 0x65, 0x74, 0x61, 0x1a, 0x72, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x2d, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x17, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x44, 0x79, 0x6e, 0x61, + 0x6d, 0x69, 0x63, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x12, + 0x37, 0x0a, 0x0b, 0x64, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x18, 0x02, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, + 0x2e, 0x44, 0x69, 0x61, 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x52, 0x0b, 0x64, 0x69, 0x61, + 0x67, 0x6e, 0x6f, 0x73, 0x74, 0x69, 0x63, 0x73, 0x2a, 0x25, 0x0a, 0x0a, 0x53, 0x74, 0x72, 0x69, + 0x6e, 0x67, 0x4b, 0x69, 0x6e, 0x64, 0x12, 0x09, 0x0a, 0x05, 0x50, 0x4c, 0x41, 0x49, 0x4e, 0x10, + 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x4d, 0x41, 0x52, 0x4b, 0x44, 0x4f, 0x57, 0x4e, 0x10, 0x01, 0x32, + 0xcc, 0x09, 0x0a, 0x08, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, 0x60, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, 0x68, 0x65, 0x6d, - 0x61, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6f, 0x0a, 0x16, 0x56, 0x61, - 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x43, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x12, 0x29, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, - 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, - 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, - 0x2a, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x56, 0x61, 0x6c, 0x69, - 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6f, 0x0a, 0x16, 0x56, - 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x29, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, - 0x36, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x2a, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x56, 0x61, 0x6c, - 0x69, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x7b, 0x0a, 0x1a, - 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x2d, 0x2e, 0x74, 0x66, 0x70, - 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x44, - 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2e, 0x2e, 0x74, 0x66, 0x70, 0x6c, - 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, - 0x74, 0x61, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x69, 0x0a, 0x14, 0x55, 0x70, 0x67, - 0x72, 0x61, 0x64, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, - 0x65, 0x12, 0x27, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x55, 0x70, - 0x67, 0x72, 0x61, 0x64, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, - 0x74, 0x65, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x28, 0x2e, 0x74, 0x66, 0x70, - 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x55, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x52, 0x65, - 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x60, 0x0a, 0x11, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, - 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, 0x24, 0x2e, 0x74, 0x66, 0x70, 0x6c, - 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x65, 0x50, - 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, - 0x25, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x75, 0x72, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x51, 0x0a, 0x0c, 0x52, 0x65, 0x61, 0x64, 0x52, 0x65, - 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x1f, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, - 0x6e, 0x36, 0x2e, 0x52, 0x65, 0x61, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x20, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, - 0x69, 0x6e, 0x36, 0x2e, 0x52, 0x65, 0x61, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x63, 0x0a, 0x12, 0x50, 0x6c, 0x61, - 0x6e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, - 0x25, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x50, 0x6c, 0x61, 0x6e, - 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x26, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, - 0x6e, 0x36, 0x2e, 0x50, 0x6c, 0x61, 0x6e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, - 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x66, - 0x0a, 0x13, 0x41, 0x70, 0x70, 0x6c, 0x79, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, - 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x26, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, - 0x36, 0x2e, 0x41, 0x70, 0x70, 0x6c, 0x79, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, - 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, - 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x41, 0x70, 0x70, 0x6c, 0x79, 0x52, - 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x66, 0x0a, 0x13, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, - 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x26, 0x2e, - 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, - 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, - 0x36, 0x2e, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x53, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x57, - 0x0a, 0x0e, 0x52, 0x65, 0x61, 0x64, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x12, 0x21, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x52, 0x65, 0x61, - 0x64, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x22, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, - 0x52, 0x65, 0x61, 0x64, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x51, 0x0a, 0x0c, 0x53, 0x74, 0x6f, 0x70, 0x50, - 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, 0x1f, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, - 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x74, 0x6f, 0x70, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, - 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x20, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, - 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x74, 0x6f, 0x70, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, - 0x72, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x33, 0x5a, 0x31, 0x67, 0x69, - 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, - 0x72, 0x70, 0x2f, 0x74, 0x65, 0x72, 0x72, 0x61, 0x66, 0x6f, 0x72, 0x6d, 0x2f, 0x69, 0x6e, 0x74, - 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x62, - 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x61, 0x12, 0x24, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x47, 0x65, + 0x74, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2e, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x25, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, + 0x69, 0x6e, 0x36, 0x2e, 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, + 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6f, + 0x0a, 0x16, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, + 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x29, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, + 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, + 0x76, 0x69, 0x64, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x2a, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, + 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, + 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, + 0x6f, 0x0a, 0x16, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, + 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x29, 0x2e, 0x74, 0x66, 0x70, 0x6c, + 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, + 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2a, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, + 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, + 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x7b, 0x0a, 0x1a, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, + 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x2d, + 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, + 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2e, 0x2e, + 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, + 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x69, 0x0a, + 0x14, 0x55, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x27, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, + 0x36, 0x2e, 0x55, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, + 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x28, + 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x55, 0x70, 0x67, 0x72, 0x61, + 0x64, 0x65, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x2e, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x60, 0x0a, 0x11, 0x43, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x75, 0x72, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, 0x24, 0x2e, + 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x75, 0x72, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x25, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, + 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x65, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, + 0x72, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x51, 0x0a, 0x0c, 0x52, 0x65, + 0x61, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x1f, 0x2e, 0x74, 0x66, 0x70, + 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x52, 0x65, 0x61, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, + 0x72, 0x63, 0x65, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x20, 0x2e, 0x74, 0x66, + 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x52, 0x65, 0x61, 0x64, 0x52, 0x65, 0x73, 0x6f, + 0x75, 0x72, 0x63, 0x65, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x63, 0x0a, + 0x12, 0x50, 0x6c, 0x61, 0x6e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, + 0x6e, 0x67, 0x65, 0x12, 0x25, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, + 0x50, 0x6c, 0x61, 0x6e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, + 0x67, 0x65, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x26, 0x2e, 0x74, 0x66, 0x70, + 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x50, 0x6c, 0x61, 0x6e, 0x52, 0x65, 0x73, 0x6f, 0x75, + 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x66, 0x0a, 0x13, 0x41, 0x70, 0x70, 0x6c, 0x79, 0x52, 0x65, 0x73, 0x6f, 0x75, + 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x26, 0x2e, 0x74, 0x66, 0x70, 0x6c, + 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x41, 0x70, 0x70, 0x6c, 0x79, 0x52, 0x65, 0x73, 0x6f, 0x75, + 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x27, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x41, 0x70, + 0x70, 0x6c, 0x79, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, + 0x65, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x66, 0x0a, 0x13, 0x49, 0x6d, + 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, + 0x65, 0x12, 0x26, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x49, 0x6d, + 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, + 0x65, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x74, 0x66, 0x70, 0x6c, + 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x73, 0x6f, + 0x75, 0x72, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x57, 0x0a, 0x0e, 0x52, 0x65, 0x61, 0x64, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, + 0x75, 0x72, 0x63, 0x65, 0x12, 0x21, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, + 0x2e, 0x52, 0x65, 0x61, 0x64, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x22, 0x2e, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, + 0x69, 0x6e, 0x36, 0x2e, 0x52, 0x65, 0x61, 0x64, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x51, 0x0a, 0x0c, 0x53, + 0x74, 0x6f, 0x70, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, 0x1f, 0x2e, 0x74, 0x66, + 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x74, 0x6f, 0x70, 0x50, 0x72, 0x6f, 0x76, + 0x69, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x20, 0x2e, 0x74, + 0x66, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x36, 0x2e, 0x53, 0x74, 0x6f, 0x70, 0x50, 0x72, 0x6f, + 0x76, 0x69, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x33, + 0x5a, 0x31, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, + 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x74, 0x65, 0x72, 0x72, 0x61, 0x66, 0x6f, 0x72, 0x6d, + 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x74, 0x66, 0x70, 0x6c, 0x75, 0x67, + 0x69, 0x6e, 0x36, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6.proto b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6.proto index 9986f780ac1c..da5e58eafe6d 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6.proto +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6.proto @@ -1,6 +1,6 @@ -// Terraform Plugin RPC protocol version 6.0 +// Terraform Plugin RPC protocol version 6.2 // -// This file defines version 6.0 of the RPC protocol. To implement a plugin +// This file defines version 6.2 of the RPC protocol. To implement a plugin // against this protocol, copy this definition into your own codebase and // use protoc to generate stubs for your target language. // @@ -128,13 +128,16 @@ message Schema { repeated Attribute attributes = 1; NestingMode nesting = 3; - int64 min_items = 4; - int64 max_items = 5; + + // MinItems and MaxItems were never used in the protocol, and have no + // effect on validation. + int64 min_items = 4 [deprecated = true]; + int64 max_items = 5 [deprecated = true]; } // The version of the schema. // Schemas are versioned, so that providers can upgrade a saved resource - // state when the schema is changed. + // state when the schema is changed. int64 version = 1; // Block is the top level configuration block for this schema. @@ -262,15 +265,28 @@ message PlanResourceChange { DynamicValue prior_state = 2; DynamicValue proposed_new_state = 3; DynamicValue config = 4; - bytes prior_private = 5; + bytes prior_private = 5; DynamicValue provider_meta = 6; } message Response { DynamicValue planned_state = 1; repeated AttributePath requires_replace = 2; - bytes planned_private = 3; + bytes planned_private = 3; repeated Diagnostic diagnostics = 4; + + // This may be set only by the helper/schema "SDK" in the main Terraform + // repository, to request that Terraform Core >=0.12 permit additional + // inconsistencies that can result from the legacy SDK type system + // and its imprecise mapping to the >=0.12 type system. + // The change in behavior implied by this flag makes sense only for the + // specific details of the legacy SDK type system, and are not a general + // mechanism to avoid proper type handling in providers. + // + // ==== DO NOT USE THIS ==== + // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== + // ==== DO NOT USE THIS ==== + bool legacy_type_system = 5; } } @@ -280,13 +296,26 @@ message ApplyResourceChange { DynamicValue prior_state = 2; DynamicValue planned_state = 3; DynamicValue config = 4; - bytes planned_private = 5; + bytes planned_private = 5; DynamicValue provider_meta = 6; } message Response { DynamicValue new_state = 1; - bytes private = 2; + bytes private = 2; repeated Diagnostic diagnostics = 3; + + // This may be set only by the helper/schema "SDK" in the main Terraform + // repository, to request that Terraform Core >=0.12 permit additional + // inconsistencies that can result from the legacy SDK type system + // and its imprecise mapping to the >=0.12 type system. + // The change in behavior implied by this flag makes sense only for the + // specific details of the legacy SDK type system, and are not a general + // mechanism to avoid proper type handling in providers. + // + // ==== DO NOT USE THIS ==== + // ==== THIS MUST BE LEFT UNSET IN ALL OTHER SDKS ==== + // ==== DO NOT USE THIS ==== + bool legacy_type_system = 4; } } @@ -318,4 +347,4 @@ message ReadDataSource { DynamicValue state = 1; repeated Diagnostic diagnostics = 2; } -} \ No newline at end of file +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6_grpc.pb.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6_grpc.pb.go index 957e9d239330..a22d32dc9ed4 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6_grpc.pb.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/tfplugin6_grpc.pb.go @@ -1,4 +1,8 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.2.0 +// - protoc v3.19.4 +// source: tfplugin6.proto package tfplugin6 diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto/resource.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto/resource.go index e86988849a58..bb09681850f4 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto/resource.go @@ -101,7 +101,8 @@ func PlanResourceChange_Request(in *tfprotov6.PlanResourceChangeRequest) (*tfplu func PlanResourceChange_Response(in *tfprotov6.PlanResourceChangeResponse) (*tfplugin6.PlanResourceChange_Response, error) { resp := &tfplugin6.PlanResourceChange_Response{ - PlannedPrivate: in.PlannedPrivate, + PlannedPrivate: in.PlannedPrivate, + LegacyTypeSystem: in.UnsafeToUseLegacyTypeSystem, //nolint:staticcheck } requiresReplace, err := AttributePaths(in.RequiresReplace) if err != nil { @@ -141,7 +142,8 @@ func ApplyResourceChange_Request(in *tfprotov6.ApplyResourceChangeRequest) (*tfp func ApplyResourceChange_Response(in *tfprotov6.ApplyResourceChangeResponse) (*tfplugin6.ApplyResourceChange_Response, error) { resp := &tfplugin6.ApplyResourceChange_Response{ - Private: in.Private, + Private: in.Private, + LegacyTypeSystem: in.UnsafeToUseLegacyTypeSystem, //nolint:staticcheck } diags, err := Diagnostics(in.Diagnostics) if err != nil { diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto/schema.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto/schema.go index f9f721a15e35..f3dfcb97d59b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto/schema.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto/schema.go @@ -127,9 +127,7 @@ func Schema_Object_NestingMode(in tfprotov6.SchemaObjectNestingMode) tfplugin6.S func Schema_Object(in *tfprotov6.SchemaObject) (*tfplugin6.Schema_Object, error) { resp := &tfplugin6.Schema_Object{ - Nesting: Schema_Object_NestingMode(in.Nesting), - MinItems: in.MinItems, - MaxItems: in.MaxItems, + Nesting: Schema_Object_NestingMode(in.Nesting), } attrs, err := Schema_Attributes(in.Attributes) if err != nil { diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/resource.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/resource.go index 3250f195486b..2768bb526e84 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/resource.go @@ -125,6 +125,9 @@ type ReadResourceRequest struct { // Private is any provider-defined private state stored with the // resource. It is used for keeping state with the resource that is not // meant to be included when calculating diffs. + // + // To ensure private state data is preserved, copy any necessary data to + // the ReadResourceResponse type Private field. Private []byte // ProviderMeta supplies the provider metadata configuration for the @@ -212,6 +215,9 @@ type PlanResourceChangeRequest struct { // PriorPrivate is any provider-defined private state stored with the // resource. It is used for keeping state with the resource that is not // meant to be included when calculating diffs. + // + // To ensure private state data is preserved, copy any necessary data to + // the PlanResourceChangeResponse type PlannedPrivate field. PriorPrivate []byte // ProviderMeta supplies the provider metadata configuration for the @@ -280,6 +286,10 @@ type PlanResourceChangeResponse struct { // like sent with requests for this resource. This state will be // associated with the resource, but will not be considered when // calculating diffs. + // + // This private state data will be sent in the ApplyResourceChange RPC, in + // relation to the types of this package, the ApplyResourceChangeRequest + // type PlannedPrivate field. PlannedPrivate []byte // Diagnostics report errors or warnings related to determining the @@ -341,6 +351,13 @@ type ApplyResourceChangeRequest struct { // PlannedPrivate is any provider-defined private state stored with the // resource. It is used for keeping state with the resource that is not // meant to be included when calculating diffs. + // + // This private state data is sourced from the PlanResourceChange RPC, in + // relation to the types in this package, the PlanResourceChangeResponse + // type PlannedPrivate field. + // + // To ensure private state data is preserved, copy any necessary data to + // the ApplyResourceChangeResponse type Private field. PlannedPrivate []byte // ProviderMeta supplies the provider metadata configuration for the diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/schema.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/schema.go index a7e139fed255..c17e2cceebbb 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/schema.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/schema.go @@ -96,6 +96,19 @@ type Schema struct { Block *SchemaBlock } +// ValueType returns the tftypes.Type for a Schema. +// +// If Schema is missing, an empty Object is returned. +func (s *Schema) ValueType() tftypes.Type { + if s == nil { + return tftypes.Object{ + AttributeTypes: map[string]tftypes.Type{}, + } + } + + return s.Block.ValueType() +} + // SchemaBlock represents a block in a schema. Blocks are how Terraform creates // groupings of attributes. In configurations, they don't use the equals sign // and use dynamic instead of list comprehensions. @@ -133,6 +146,51 @@ type SchemaBlock struct { Deprecated bool } +// ValueType returns the tftypes.Type for a SchemaBlock. +// +// If SchemaBlock is missing, an empty Object is returned. +func (s *SchemaBlock) ValueType() tftypes.Type { + if s == nil { + return tftypes.Object{ + AttributeTypes: map[string]tftypes.Type{}, + } + } + + attributeTypes := map[string]tftypes.Type{} + + for _, attribute := range s.Attributes { + if attribute == nil { + continue + } + + attributeType := attribute.ValueType() + + if attributeType == nil { + continue + } + + attributeTypes[attribute.Name] = attributeType + } + + for _, block := range s.BlockTypes { + if block == nil { + continue + } + + blockType := block.ValueType() + + if blockType == nil { + continue + } + + attributeTypes[block.TypeName] = blockType + } + + return tftypes.Object{ + AttributeTypes: attributeTypes, + } +} + // SchemaAttribute represents a single attribute within a schema block. // Attributes are the fields users can set in configuration using the equals // sign, can assign to variables, can interpolate, and can use list @@ -194,6 +252,22 @@ type SchemaAttribute struct { Deprecated bool } +// ValueType returns the tftypes.Type for a SchemaAttribute. +// +// If SchemaAttribute is missing, nil is returned. +func (s *SchemaAttribute) ValueType() tftypes.Type { + if s == nil { + return nil + } + + // It is not valid to set both NestedType and Type. + if s.NestedType != nil { + return s.NestedType.ValueType() + } + + return s.Type +} + // SchemaNestedBlock is a nested block within another block. See SchemaBlock // for more information on blocks. type SchemaNestedBlock struct { @@ -230,6 +304,39 @@ type SchemaNestedBlock struct { MaxItems int64 } +// ValueType returns the tftypes.Type for a SchemaNestedBlock. +// +// If SchemaNestedBlock is missing or the Nesting mode is invalid, nil is +// returned. +func (s *SchemaNestedBlock) ValueType() tftypes.Type { + if s == nil { + return nil + } + + blockType := s.Block.ValueType() + + switch s.Nesting { + case SchemaNestedBlockNestingModeGroup: + return blockType + case SchemaNestedBlockNestingModeList: + return tftypes.List{ + ElementType: blockType, + } + case SchemaNestedBlockNestingModeMap: + return tftypes.Map{ + ElementType: blockType, + } + case SchemaNestedBlockNestingModeSet: + return tftypes.Set{ + ElementType: blockType, + } + case SchemaNestedBlockNestingModeSingle: + return blockType + default: + return nil + } +} + // SchemaNestedBlockNestingMode indicates the nesting mode for // SchemaNestedBlocks. The nesting mode determines the number of instances of // the block allowed, how many labels the block expects, and the data structure @@ -260,14 +367,54 @@ type SchemaObject struct { Attributes []*SchemaAttribute Nesting SchemaObjectNestingMode +} - // MinItems is the minimum number of instances of this type that a - // user must specify or Terraform will return an error. - MinItems int64 +// ValueType returns the tftypes.Type for a SchemaObject. +// +// If SchemaObject is missing or the Nesting mode is invalid, nil is returned. +func (s *SchemaObject) ValueType() tftypes.Type { + if s == nil { + return nil + } - // MaxItems is the maximum number of instances of this type that a - // user may specify before Terraform returns an error. - MaxItems int64 + attributeTypes := map[string]tftypes.Type{} + + for _, attribute := range s.Attributes { + if attribute == nil { + continue + } + + attributeType := attribute.ValueType() + + if attributeType == nil { + continue + } + + attributeTypes[attribute.Name] = attributeType + } + + objectType := tftypes.Object{ + AttributeTypes: attributeTypes, + } + + switch s.Nesting { + case SchemaObjectNestingModeList: + return tftypes.List{ + ElementType: objectType, + } + case SchemaObjectNestingModeMap: + return tftypes.Map{ + ElementType: objectType, + } + case SchemaObjectNestingModeSet: + return tftypes.Set{ + ElementType: objectType, + } + case SchemaObjectNestingModeSingle: + return objectType + default: + return nil + } } // SchemaObjectNestingMode indicates the nesting mode for diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/tf6server/server.go b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/tf6server/server.go index 4fd0b6eba525..d4369e21fc59 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/tf6server/server.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/tf6server/server.go @@ -2,51 +2,83 @@ package tf6server import ( "context" + "encoding/json" "errors" - "log" + "fmt" + "os" + "os/signal" "regexp" + "runtime" "strings" "sync" + "time" + "github.com/hashicorp/terraform-plugin-go/internal/logging" "github.com/hashicorp/terraform-plugin-go/tfprotov6" "github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto" + "github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging" "github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6" "github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto" + "google.golang.org/grpc" "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-plugin" - "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-log/tfsdklog" - tfaddr "github.com/hashicorp/terraform-registry-address" testing "github.com/mitchellh/go-testing-interface" ) -const tflogSubsystemName = "proto" - -// Global logging keys attached to all requests. -// -// Practitioners or tooling reading logs may be depending on these keys, so be -// conscious of that when changing them. const ( - // A unique ID for the RPC request - logKeyRequestID = "tf_req_id" - - // The full address of the provider, such as - // registry.terraform.io/hashicorp/random - logKeyProviderAddress = "tf_provider_addr" - - // The RPC being run, such as "ApplyResourceChange" - logKeyRPC = "tf_rpc" + // protocolVersionMajor represents the major version number of the protocol + // being served. This is used during the plugin handshake to validate the + // server and client are compatible. + // + // In the future, it may be possible to include this information directly + // in the protocol buffers rather than recreating a constant here. + protocolVersionMajor uint = 6 + + // protocolVersionMinor represents the minor version number of the protocol + // being served. Backwards compatible additions are possible in the + // protocol definitions, which is when this may be increased. While it is + // not used in plugin negotiation, it can be helpful to include this value + // for debugging, such as in logs. + // + // In the future, it may be possible to include this information directly + // in the protocol buffers rather than recreating a constant here. + protocolVersionMinor uint = 0 +) - // The type of resource being operated on, such as "random_pet" - logKeyResourceType = "tf_resource_type" +// protocolVersion represents the combined major and minor version numbers of +// the protocol being served. +var protocolVersion string = fmt.Sprintf("%d.%d", protocolVersionMajor, protocolVersionMinor) - // The type of data source being operated on, such as "archive_file" - logKeyDataSourceType = "tf_data_source_type" +const ( + // envTfReattachProviders is the environment variable used by Terraform CLI + // to directly connect to already running provider processes, such as those + // being inspected by debugging processes. When connecting to providers in + // this manner, Terraform CLI disables certain plugin handshake checks and + // will not stop the provider process. + envTfReattachProviders = "TF_REATTACH_PROVIDERS" +) - // The protocol version being used, as a string, such as "6" - logKeyProtocolVersion = "tf_proto_version" +const ( + // grpcMaxMessageSize is the maximum gRPC send and receive message sizes + // for the server. + // + // This 256MB value is arbitrarily raised from the default message sizes of + // 4MB to account for advanced use cases, but arbitrarily lowered from + // MaxInt32 (or similar) to prevent incorrect server implementations from + // exhausting resources in common execution environments. Receiving a gRPC + // message size error is preferable for troubleshooting over determining + // why an execution environment may have terminated the process via its + // memory management processes, such as oom-killer on Linux. + // + // This value is kept as constant over allowing server configurability + // since there are many factors that influence message size, such as + // Terraform configuration and state data. If larger message size use + // cases appear, other gRPC options should be explored, such as + // implementing streaming RPCs and messages. + grpcMaxMessageSize = 256 << 20 ) // ServeOpt is an interface for defining options that can be passed to the @@ -65,6 +97,10 @@ type ServeConfig struct { debugCh chan *plugin.ReattachConfig debugCloseCh chan struct{} + managedDebug bool + managedDebugReattachConfigTimeout time.Duration + managedDebugStopSignals []os.Signal + disableLogInitStderr bool disableLogLocation bool useLoggingSink testing.T @@ -79,8 +115,17 @@ func (s serveConfigFunc) ApplyServeOpt(in *ServeConfig) error { // WithDebug returns a ServeOpt that will set the server into debug mode, using // the passed options to populate the go-plugin ServeTestConfig. +// +// This is an advanced ServeOpt that assumes the caller will fully manage the +// reattach configuration and server lifecycle. Refer to WithManagedDebug for a +// ServeOpt that handles common use cases, such as implementing provider main +// functions. func WithDebug(ctx context.Context, config chan *plugin.ReattachConfig, closeCh chan struct{}) ServeOpt { return serveConfigFunc(func(in *ServeConfig) error { + if in.managedDebug { + return errors.New("cannot set both WithDebug and WithManagedDebug") + } + in.debugCtx = ctx in.debugCh = config in.debugCloseCh = closeCh @@ -88,6 +133,47 @@ func WithDebug(ctx context.Context, config chan *plugin.ReattachConfig, closeCh }) } +// WithManagedDebug returns a ServeOpt that will start the server in debug +// mode, managing the reattach configuration handling and server lifecycle. +// Reattach configuration is output to stdout with human friendly instructions. +// By default, the server can be stopped with os.Interrupt (SIGINT; ctrl-c). +// +// Refer to the optional WithManagedDebugStopSignals and +// WithManagedDebugReattachConfigTimeout ServeOpt for additional configuration. +// +// The reattach configuration output of this handling is not protected by +// compatibility guarantees. Use the WithDebug ServeOpt for advanced use cases. +func WithManagedDebug() ServeOpt { + return serveConfigFunc(func(in *ServeConfig) error { + if in.debugCh != nil { + return errors.New("cannot set both WithDebug and WithManagedDebug") + } + + in.managedDebug = true + return nil + }) +} + +// WithManagedDebugStopSignals returns a ServeOpt that will set the stop signals for a +// debug managed process (WithManagedDebug). When not configured, os.Interrupt +// (SIGINT; Ctrl-c) will stop the process. +func WithManagedDebugStopSignals(signals []os.Signal) ServeOpt { + return serveConfigFunc(func(in *ServeConfig) error { + in.managedDebugStopSignals = signals + return nil + }) +} + +// WithManagedDebugReattachConfigTimeout returns a ServeOpt that will set the timeout +// for a debug managed process to start and return its reattach configuration. +// When not configured, 2 seconds is the default. +func WithManagedDebugReattachConfigTimeout(timeout time.Duration) ServeOpt { + return serveConfigFunc(func(in *ServeConfig) error { + in.managedDebugReattachConfigTimeout = timeout + return nil + }) +} + // WithGoPluginLogger returns a ServeOpt that will set the logger that // go-plugin should use to log messages. func WithGoPluginLogger(logger hclog.Logger) ServeOpt { @@ -152,16 +238,22 @@ func WithLogEnvVarName(name string) ServeOpt { // modify the logger that go-plugin is using, ServeOpts can be specified to // support that. func Serve(name string, serverFactory func() tfprotov6.ProviderServer, opts ...ServeOpt) error { - var conf ServeConfig + // Defaults + conf := ServeConfig{ + managedDebugReattachConfigTimeout: 2 * time.Second, + managedDebugStopSignals: []os.Signal{os.Interrupt}, + } + for _, opt := range opts { err := opt.ApplyServeOpt(&conf) if err != nil { return err } } + serveConfig := &plugin.ServeConfig{ HandshakeConfig: plugin.HandshakeConfig{ - ProtocolVersion: 6, + ProtocolVersion: protocolVersionMajor, MagicCookieKey: "TF_PLUGIN_MAGIC_COOKIE", MagicCookieValue: "d602bf8f470bc67ca7faa0386276bbdd4330efaf76d1a219cb4d6991ca9872b2", }, @@ -172,11 +264,42 @@ func Serve(name string, serverFactory func() tfprotov6.ProviderServer, opts ...S Name: name, }, }, - GRPCServer: plugin.DefaultGRPCServer, + GRPCServer: func(opts []grpc.ServerOption) *grpc.Server { + opts = append(opts, grpc.MaxRecvMsgSize(grpcMaxMessageSize)) + opts = append(opts, grpc.MaxSendMsgSize(grpcMaxMessageSize)) + + return grpc.NewServer(opts...) + }, } + if conf.logger != nil { serveConfig.Logger = conf.logger } + + if conf.managedDebug { + ctx, cancel := context.WithCancel(context.Background()) + signalCh := make(chan os.Signal, len(conf.managedDebugStopSignals)) + + signal.Notify(signalCh, conf.managedDebugStopSignals...) + + defer func() { + signal.Stop(signalCh) + cancel() + }() + + go func() { + select { + case <-signalCh: + cancel() + case <-ctx.Done(): + } + }() + + conf.debugCh = make(chan *plugin.ReattachConfig) + conf.debugCloseCh = make(chan struct{}) + conf.debugCtx = ctx + } + if conf.debugCh != nil { serveConfig.Test = &plugin.ServeTestConfig{ Context: conf.debugCtx, @@ -184,7 +307,78 @@ func Serve(name string, serverFactory func() tfprotov6.ProviderServer, opts ...S CloseCh: conf.debugCloseCh, } } - plugin.Serve(serveConfig) + + if !conf.managedDebug { + plugin.Serve(serveConfig) + return nil + } + + go plugin.Serve(serveConfig) + + var pluginReattachConfig *plugin.ReattachConfig + + select { + case pluginReattachConfig = <-conf.debugCh: + case <-time.After(conf.managedDebugReattachConfigTimeout): + return errors.New("timeout waiting on reattach configuration") + } + + if pluginReattachConfig == nil { + return errors.New("nil reattach configuration received") + } + + // Duplicate implementation is required because the go-plugin + // ReattachConfig.Addr implementation is not friendly for JSON encoding + // and to avoid importing terraform-exec. + type reattachConfigAddr struct { + Network string + String string + } + + type reattachConfig struct { + Protocol string + ProtocolVersion int + Pid int + Test bool + Addr reattachConfigAddr + } + + reattachBytes, err := json.Marshal(map[string]reattachConfig{ + name: { + Protocol: string(pluginReattachConfig.Protocol), + ProtocolVersion: pluginReattachConfig.ProtocolVersion, + Pid: pluginReattachConfig.Pid, + Test: pluginReattachConfig.Test, + Addr: reattachConfigAddr{ + Network: pluginReattachConfig.Addr.Network(), + String: pluginReattachConfig.Addr.String(), + }, + }, + }) + + if err != nil { + return fmt.Errorf("Error building reattach string: %w", err) + } + + reattachStr := string(reattachBytes) + + // This is currently intended to be executed via provider main function and + // human friendly, so output directly to stdout. + fmt.Printf("Provider started. To attach Terraform CLI, set the %s environment variable with the following:\n\n", envTfReattachProviders) + + switch runtime.GOOS { + case "windows": + fmt.Printf("\tCommand Prompt:\tset \"%s=%s\"\n", envTfReattachProviders, reattachStr) + fmt.Printf("\tPowerShell:\t$env:%s='%s'\n", envTfReattachProviders, strings.ReplaceAll(reattachStr, `'`, `''`)) + default: + fmt.Printf("\t%s='%s'\n", envTfReattachProviders, strings.ReplaceAll(reattachStr, `'`, `'"'"'`)) + } + + fmt.Println("") + + // Wait for the server to be done. + <-conf.debugCloseCh + return nil } @@ -200,6 +394,13 @@ type server struct { useTFLogSink bool testHandle testing.T name string + + // protocolDataDir is a directory to store raw protocol data files for + // debugging purposes. + protocolDataDir string + + // protocolVersion is the protocol version for the server. + protocolVersion string } func mergeStop(ctx context.Context, cancel context.CancelFunc, stopCh chan struct{}) { @@ -232,50 +433,11 @@ func (s *server) loggingContext(ctx context.Context) context.Context { ctx = tfsdklog.RegisterTestSink(ctx, s.testHandle) } - // generate a request ID - reqID, err := uuid.GenerateUUID() - if err != nil { - reqID = "unable to assign request ID: " + err.Error() - } - - // set up the logger SDK loggers are derived from - ctx = tfsdklog.NewRootSDKLogger(ctx, append(tfsdklog.Options{ - tfsdklog.WithLevelFromEnv("TF_LOG_SDK"), - }, s.tflogSDKOpts...)...) - ctx = tfsdklog.With(ctx, logKeyRequestID, reqID) - ctx = tfsdklog.With(ctx, logKeyProviderAddress, s.name) - - // set up our protocol-level subsystem logger - ctx = tfsdklog.NewSubsystem(ctx, tflogSubsystemName, append(tfsdklog.Options{ - tfsdklog.WithLevelFromEnv("TF_LOG_SDK_PROTO"), - }, s.tflogSDKOpts...)...) - ctx = tfsdklog.SubsystemWith(ctx, tflogSubsystemName, logKeyProtocolVersion, "6") - - // set up the provider logger - ctx = tfsdklog.NewRootProviderLogger(ctx, s.tflogOpts...) - ctx = tflog.With(ctx, logKeyRequestID, reqID) - ctx = tflog.With(ctx, logKeyProviderAddress, s.name) - return ctx -} - -func rpcLoggingContext(ctx context.Context, rpc string) context.Context { - ctx = tfsdklog.With(ctx, logKeyRPC, rpc) - ctx = tfsdklog.SubsystemWith(ctx, tflogSubsystemName, logKeyRPC, rpc) - ctx = tflog.With(ctx, logKeyRPC, rpc) - return ctx -} + ctx = logging.InitContext(ctx, s.tflogSDKOpts, s.tflogOpts) + ctx = logging.RequestIdContext(ctx) + ctx = logging.ProviderAddressContext(ctx, s.name) + ctx = logging.ProtocolVersionContext(ctx, s.protocolVersion) -func resourceLoggingContext(ctx context.Context, resource string) context.Context { - ctx = tfsdklog.With(ctx, logKeyResourceType, resource) - ctx = tfsdklog.SubsystemWith(ctx, tflogSubsystemName, logKeyResourceType, resource) - ctx = tflog.With(ctx, logKeyResourceType, resource) - return ctx -} - -func dataSourceLoggingContext(ctx context.Context, dataSource string) context.Context { - ctx = tfsdklog.With(ctx, logKeyDataSourceType, dataSource) - ctx = tfsdklog.SubsystemWith(ctx, tflogSubsystemName, logKeyDataSourceType, dataSource) - ctx = tflog.With(ctx, logKeyDataSourceType, dataSource) return ctx } @@ -303,97 +465,101 @@ func New(name string, serve tfprotov6.ProviderServer, opts ...ServeOpt) tfplugin } envVar := conf.envVar if envVar == "" { - addr, err := tfaddr.ParseRawProviderSourceString(name) - if err != nil { - log.Printf("[ERROR] Error parsing provider name %q: %s", name, err) - } else { - envVar = addr.Type - } + envVar = logging.ProviderLoggerName(name) } - envVar = strings.ReplaceAll(envVar, "-", "_") if envVar != "" { - options = append(options, tfsdklog.WithLogName(envVar), tflog.WithLevelFromEnv("TF_LOG_PROVIDER", envVar)) + options = append(options, tfsdklog.WithLogName(envVar), tflog.WithLevelFromEnv(logging.EnvTfLogProvider, envVar)) } return &server{ - downstream: serve, - stopCh: make(chan struct{}), - tflogOpts: options, - tflogSDKOpts: sdkOptions, - name: name, - useTFLogSink: conf.useLoggingSink != nil, - testHandle: conf.useLoggingSink, + downstream: serve, + stopCh: make(chan struct{}), + tflogOpts: options, + tflogSDKOpts: sdkOptions, + name: name, + useTFLogSink: conf.useLoggingSink != nil, + testHandle: conf.useLoggingSink, + protocolDataDir: os.Getenv(logging.EnvTfLogSdkProtoDataDir), + protocolVersion: protocolVersion, } } func (s *server) GetProviderSchema(ctx context.Context, req *tfplugin6.GetProviderSchema_Request) (*tfplugin6.GetProviderSchema_Response, error) { - ctx = rpcLoggingContext(s.loggingContext(ctx), "GetProviderSchema") + rpc := "GetProviderSchema" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.GetProviderSchemaRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.GetProviderSchema(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) ret, err := toproto.GetProviderSchema_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ConfigureProvider(ctx context.Context, req *tfplugin6.ConfigureProvider_Request) (*tfplugin6.ConfigureProvider_Response, error) { - ctx = rpcLoggingContext(s.loggingContext(ctx), "ConfigureProvider") + rpc := "ConfigureProvider" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ConfigureProviderRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ConfigureProvider(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) ret, err := toproto.Configure_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ValidateProviderConfig(ctx context.Context, req *tfplugin6.ValidateProviderConfig_Request) (*tfplugin6.ValidateProviderConfig_Response, error) { - ctx = rpcLoggingContext(s.loggingContext(ctx), "ValidateProviderConfig") - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + rpc := "ValidateProviderConfig" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ValidateProviderConfigRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ValidateProviderConfig(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) ret, err := toproto.ValidateProviderConfig_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil @@ -413,228 +579,276 @@ func (s *server) stop() { } func (s *server) Stop(ctx context.Context, req *tfplugin6.StopProvider_Request) (*tfplugin6.StopProvider_Response, error) { - ctx = rpcLoggingContext(s.loggingContext(ctx), "Stop") + rpc := "StopProvider" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.StopProviderRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.StopProvider(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Closing all our contexts") + tf6serverlogging.DownstreamResponse(ctx, nil) + logging.ProtocolTrace(ctx, "Closing all our contexts") s.stop() - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Closed all our contexts") + logging.ProtocolTrace(ctx, "Closed all our contexts") ret, err := toproto.Stop_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ValidateDataResourceConfig(ctx context.Context, req *tfplugin6.ValidateDataResourceConfig_Request) (*tfplugin6.ValidateDataResourceConfig_Response, error) { - ctx = dataSourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ValidateDataResourceConfig"), req.TypeName) + rpc := "ValidateDataResourceConfig" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.DataSourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ValidateDataResourceConfigRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ValidateDataResourceConfig(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) ret, err := toproto.ValidateDataResourceConfig_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ReadDataSource(ctx context.Context, req *tfplugin6.ReadDataSource_Request) (*tfplugin6.ReadDataSource_Response, error) { - ctx = dataSourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ReadDataSource"), req.TypeName) + rpc := "ReadDataSource" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.DataSourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ReadDataSourceRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "ProviderMeta", r.ProviderMeta) + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ReadDataSource(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "State", resp.State) ret, err := toproto.ReadDataSource_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ValidateResourceConfig(ctx context.Context, req *tfplugin6.ValidateResourceConfig_Request) (*tfplugin6.ValidateResourceConfig_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ValidateResourceConfig"), req.TypeName) + rpc := "ValidateResourceConfig" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ValidateResourceConfigRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ValidateResourceConfig(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) ret, err := toproto.ValidateResourceConfig_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) UpgradeResourceState(ctx context.Context, req *tfplugin6.UpgradeResourceState_Request) (*tfplugin6.UpgradeResourceState_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "UpgradeResourceState"), req.TypeName) + rpc := "UpgradeResourceState" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.UpgradeResourceStateRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.UpgradeResourceState(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "UpgradedState", resp.UpgradedState) ret, err := toproto.UpgradeResourceState_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ReadResource(ctx context.Context, req *tfplugin6.ReadResource_Request) (*tfplugin6.ReadResource_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ReadResource"), req.TypeName) + rpc := "ReadResource" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ReadResourceRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "CurrentState", r.CurrentState) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "ProviderMeta", r.ProviderMeta) + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ReadResource(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "NewState", resp.NewState) ret, err := toproto.ReadResource_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) PlanResourceChange(ctx context.Context, req *tfplugin6.PlanResourceChange_Request) (*tfplugin6.PlanResourceChange_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "PlanResourceChange"), req.TypeName) + rpc := "PlanResourceChange" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.PlanResourceChangeRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "PriorState", r.PriorState) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "ProposedNewState", r.ProposedNewState) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "ProviderMeta", r.ProviderMeta) + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.PlanResourceChange(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "PlannedState", resp.PlannedState) ret, err := toproto.PlanResourceChange_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ApplyResourceChange(ctx context.Context, req *tfplugin6.ApplyResourceChange_Request) (*tfplugin6.ApplyResourceChange_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ApplyResourceChange"), req.TypeName) + rpc := "ApplyResourceChange" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ApplyResourceChangeRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "PlannedState", r.PlannedState) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Request", "Config", r.Config) + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ApplyResourceChange(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response", "NewState", resp.NewState) ret, err := toproto.ApplyResourceChange_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil } func (s *server) ImportResourceState(ctx context.Context, req *tfplugin6.ImportResourceState_Request) (*tfplugin6.ImportResourceState_Response, error) { - ctx = resourceLoggingContext(rpcLoggingContext(s.loggingContext(ctx), "ImportResourceState"), req.TypeName) + rpc := "ImportResourceState" + ctx = s.loggingContext(ctx) + ctx = logging.RpcContext(ctx, rpc) + ctx = logging.ResourceContext(ctx, req.TypeName) ctx = s.stoppableContext(ctx) - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Received request") - defer tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Served request") + logging.ProtocolTrace(ctx, "Received request") + defer logging.ProtocolTrace(ctx, "Served request") r, err := fromproto.ImportResourceStateRequest(req) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting request from protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting request from protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Calling downstream") + ctx = tf6serverlogging.DownstreamRequest(ctx) resp, err := s.downstream.ImportResourceState(ctx, r) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error from downstream", "error", err) + logging.ProtocolError(ctx, "Error from downstream", map[string]interface{}{logging.KeyError: err}) return nil, err } - tfsdklog.SubsystemTrace(ctx, tflogSubsystemName, "Called downstream") + tf6serverlogging.DownstreamResponse(ctx, resp.Diagnostics) + for _, importedResource := range resp.ImportedResources { + logging.ProtocolData(ctx, s.protocolDataDir, rpc, "Response_ImportedResource", "State", importedResource.State) + } ret, err := toproto.ImportResourceState_Response(resp) if err != nil { - tfsdklog.SubsystemError(ctx, tflogSubsystemName, "Error converting response to protobuf", "error", err) + logging.ProtocolError(ctx, "Error converting response to protobuf", map[string]interface{}{logging.KeyError: err}) return nil, err } return ret, nil diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/attribute_path.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/attribute_path.go index fd91f96a5c91..d6108d4ab335 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/attribute_path.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/attribute_path.go @@ -284,9 +284,9 @@ type AttributePathStepper interface { ApplyTerraform5AttributePathStep(AttributePathStep) (interface{}, error) } -// WalkAttributePath will return the value that `path` is pointing to, using -// `in` as the root. If an error is returned, the AttributePath returned will -// indicate the steps that remained to be applied when the error was +// WalkAttributePath will return the Type or Value that `path` is pointing to, +// using `in` as the root. If an error is returned, the AttributePath returned +// will indicate the steps that remained to be applied when the error was // encountered. // // map[string]interface{} and []interface{} types have built-in support. Other diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/diff.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/diff.go index dc89026c53b4..328b1adf67cb 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/diff.go @@ -283,6 +283,9 @@ func (val1 Value) Diff(val2 Value) ([]ValueDiff, error) { // if we have the same keys, we can just let recursion // from the walk check the sub-values match return true, nil + case value1.Type().Is(DynamicPseudoType): + // Let recursion from the walk check the sub-values match + return true, nil } return false, fmt.Errorf("unexpected type %v in Diff at %s", value1.Type(), path) }) diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/list.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/list.go index a633ed1e048b..a0bc2f370095 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/list.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/list.go @@ -15,6 +15,23 @@ type List struct { _ []struct{} } +// ApplyTerraform5AttributePathStep applies an AttributePathStep to a List, +// returning the Type found at that AttributePath within the List. If the +// AttributePathStep cannot be applied to the List, an ErrInvalidStep error +// will be returned. +func (l List) ApplyTerraform5AttributePathStep(step AttributePathStep) (interface{}, error) { + switch s := step.(type) { + case ElementKeyInt: + if int64(s) < 0 { + return nil, ErrInvalidStep + } + + return l.ElementType, nil + default: + return nil, ErrInvalidStep + } +} + // Equal returns true if the two Lists are exactly equal. Unlike Is, passing in // a List with no ElementType will always return false. func (l List) Equal(o Type) bool { @@ -70,9 +87,7 @@ func valueFromList(typ Type, in interface{}) (Value, error) { case []Value: var valType Type for pos, v := range value { - if v.Type().Is(DynamicPseudoType) && v.IsKnown() { - return Value{}, NewAttributePath().WithElementKeyInt(pos).NewErrorf("invalid value %s for %s", v, v.Type()) - } else if !v.Type().Is(DynamicPseudoType) && !v.Type().UsableAs(typ) { + if !v.Type().UsableAs(typ) { return Value{}, NewAttributePath().WithElementKeyInt(pos).NewErrorf("can't use %s as %s", v.Type(), typ) } if valType == nil { diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/map.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/map.go index 9188df88f4d6..7c1e7d05ae0a 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/map.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/map.go @@ -16,6 +16,19 @@ type Map struct { _ []struct{} } +// ApplyTerraform5AttributePathStep applies an AttributePathStep to a Map, +// returning the Type found at that AttributePath within the Map. If the +// AttributePathStep cannot be applied to the Map, an ErrInvalidStep error +// will be returned. +func (m Map) ApplyTerraform5AttributePathStep(step AttributePathStep) (interface{}, error) { + switch step.(type) { + case ElementKeyString: + return m.ElementType, nil + default: + return nil, ErrInvalidStep + } +} + // Equal returns true if the two Maps are exactly equal. Unlike Is, passing in // a Map with no ElementType will always return false. func (m Map) Equal(o Type) bool { @@ -89,9 +102,7 @@ func valueFromMap(typ Type, in interface{}) (Value, error) { var elType Type for _, k := range keys { v := value[k] - if v.Type().Is(DynamicPseudoType) && v.IsKnown() { - return Value{}, NewAttributePath().WithElementKeyString(k).NewErrorf("invalid value %s for %s", v, v.Type()) - } else if !v.Type().Is(DynamicPseudoType) && !v.Type().UsableAs(typ) { + if !v.Type().UsableAs(typ) { return Value{}, NewAttributePath().WithElementKeyString(k).NewErrorf("can't use %s as %s", v.Type(), typ) } if elType == nil { diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/object.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/object.go index 2c9dde76d081..ce2bf1325c63 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/object.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/object.go @@ -24,6 +24,12 @@ type Object struct { // are considered part of the type signature, and their absence means a // value is no longer of that type. // + // OptionalAttributes is only valid when declaring a type constraint + // (e.g. Schema) and should not be used as part of a Type when creating + // a Value (e.g. NewValue()). When creating a Value, all OptionalAttributes + // must still be defined in the Object by setting each attribute to a null + // or known value for its attribute type. + // // The key of OptionalAttributes should be the name of the attribute // that is optional. The value should be an empty struct, used only to // indicate presence. @@ -38,6 +44,29 @@ type Object struct { _ []struct{} } +// ApplyTerraform5AttributePathStep applies an AttributePathStep to an Object, +// returning the Type found at that AttributePath within the Object. If the +// AttributePathStep cannot be applied to the Object, an ErrInvalidStep error +// will be returned. +func (o Object) ApplyTerraform5AttributePathStep(step AttributePathStep) (interface{}, error) { + switch s := step.(type) { + case AttributeName: + if len(o.AttributeTypes) == 0 { + return nil, ErrInvalidStep + } + + attrType, ok := o.AttributeTypes[string(s)] + + if !ok { + return nil, ErrInvalidStep + } + + return attrType, nil + default: + return nil, ErrInvalidStep + } +} + // Equal returns true if the two Objects are exactly equal. Unlike Is, passing // in an Object with no AttributeTypes will always return false. func (o Object) Equal(other Type) bool { @@ -183,9 +212,7 @@ func valueFromObject(types map[string]Type, optionalAttrs map[string]struct{}, i if v.Type() == nil { return Value{}, NewAttributePath().WithAttributeName(k).NewErrorf("missing value type") } - if v.Type().Is(DynamicPseudoType) && v.IsKnown() && !v.IsNull() { - return Value{}, NewAttributePath().WithAttributeName(k).NewErrorf("invalid value %s for %s", v, v.Type()) - } else if !v.Type().Is(DynamicPseudoType) && !v.Type().UsableAs(typ) { + if !v.Type().UsableAs(typ) { return Value{}, NewAttributePath().WithAttributeName(k).NewErrorf("can't use %s as %s", v.Type(), typ) } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/primitive.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/primitive.go index ff0f14e60808..0349f4145531 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/primitive.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/primitive.go @@ -37,6 +37,12 @@ type primitive struct { _ []struct{} } +// ApplyTerraform5AttributePathStep always returns an ErrInvalidStep error +// as it is invalid to step into a primitive. +func (p primitive) ApplyTerraform5AttributePathStep(step AttributePathStep) (interface{}, error) { + return nil, ErrInvalidStep +} + func (p primitive) Equal(o Type) bool { v, ok := o.(primitive) if !ok { @@ -61,7 +67,7 @@ func (p primitive) UsableAs(t Type) bool { } func (p primitive) String() string { - return "tftypes." + string(p.name) + return "tftypes." + p.name } func (p primitive) private() {} @@ -102,7 +108,16 @@ func (p primitive) supportedGoTypes() []string { case Bool.name: return []string{"bool", "*bool"} case DynamicPseudoType.name: - return []string{"nil", "UnknownValue"} + // List/Set is covered by Tuple, Map is covered by Object + possibleTypes := []Type{ + String, Bool, Number, + Tuple{}, Object{}, + } + results := []string{} + for _, t := range possibleTypes { + results = append(results, t.supportedGoTypes()...) + } + return results } panic(fmt.Sprintf("unknown primitive type %q", p.name)) } @@ -346,3 +361,45 @@ func valueFromNumber(in interface{}) (Value, error) { return Value{}, fmt.Errorf("tftypes.NewValue can't use %T as a tftypes.Number; expected types are: %s", in, formattedSupportedGoTypes(Number)) } } + +func valueFromDynamicPseudoType(val interface{}) (Value, error) { + switch val := val.(type) { + case string, *string: + v, err := valueFromString(val) + if err != nil { + return Value{}, err + } + v.typ = DynamicPseudoType + return v, nil + case *big.Float, float64, *float64, int, *int, int8, *int8, int16, *int16, int32, *int32, int64, *int64, uint, *uint, uint8, *uint8, uint16, *uint16, uint32, *uint32, uint64, *uint64: + v, err := valueFromNumber(val) + if err != nil { + return Value{}, err + } + v.typ = DynamicPseudoType + return v, nil + case bool, *bool: + v, err := valueFromBool(val) + if err != nil { + return Value{}, err + } + v.typ = DynamicPseudoType + return v, nil + case map[string]Value: + v, err := valueFromObject(nil, nil, val) + if err != nil { + return Value{}, err + } + v.typ = DynamicPseudoType + return v, nil + case []Value: + v, err := valueFromTuple(nil, val) + if err != nil { + return Value{}, err + } + v.typ = DynamicPseudoType + return v, nil + default: + return Value{}, fmt.Errorf("tftypes.NewValue can't use %T as a tftypes.DynamicPseudoType; expected types are: %s", val, formattedSupportedGoTypes(DynamicPseudoType)) + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/set.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/set.go index 3bd3e8a67e48..00163067ea1c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/set.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/set.go @@ -15,6 +15,19 @@ type Set struct { _ []struct{} } +// ApplyTerraform5AttributePathStep applies an AttributePathStep to a Set, +// returning the Type found at that AttributePath within the Set. If the +// AttributePathStep cannot be applied to the Set, an ErrInvalidStep error +// will be returned. +func (s Set) ApplyTerraform5AttributePathStep(step AttributePathStep) (interface{}, error) { + switch step.(type) { + case ElementKeyValue: + return s.ElementType, nil + default: + return nil, ErrInvalidStep + } +} + // Equal returns true if the two Sets are exactly equal. Unlike Is, passing in // a Set with no ElementType will always return false. func (s Set) Equal(o Type) bool { @@ -70,9 +83,7 @@ func valueFromSet(typ Type, in interface{}) (Value, error) { case []Value: var elType Type for _, v := range value { - if v.Type().Is(DynamicPseudoType) && v.IsKnown() { - return Value{}, NewAttributePath().WithElementKeyValue(v).NewErrorf("invalid value %s for %s", v, v.Type()) - } else if !v.Type().Is(DynamicPseudoType) && !v.Type().UsableAs(typ) { + if !v.Type().UsableAs(typ) { return Value{}, NewAttributePath().WithElementKeyValue(v).NewErrorf("can't use %s as %s", v.Type(), typ) } if elType == nil { diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/tuple.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/tuple.go index 088243bbd56b..5ca5709a340a 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/tuple.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/tuple.go @@ -19,6 +19,23 @@ type Tuple struct { _ []struct{} } +// ApplyTerraform5AttributePathStep applies an AttributePathStep to a Tuple, +// returning the Type found at that AttributePath within the Tuple. If the +// AttributePathStep cannot be applied to the Tuple, an ErrInvalidStep error +// will be returned. +func (tu Tuple) ApplyTerraform5AttributePathStep(step AttributePathStep) (interface{}, error) { + switch s := step.(type) { + case ElementKeyInt: + if int64(s) < 0 || int64(s) >= int64(len(tu.ElementTypes)) { + return nil, ErrInvalidStep + } + + return tu.ElementTypes[int64(s)], nil + default: + return nil, ErrInvalidStep + } +} + // Equal returns true if the two Tuples are exactly equal. Unlike Is, passing // in a Tuple with no ElementTypes will always return false. func (tu Tuple) Equal(o Type) bool { @@ -109,9 +126,7 @@ func valueFromTuple(types []Type, in interface{}) (Value, error) { } for pos, v := range value { typ := types[pos] - if v.Type().Is(DynamicPseudoType) && v.IsKnown() { - return Value{}, NewAttributePath().WithElementKeyInt(pos).NewErrorf("invalid value %s for %s", v, v.Type()) - } else if !v.Type().Is(DynamicPseudoType) && !v.Type().UsableAs(typ) { + if !v.Type().UsableAs(typ) { return Value{}, NewAttributePath().WithElementKeyInt(pos).NewErrorf("can't use %s as %s", v.Type(), typ) } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/type.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/type.go index 955e322fcff7..4f0e4af7c850 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/type.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/type.go @@ -12,6 +12,12 @@ import ( // implemented by the tftypes package. Types define the shape and // characteristics of data coming from or being sent to Terraform. type Type interface { + // AttributePathStepper requires each Type to implement the + // ApplyTerraform5AttributePathStep method, so Type is compatible with + // WalkAttributePath. The method should return the Type found at that + // AttributePath within the Type or ErrInvalidStep. + AttributePathStepper + // Is is used to determine what type a Type implementation is. It is // the recommended method for determining whether two types are // equivalent or not. diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value.go index 6166cb01bb90..4d7b749894ee 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value.go @@ -2,14 +2,13 @@ package tftypes import ( "bytes" - "errors" "fmt" "math/big" "sort" "strconv" "strings" - "github.com/vmihailenco/msgpack" + msgpack "github.com/vmihailenco/msgpack/v4" ) // ValueConverter is an interface that provider-defined types can implement to @@ -296,10 +295,6 @@ func newValue(t Type, val interface{}) (Value, error) { }, nil } - if t.Is(DynamicPseudoType) { - return Value{}, errors.New("cannot have DynamicPseudoType with known value, DynamicPseudoType can only contain null or unknown values") - } - if creator, ok := val.(ValueCreator); ok { var err error val, err = creator.ToTerraform5Value() @@ -357,6 +352,12 @@ func newValue(t Type, val interface{}) (Value, error) { return Value{}, err } return v, nil + case t.Is(DynamicPseudoType): + v, err := valueFromDynamicPseudoType(val) + if err != nil { + return Value{}, err + } + return v, nil default: return Value{}, fmt.Errorf("unknown type %s passed to tftypes.NewValue", t) } @@ -439,7 +440,7 @@ func (val Value) As(dst interface{}) error { if !ok { return fmt.Errorf("can't unmarshal %s into %T, expected *big.Float", val.Type(), dst) } - target.Set(v) + target.Copy(v) return nil case **big.Float: if val.IsNull() { diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_json.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_json.go index c96401adf191..308434776953 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_json.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_json.go @@ -62,7 +62,7 @@ func jsonUnmarshal(buf []byte, typ Type, p *AttributePath) (Value, error) { return Value{}, p.NewErrorf("unknown type %s", typ) } -func jsonUnmarshalString(buf []byte, typ Type, p *AttributePath) (Value, error) { +func jsonUnmarshalString(buf []byte, _ Type, p *AttributePath) (Value, error) { dec := jsonByteDecoder(buf) tok, err := dec.Token() @@ -98,7 +98,7 @@ func jsonUnmarshalNumber(buf []byte, typ Type, p *AttributePath) (Value, error) } return NewValue(typ, f), nil case string: - f, _, err := big.ParseFloat(string(numTok), 10, 512, big.ToNearestEven) + f, _, err := big.ParseFloat(numTok, 10, 512, big.ToNearestEven) if err != nil { return Value{}, p.NewErrorf("error parsing number: %w", err) } @@ -107,7 +107,7 @@ func jsonUnmarshalNumber(buf []byte, typ Type, p *AttributePath) (Value, error) return Value{}, p.NewErrorf("unsupported type %T sent as %s", tok, Number) } -func jsonUnmarshalBool(buf []byte, typ Type, p *AttributePath) (Value, error) { +func jsonUnmarshalBool(buf []byte, _ Type, p *AttributePath) (Value, error) { dec := jsonByteDecoder(buf) tok, err := dec.Token() if err != nil { @@ -123,7 +123,7 @@ func jsonUnmarshalBool(buf []byte, typ Type, p *AttributePath) (Value, error) { case "false", "0": return NewValue(Bool, false), nil } - switch strings.ToLower(string(v)) { + switch strings.ToLower(v) { case "true": return Value{}, p.NewErrorf("to convert from string, use lowercase \"true\"") case "false": @@ -140,7 +140,7 @@ func jsonUnmarshalBool(buf []byte, typ Type, p *AttributePath) (Value, error) { return Value{}, p.NewErrorf("unsupported type %T sent as %s", tok, Bool) } -func jsonUnmarshalDynamicPseudoType(buf []byte, typ Type, p *AttributePath) (Value, error) { +func jsonUnmarshalDynamicPseudoType(buf []byte, _ Type, p *AttributePath) (Value, error) { dec := jsonByteDecoder(buf) tok, err := dec.Token() if err != nil { @@ -355,20 +355,8 @@ func jsonUnmarshalMap(buf []byte, attrType Type, p *AttributePath) (Value, error return Value{}, p.NewErrorf("invalid JSON, expected %q, got %q", json.Delim('}'), tok) } - elTyp := attrType - if attrType.Is(DynamicPseudoType) { - var elements []Value - for _, val := range vals { - elements = append(elements, val) - } - elTyp, err = TypeFromElements(elements) - if err != nil { - return Value{}, p.NewErrorf("invalid elements for map: %w", err) - } - } - return NewValue(Map{ - ElementType: elTyp, + ElementType: attrType, }, vals), nil } @@ -393,7 +381,6 @@ func jsonUnmarshalTuple(buf []byte, elementTypes []Type, p *AttributePath) (Valu // while generally in Go it's undesirable to treat empty and nil slices // separately, in this case we're surfacing a non-Go-in-origin // distinction, so we'll allow it. - types := []Type{} vals := []Value{} var idx int @@ -415,7 +402,6 @@ func jsonUnmarshalTuple(buf []byte, elementTypes []Type, p *AttributePath) (Valu if err != nil { return Value{}, err } - types = append(types, val.Type()) vals = append(vals, val) } @@ -432,7 +418,7 @@ func jsonUnmarshalTuple(buf []byte, elementTypes []Type, p *AttributePath) (Valu } return NewValue(Tuple{ - ElementTypes: types, + ElementTypes: elementTypes, }, vals), nil } @@ -447,7 +433,6 @@ func jsonUnmarshalObject(buf []byte, attrTypes map[string]Type, p *AttributePath return Value{}, p.NewErrorf("invalid JSON, expected %q, got %q", json.Delim('{'), tok) } - types := map[string]Type{} vals := map[string]Value{} for dec.More() { innerPath := p.WithElementKeyValue(NewValue(String, UnknownValue)) @@ -474,7 +459,6 @@ func jsonUnmarshalObject(buf []byte, attrTypes map[string]Type, p *AttributePath if err != nil { return Value{}, err } - types[key] = val.Type() vals[key] = val } @@ -494,6 +478,6 @@ func jsonUnmarshalObject(buf []byte, attrTypes map[string]Type, p *AttributePath } return NewValue(Object{ - AttributeTypes: types, + AttributeTypes: attrTypes, }, vals), nil } diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_msgpack.go b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_msgpack.go index 3f3db12ef898..c4047aeab2b3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_msgpack.go +++ b/vendor/github.com/hashicorp/terraform-plugin-go/tftypes/value_msgpack.go @@ -7,8 +7,8 @@ import ( "math/big" "sort" - "github.com/vmihailenco/msgpack" - msgpackCodes "github.com/vmihailenco/msgpack/codes" + msgpack "github.com/vmihailenco/msgpack/v4" + msgpackCodes "github.com/vmihailenco/msgpack/v4/codes" ) type msgPackUnknownType struct{} @@ -74,7 +74,7 @@ func msgpackUnmarshal(dec *msgpack.Decoder, typ Type, path *AttributePath) (Valu if err != nil { return Value{}, path.NewErrorf("couldn't decode number as int64: %w", err) } - return NewValue(Number, big.NewFloat(float64(rv))), nil + return NewValue(Number, new(big.Float).SetInt64(rv)), nil } switch peek { case msgpackCodes.Int8, msgpackCodes.Int16, msgpackCodes.Int32, msgpackCodes.Int64: @@ -82,19 +82,19 @@ func msgpackUnmarshal(dec *msgpack.Decoder, typ Type, path *AttributePath) (Valu if err != nil { return Value{}, path.NewErrorf("couldn't decode number as int64: %w", err) } - return NewValue(Number, big.NewFloat(float64(rv))), nil + return NewValue(Number, new(big.Float).SetInt64(rv)), nil case msgpackCodes.Uint8, msgpackCodes.Uint16, msgpackCodes.Uint32, msgpackCodes.Uint64: rv, err := dec.DecodeUint64() if err != nil { return Value{}, path.NewErrorf("couldn't decode number as uint64: %w", err) } - return NewValue(Number, big.NewFloat(float64(rv))), nil + return NewValue(Number, new(big.Float).SetUint64(rv)), nil case msgpackCodes.Float, msgpackCodes.Double: rv, err := dec.DecodeFloat64() if err != nil { return Value{}, path.NewErrorf("couldn't decode number as float64: %w", err) } - return NewValue(Number, big.NewFloat(float64(rv))), nil + return NewValue(Number, big.NewFloat(rv)), nil default: rv, err := dec.DecodeString() if err != nil { @@ -239,24 +239,8 @@ func msgpackUnmarshalMap(dec *msgpack.Decoder, typ Type, path *AttributePath) (V vals[key] = val } - elTyp := typ - - if typ.Is(DynamicPseudoType) { - var elements []Value - - for _, val := range vals { - elements = append(elements, val) - } - - elTyp, err = TypeFromElements(elements) - - if err != nil { - return Value{}, path.NewErrorf("invalid elements for map: %w", err) - } - } - return NewValue(Map{ - ElementType: elTyp, + ElementType: typ, }, vals), nil } @@ -275,7 +259,6 @@ func msgpackUnmarshalTuple(dec *msgpack.Decoder, types []Type, path *AttributePa return Value{}, path.NewErrorf("error decoding tuple; expected %d items, got %d", len(types), length) } - elTypes := make([]Type, 0, length) vals := make([]Value, 0, length) for i := 0; i < length; i++ { innerPath := path.WithElementKeyInt(i) @@ -284,12 +267,11 @@ func msgpackUnmarshalTuple(dec *msgpack.Decoder, types []Type, path *AttributePa if err != nil { return Value{}, err } - elTypes = append(elTypes, val.Type()) vals = append(vals, val) } return NewValue(Tuple{ - ElementTypes: elTypes, + ElementTypes: types, }, vals), nil } @@ -308,7 +290,6 @@ func msgpackUnmarshalObject(dec *msgpack.Decoder, types map[string]Type, path *A return Value{}, path.NewErrorf("error decoding object; expected %d attributes, got %d", len(types), length) } - attrTypes := make(map[string]Type, length) vals := make(map[string]Value, length) for i := 0; i < length; i++ { key, err := dec.DecodeString() @@ -324,12 +305,11 @@ func msgpackUnmarshalObject(dec *msgpack.Decoder, types map[string]Type, path *A if err != nil { return Value{}, err } - attrTypes[key] = val.Type() vals[key] = val } return NewValue(Object{ - AttributeTypes: attrTypes, + AttributeTypes: types, }, vals), nil } @@ -397,7 +377,7 @@ func marshalMsgPack(val Value, typ Type, p *AttributePath, enc *msgpack.Encoder) return fmt.Errorf("unknown type %s", typ) } -func marshalMsgPackDynamicPseudoType(val Value, typ Type, p *AttributePath, enc *msgpack.Encoder) error { +func marshalMsgPackDynamicPseudoType(val Value, _ Type, p *AttributePath, enc *msgpack.Encoder) error { typeJSON, err := val.Type().MarshalJSON() if err != nil { return p.NewErrorf("error generating JSON for type %s: %w", val.Type(), err) diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/internal/hclogutils/args.go b/vendor/github.com/hashicorp/terraform-plugin-log/internal/hclogutils/args.go new file mode 100644 index 000000000000..220120f77f7a --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-log/internal/hclogutils/args.go @@ -0,0 +1,36 @@ +package hclogutils + +// MapsToArgs will shallow merge field maps into the slice of key1, value1, +// key2, value2, ... arguments expected by hc-log.Logger methods. +func MapsToArgs(maps ...map[string]interface{}) []interface{} { + switch len(maps) { + case 0: + return nil + case 1: + result := make([]interface{}, 0, len(maps[0])*2) + + for k, v := range maps[0] { + result = append(result, k) + result = append(result, v) + } + + return result + default: + mergedMap := make(map[string]interface{}, 0) + + for _, m := range maps { + for k, v := range m { + mergedMap[k] = v + } + } + + result := make([]interface{}, 0, len(mergedMap)*2) + + for k, v := range mergedMap { + result = append(result, k) + result = append(result, v) + } + + return result + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/internal/hclogutils/logger_options.go b/vendor/github.com/hashicorp/terraform-plugin-log/internal/hclogutils/logger_options.go new file mode 100644 index 000000000000..a0ec34e20fcd --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-log/internal/hclogutils/logger_options.go @@ -0,0 +1,29 @@ +package hclogutils + +import ( + "github.com/hashicorp/go-hclog" +) + +// LoggerOptionsCopy will safely copy LoggerOptions. Manually implemented +// to save importing a dependency such as github.com/mitchellh/copystructure. +func LoggerOptionsCopy(src *hclog.LoggerOptions) *hclog.LoggerOptions { + if src == nil { + return nil + } + + return &hclog.LoggerOptions{ + AdditionalLocationOffset: src.AdditionalLocationOffset, + Color: src.Color, + DisableTime: src.DisableTime, + Exclude: src.Exclude, + IncludeLocation: src.IncludeLocation, + IndependentLevels: src.IndependentLevels, + JSONFormat: src.JSONFormat, + Level: src.Level, + Mutex: src.Mutex, + Name: src.Name, + Output: src.Output, + TimeFormat: src.TimeFormat, + TimeFn: src.TimeFn, + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/log.go b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/log.go index 8c0ef20f4af8..983bc874dd5f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/log.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/log.go @@ -5,6 +5,14 @@ import ( "os" ) +const ( + // Default provider root logger name. + DefaultProviderRootLoggerName string = "provider" + + // Default SDK root logger name. + DefaultSDKRootLoggerName string = "sdk" +) + // loggerKey defines context keys for locating loggers in context.Context // it's a private type to make sure no other packages can override the key type loggerKey string @@ -14,13 +22,31 @@ const ( // logger for writing logs from within provider code. ProviderRootLoggerKey loggerKey = "provider" + // ProviderRootLoggerOptionsKey is the loggerKey that will hold the root + // logger options when the root provider logger is created. This is to + // assist creating subsystem loggers, as most options cannot be fetched and + // a logger does not provide set methods for these options. + ProviderRootLoggerOptionsKey loggerKey = "provider-options" + // SDKRootLoggerKey is the loggerKey that will hold the root logger for // writing logs from with SDKs. SDKRootLoggerKey loggerKey = "sdk" + // SDKRootLoggerOptionsKey is the loggerKey that will hold the root + // logger options when the SDK provider logger is created. This is to + // assist creating subsystem loggers, as most options cannot be fetched and + // a logger does not provide set methods for these options. + SDKRootLoggerOptionsKey loggerKey = "sdk-options" + // SinkKey is the loggerKey that will hold the logging sink used for // test frameworks. SinkKey loggerKey = "" + + // SinkOptionsKey is the loggerKey that will hold the sink + // logger options when the SDK provider logger is created. This is to + // assist creating subsystem loggers, as most options cannot be fetched and + // a logger does not provide set methods for these options. + SinkOptionsKey loggerKey = "sink-options" ) var ( diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/options.go b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/options.go index fe1e0762df82..02891a33037c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/options.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/options.go @@ -22,6 +22,11 @@ type LoggerOpts struct { // of the logging statement or not. IncludeLocation bool + // AdditionalLocationOffset is the number of additional stack levels to + // skip when finding the file and line information for the log line. + // Defaults to 1 to account for the tflog and tfsdklog logging functions. + AdditionalLocationOffset int + // Output dictates where logs are written to. Output should only ever // be set by tflog or tfsdklog, never by SDK authors or provider // developers. Where logs get written to is complex and delicate and @@ -34,17 +39,23 @@ type LoggerOpts struct { // tfsdklog; providers and SDKs should always include the time logs // were written as part of the log. IncludeTime bool + + // IncludeRootFields indicates whether a new subsystem logger should + // copy existing fields from the root logger. This is only performed + // at the time of new subsystem creation. + IncludeRootFields bool } // ApplyLoggerOpts generates a LoggerOpts out of a list of Option -// implementations. By default, IncludeLocation is true, IncludeTime is true, -// and Output is os.Stderr. +// implementations. By default, AdditionalLocationOffset is 1, IncludeLocation +// is true, IncludeTime is true, and Output is os.Stderr. func ApplyLoggerOpts(opts ...Option) LoggerOpts { // set some defaults l := LoggerOpts{ - IncludeLocation: true, - IncludeTime: true, - Output: os.Stderr, + AdditionalLocationOffset: 1, + IncludeLocation: true, + IncludeTime: true, + Output: os.Stderr, } for _, opt := range opts { l = opt(l) @@ -52,6 +63,18 @@ func ApplyLoggerOpts(opts ...Option) LoggerOpts { return l } +// WithAdditionalLocationOffset sets the WithAdditionalLocationOffset +// configuration option, allowing implementations to fix location information +// when implementing helper functions. The default offset of 1 is automatically +// added to the provided value to account for the tflog and tfsdk logging +// functions. +func WithAdditionalLocationOffset(additionalLocationOffset int) Option { + return func(l LoggerOpts) LoggerOpts { + l.AdditionalLocationOffset = additionalLocationOffset + 1 + return l + } +} + // WithOutput sets the Output configuration option, controlling where logs get // written to. This is mostly used for testing (to write to os.Stdout, so the // test framework can compare it against the example output) and as a helper @@ -63,6 +86,25 @@ func WithOutput(output io.Writer) Option { } } +// WithRootFields enables the copying of root logger fields to a new subsystem +// logger during creation. +func WithRootFields() Option { + return func(l LoggerOpts) LoggerOpts { + l.IncludeRootFields = true + return l + } +} + +// WithoutLocation disables the location included with logging statements. It +// should only ever be used to make log output deterministic when testing +// terraform-plugin-log. +func WithoutLocation() Option { + return func(l LoggerOpts) LoggerOpts { + l.IncludeLocation = false + return l + } +} + // WithoutTimestamp disables the timestamp included with logging statements. It // should only ever be used to make log output deterministic when testing // terraform-plugin-log. diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/provider.go b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/provider.go index 897393c5d5ea..b40a12f83aaf 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/provider.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/provider.go @@ -16,12 +16,41 @@ func GetProviderRootLogger(ctx context.Context) hclog.Logger { return logger.(hclog.Logger) } +// GetProviderRootLoggerOptions returns the root logger options used for +// creating the root provider logger. If the root logger has not been created +// or the options are not present, it will return nil. +func GetProviderRootLoggerOptions(ctx context.Context) *hclog.LoggerOptions { + if GetProviderRootLogger(ctx) == nil { + return nil + } + + loggerOptionsRaw := ctx.Value(ProviderRootLoggerOptionsKey) + + if loggerOptionsRaw == nil { + return nil + } + + loggerOptions, ok := loggerOptionsRaw.(*hclog.LoggerOptions) + + if !ok { + return nil + } + + return loggerOptions +} + // SetProviderRootLogger sets `logger` as the root logger used for writing // logs from a provider. func SetProviderRootLogger(ctx context.Context, logger hclog.Logger) context.Context { return context.WithValue(ctx, ProviderRootLoggerKey, logger) } +// SetProviderRootLoggerOptions sets `loggerOptions` as the root logger options +// used for creating the provider root logger. +func SetProviderRootLoggerOptions(ctx context.Context, loggerOptions *hclog.LoggerOptions) context.Context { + return context.WithValue(ctx, ProviderRootLoggerOptionsKey, loggerOptions) +} + // NewProviderSubsystemLoggerWarning is the text included in log output when a // subsystem is auto-generated by terraform-plugin-log because it was used // before the provider instantiated it. diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/sdk.go b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/sdk.go index 99c577a9d6c4..3c6772b53bb5 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/sdk.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/sdk.go @@ -16,12 +16,41 @@ func GetSDKRootLogger(ctx context.Context) hclog.Logger { return logger.(hclog.Logger) } +// GetSDKRootLoggerOptions returns the root logger options used for +// creating the root SDK logger. If the root logger has not been created or +// the options are not present, it will return nil. +func GetSDKRootLoggerOptions(ctx context.Context) *hclog.LoggerOptions { + if GetSDKRootLogger(ctx) == nil { + return nil + } + + loggerOptionsRaw := ctx.Value(SDKRootLoggerOptionsKey) + + if loggerOptionsRaw == nil { + return nil + } + + loggerOptions, ok := loggerOptionsRaw.(*hclog.LoggerOptions) + + if !ok { + return nil + } + + return loggerOptions +} + // SetSDKRootLogger sets `logger` as the root logger used for writing logs from // an SDK. func SetSDKRootLogger(ctx context.Context, logger hclog.Logger) context.Context { return context.WithValue(ctx, SDKRootLoggerKey, logger) } +// SetSDKRootLoggerOptions sets `loggerOptions` as the root logger options +// used for creating the SDK root logger. +func SetSDKRootLoggerOptions(ctx context.Context, loggerOptions *hclog.LoggerOptions) context.Context { + return context.WithValue(ctx, SDKRootLoggerOptionsKey, loggerOptions) +} + // NewSDKSubsystemLoggerWarning is the text included in log output when a // subsystem is auto-generated by terraform-plugin-log because it was used // before the SDK instantiated it. diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/sink.go b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/sink.go new file mode 100644 index 000000000000..d48f3bf4c18e --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-log/internal/logging/sink.go @@ -0,0 +1,51 @@ +package logging + +import ( + "context" + + "github.com/hashicorp/go-hclog" +) + +// GetSink returns the sink logger used for writing logs. +// If no sink logger has been created, it will return nil. +func GetSink(ctx context.Context) hclog.Logger { + logger := ctx.Value(SinkKey) + if logger == nil { + return nil + } + return logger.(hclog.Logger) +} + +// GetSinkOptions returns the root logger options used for +// creating the root SDK logger. If the root logger has not been created or +// the options are not present, it will return nil. +func GetSinkOptions(ctx context.Context) *hclog.LoggerOptions { + if GetSink(ctx) == nil { + return nil + } + + loggerOptionsRaw := ctx.Value(SinkOptionsKey) + + if loggerOptionsRaw == nil { + return nil + } + + loggerOptions, ok := loggerOptionsRaw.(*hclog.LoggerOptions) + + if !ok { + return nil + } + + return loggerOptions +} + +// SetSink sets `logger` as the sink logger used for writing logs. +func SetSink(ctx context.Context, logger hclog.Logger) context.Context { + return context.WithValue(ctx, SinkKey, logger) +} + +// SetSinkOptions sets `loggerOptions` as the root logger options +// used for creating the SDK root logger. +func SetSinkOptions(ctx context.Context, loggerOptions *hclog.LoggerOptions) context.Context { + return context.WithValue(ctx, SinkOptionsKey, loggerOptions) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/tflog/options.go b/vendor/github.com/hashicorp/terraform-plugin-log/tflog/options.go index 1b61eb55fce8..750177812c28 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/tflog/options.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/tflog/options.go @@ -12,6 +12,14 @@ import ( // to NewSubsystem prior to calling it. type Options []logging.Option +// WithAdditionalLocationOffset returns an option that allowing implementations +// to fix location information when implementing helper functions. The default +// offset of 1 is automatically added to the provided value to account for the +// tflog logging functions. +func WithAdditionalLocationOffset(additionalLocationOffset int) logging.Option { + return logging.WithAdditionalLocationOffset(additionalLocationOffset) +} + // WithLevelFromEnv returns an option that will set the level of the logger // based on the string in an environment variable. The environment variable // checked will be `name` and `subsystems`, joined by _ and in all caps. @@ -35,6 +43,12 @@ func WithLevel(level hclog.Level) logging.Option { } } +// WithRootFields enables the copying of root logger fields to a new subsystem +// logger during creation. +func WithRootFields() logging.Option { + return logging.WithRootFields() +} + // WithoutLocation returns an option that disables including the location of // the log line in the log output, which is on by default. This has no effect // when used with NewSubsystem. diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/tflog/provider.go b/vendor/github.com/hashicorp/terraform-plugin-log/tflog/provider.go index b05856df0da8..e450e3bb6438 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/tflog/provider.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/tflog/provider.go @@ -3,6 +3,7 @@ package tflog import ( "context" + "github.com/hashicorp/terraform-plugin-log/internal/hclogutils" "github.com/hashicorp/terraform-plugin-log/internal/logging" ) @@ -21,10 +22,11 @@ func With(ctx context.Context, key string, value interface{}) context.Context { return logging.SetProviderRootLogger(ctx, logger.With(key, value)) } -// Trace logs `msg` at the trace level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Trace(ctx context.Context, msg string, args ...interface{}) { +// Trace logs `msg` at the trace level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Trace(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderRootLogger(ctx) if logger == nil { // this essentially should never happen in production @@ -34,13 +36,14 @@ func Trace(ctx context.Context, msg string, args ...interface{}) { // so just making this a no-op is fine return } - logger.Trace(msg, args...) + logger.Trace(msg, hclogutils.MapsToArgs(additionalFields...)...) } -// Debug logs `msg` at the debug level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Debug(ctx context.Context, msg string, args ...interface{}) { +// Debug logs `msg` at the debug level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Debug(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderRootLogger(ctx) if logger == nil { // this essentially should never happen in production @@ -50,13 +53,14 @@ func Debug(ctx context.Context, msg string, args ...interface{}) { // so just making this a no-op is fine return } - logger.Debug(msg, args...) + logger.Debug(msg, hclogutils.MapsToArgs(additionalFields...)...) } -// Info logs `msg` at the info level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Info(ctx context.Context, msg string, args ...interface{}) { +// Info logs `msg` at the info level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Info(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderRootLogger(ctx) if logger == nil { // this essentially should never happen in production @@ -66,13 +70,14 @@ func Info(ctx context.Context, msg string, args ...interface{}) { // so just making this a no-op is fine return } - logger.Info(msg, args...) + logger.Info(msg, hclogutils.MapsToArgs(additionalFields...)...) } -// Warn logs `msg` at the warn level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Warn(ctx context.Context, msg string, args ...interface{}) { +// Warn logs `msg` at the warn level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Warn(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderRootLogger(ctx) if logger == nil { // this essentially should never happen in production @@ -82,13 +87,14 @@ func Warn(ctx context.Context, msg string, args ...interface{}) { // so just making this a no-op is fine return } - logger.Warn(msg, args...) + logger.Warn(msg, hclogutils.MapsToArgs(additionalFields...)...) } -// Error logs `msg` at the error level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Error(ctx context.Context, msg string, args ...interface{}) { +// Error logs `msg` at the error level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Error(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderRootLogger(ctx) if logger == nil { // this essentially should never happen in production @@ -98,5 +104,5 @@ func Error(ctx context.Context, msg string, args ...interface{}) { // so just making this a no-op is fine return } - logger.Error(msg, args...) + logger.Error(msg, hclogutils.MapsToArgs(additionalFields...)...) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/tflog/subsystem.go b/vendor/github.com/hashicorp/terraform-plugin-log/tflog/subsystem.go index fbc564e477e2..5cf08f22baf9 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/tflog/subsystem.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/tflog/subsystem.go @@ -4,6 +4,7 @@ import ( "context" "github.com/hashicorp/go-hclog" + "github.com/hashicorp/terraform-plugin-log/internal/hclogutils" "github.com/hashicorp/terraform-plugin-log/internal/logging" ) @@ -17,9 +18,10 @@ import ( // at other times. // // The only Options supported for subsystems are the Options for setting the -// level of the logger. +// level and additional location offset of the logger. func NewSubsystem(ctx context.Context, subsystem string, options ...logging.Option) context.Context { logger := logging.GetProviderRootLogger(ctx) + if logger == nil { // this essentially should never happen in production // the root logger for provider code should be injected @@ -28,11 +30,45 @@ func NewSubsystem(ctx context.Context, subsystem string, options ...logging.Opti // so just making this a no-op is fine return ctx } - subLogger := logger.Named(subsystem) + + loggerOptions := logging.GetProviderRootLoggerOptions(ctx) opts := logging.ApplyLoggerOpts(options...) + + // On the off-chance that the logger options are not available, fallback + // to creating a named logger. This will preserve the root logger options, + // but cannot make changes beyond the level due to the hclog.Logger + // interface. + if loggerOptions == nil { + subLogger := logger.Named(subsystem) + + if opts.AdditionalLocationOffset != 1 { + logger.Warn("Unable to create logging subsystem with AdditionalLocationOffset due to missing root logger options") + } + + if opts.Level != hclog.NoLevel { + subLogger.SetLevel(opts.Level) + } + + return logging.SetProviderSubsystemLogger(ctx, subsystem, subLogger) + } + + subLoggerOptions := hclogutils.LoggerOptionsCopy(loggerOptions) + subLoggerOptions.Name = subLoggerOptions.Name + "." + subsystem + + if opts.AdditionalLocationOffset != 1 { + subLoggerOptions.AdditionalLocationOffset = opts.AdditionalLocationOffset + } + if opts.Level != hclog.NoLevel { - subLogger.SetLevel(opts.Level) + subLoggerOptions.Level = opts.Level } + + subLogger := hclog.New(subLoggerOptions) + + if opts.IncludeRootFields { + subLogger = subLogger.With(logger.ImpliedArgs()...) + } + return logging.SetProviderSubsystemLogger(ctx, subsystem, subLogger) } @@ -42,6 +78,11 @@ func NewSubsystem(ctx context.Context, subsystem string, options ...logging.Opti func SubsystemWith(ctx context.Context, subsystem, key string, value interface{}) context.Context { logger := logging.GetProviderSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetProviderRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return ctx + } // create a new logger if one doesn't exist logger = logging.GetProviderSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewProviderSubsystemLoggerWarning) } @@ -49,61 +90,96 @@ func SubsystemWith(ctx context.Context, subsystem, key string, value interface{} } // SubsystemTrace logs `msg` at the trace level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemTrace(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemTrace(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetProviderRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetProviderSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewProviderSubsystemLoggerWarning) } - logger.Trace(msg, args...) + logger.Trace(msg, hclogutils.MapsToArgs(additionalFields...)...) } // SubsystemDebug logs `msg` at the debug level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemDebug(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemDebug(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetProviderRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetProviderSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewProviderSubsystemLoggerWarning) } - logger.Debug(msg, args...) + logger.Debug(msg, hclogutils.MapsToArgs(additionalFields...)...) } // SubsystemInfo logs `msg` at the info level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemInfo(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemInfo(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetProviderRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetProviderSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewProviderSubsystemLoggerWarning) } - logger.Info(msg, args...) + logger.Info(msg, hclogutils.MapsToArgs(additionalFields...)...) } // SubsystemWarn logs `msg` at the warn level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemWarn(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemWarn(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetProviderRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetProviderSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewProviderSubsystemLoggerWarning) } - logger.Warn(msg, args...) + logger.Warn(msg, hclogutils.MapsToArgs(additionalFields...)...) } // SubsystemError logs `msg` at the error level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemError(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemError(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetProviderSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetProviderRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetProviderSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewProviderSubsystemLoggerWarning) } - logger.Error(msg, args...) + logger.Error(msg, hclogutils.MapsToArgs(additionalFields...)...) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/options.go b/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/options.go index 2115babd71e1..b1ba8e51ef0b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/options.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/options.go @@ -13,6 +13,14 @@ import ( // them. type Options []logging.Option +// WithAdditionalLocationOffset returns an option that allowing implementations +// to fix location information when implementing helper functions. The default +// offset of 1 is automatically added to the provided value to account for the +// tfsdklog logging functions. +func WithAdditionalLocationOffset(additionalLocationOffset int) logging.Option { + return logging.WithAdditionalLocationOffset(additionalLocationOffset) +} + // WithLogName returns an option that will set the logger name explicitly to // `name`. This has no effect when used with NewSubsystem. func WithLogName(name string) logging.Option { @@ -45,6 +53,12 @@ func WithLevel(level hclog.Level) logging.Option { } } +// WithRootFields enables the copying of root logger fields to a new subsystem +// logger during creation. +func WithRootFields() logging.Option { + return logging.WithRootFields() +} + // WithoutLocation returns an option that disables including the location of // the log line in the log output, which is on by default. This has no effect // when used with NewSubsystem. diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/sdk.go b/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/sdk.go index ec22d9fc6d94..a27b7f3b0c83 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/sdk.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/sdk.go @@ -4,6 +4,7 @@ import ( "context" "github.com/hashicorp/go-hclog" + "github.com/hashicorp/terraform-plugin-log/internal/hclogutils" "github.com/hashicorp/terraform-plugin-log/internal/logging" ) @@ -12,14 +13,23 @@ import ( func NewRootSDKLogger(ctx context.Context, options ...logging.Option) context.Context { opts := logging.ApplyLoggerOpts(options...) if opts.Name == "" { - opts.Name = "sdk" + opts.Name = logging.DefaultSDKRootLoggerName } - if sink := getSink(ctx); sink != nil { + if sink := logging.GetSink(ctx); sink != nil { logger := sink.Named(opts.Name) + sinkLoggerOptions := logging.GetSinkOptions(ctx) + sdkLoggerOptions := hclogutils.LoggerOptionsCopy(sinkLoggerOptions) + sdkLoggerOptions.Name = opts.Name + if opts.Level != hclog.NoLevel { logger.SetLevel(opts.Level) + sdkLoggerOptions.Level = opts.Level } - return logging.SetSDKRootLogger(ctx, logger) + + ctx = logging.SetSDKRootLogger(ctx, logger) + ctx = logging.SetSDKRootLoggerOptions(ctx, sdkLoggerOptions) + + return ctx } if opts.Level == hclog.NoLevel { opts.Level = hclog.Trace @@ -32,9 +42,13 @@ func NewRootSDKLogger(ctx context.Context, options ...logging.Option) context.Co IncludeLocation: opts.IncludeLocation, DisableTime: !opts.IncludeTime, Output: opts.Output, - AdditionalLocationOffset: 1, + AdditionalLocationOffset: opts.AdditionalLocationOffset, } - return logging.SetSDKRootLogger(ctx, hclog.New(loggerOptions)) + + ctx = logging.SetSDKRootLogger(ctx, hclog.New(loggerOptions)) + ctx = logging.SetSDKRootLoggerOptions(ctx, loggerOptions) + + return ctx } // NewRootProviderLogger returns a new context.Context that contains a provider @@ -42,14 +56,23 @@ func NewRootSDKLogger(ctx context.Context, options ...logging.Option) context.Co func NewRootProviderLogger(ctx context.Context, options ...logging.Option) context.Context { opts := logging.ApplyLoggerOpts(options...) if opts.Name == "" { - opts.Name = "provider" + opts.Name = logging.DefaultProviderRootLoggerName } - if sink := getSink(ctx); sink != nil { + if sink := logging.GetSink(ctx); sink != nil { logger := sink.Named(opts.Name) + sinkLoggerOptions := logging.GetSinkOptions(ctx) + providerLoggerOptions := hclogutils.LoggerOptionsCopy(sinkLoggerOptions) + providerLoggerOptions.Name = opts.Name + if opts.Level != hclog.NoLevel { logger.SetLevel(opts.Level) + providerLoggerOptions.Level = opts.Level } - return logging.SetProviderRootLogger(ctx, logger) + + ctx = logging.SetProviderRootLogger(ctx, logger) + ctx = logging.SetProviderRootLoggerOptions(ctx, providerLoggerOptions) + + return ctx } if opts.Level == hclog.NoLevel { opts.Level = hclog.Trace @@ -62,9 +85,13 @@ func NewRootProviderLogger(ctx context.Context, options ...logging.Option) conte IncludeLocation: opts.IncludeLocation, DisableTime: !opts.IncludeTime, Output: opts.Output, - AdditionalLocationOffset: 1, + AdditionalLocationOffset: opts.AdditionalLocationOffset, } - return logging.SetProviderRootLogger(ctx, hclog.New(loggerOptions)) + + ctx = logging.SetProviderRootLogger(ctx, hclog.New(loggerOptions)) + ctx = logging.SetProviderRootLoggerOptions(ctx, loggerOptions) + + return ctx } // With returns a new context.Context that has a modified logger in it which @@ -81,10 +108,11 @@ func With(ctx context.Context, key string, value interface{}) context.Context { return logging.SetSDKRootLogger(ctx, logger.With(key, value)) } -// Trace logs `msg` at the trace level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Trace(ctx context.Context, msg string, args ...interface{}) { +// Trace logs `msg` at the trace level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Trace(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKRootLogger(ctx) if logger == nil { // this essentially should never happen in production the root @@ -93,13 +121,14 @@ func Trace(ctx context.Context, msg string, args ...interface{}) { // most so just making this a no-op is fine return } - logger.Trace(msg, args...) + logger.Trace(msg, hclogutils.MapsToArgs(additionalFields...)...) } -// Debug logs `msg` at the debug level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Debug(ctx context.Context, msg string, args ...interface{}) { +// Debug logs `msg` at the debug level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Debug(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKRootLogger(ctx) if logger == nil { // this essentially should never happen in production the root @@ -108,13 +137,14 @@ func Debug(ctx context.Context, msg string, args ...interface{}) { // most so just making this a no-op is fine return } - logger.Debug(msg, args...) + logger.Debug(msg, hclogutils.MapsToArgs(additionalFields...)...) } -// Info logs `msg` at the info level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Info(ctx context.Context, msg string, args ...interface{}) { +// Info logs `msg` at the info level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Info(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKRootLogger(ctx) if logger == nil { // this essentially should never happen in production the root @@ -123,13 +153,14 @@ func Info(ctx context.Context, msg string, args ...interface{}) { // most so just making this a no-op is fine return } - logger.Info(msg, args...) + logger.Info(msg, hclogutils.MapsToArgs(additionalFields...)...) } -// Warn logs `msg` at the warn level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Warn(ctx context.Context, msg string, args ...interface{}) { +// Warn logs `msg` at the warn level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Warn(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKRootLogger(ctx) if logger == nil { // this essentially should never happen in production the root @@ -138,13 +169,14 @@ func Warn(ctx context.Context, msg string, args ...interface{}) { // most so just making this a no-op is fine return } - logger.Warn(msg, args...) + logger.Warn(msg, hclogutils.MapsToArgs(additionalFields...)...) } -// Error logs `msg` at the error level to the logger in `ctx`, with `args` as -// structured arguments in the log output. `args` is expected to be pairs of -// key and value. -func Error(ctx context.Context, msg string, args ...interface{}) { +// Error logs `msg` at the error level to the logger in `ctx`, with optional +// `additionalFields` structured key-value fields in the log output. Fields are +// shallow merged with any defined on the logger, e.g. by the `With()` function, +// and across multiple maps. +func Error(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKRootLogger(ctx) if logger == nil { // this essentially should never happen in production the root @@ -153,5 +185,5 @@ func Error(ctx context.Context, msg string, args ...interface{}) { // most so just making this a no-op is fine return } - logger.Error(msg, args...) + logger.Error(msg, hclogutils.MapsToArgs(additionalFields...)...) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/sink.go b/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/sink.go index 0b26a08907f9..6326901f17ae 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/sink.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/sink.go @@ -6,6 +6,7 @@ import ( "io" "os" "strings" + "sync" "syscall" "github.com/hashicorp/go-hclog" @@ -53,13 +54,8 @@ const ( // loggers. var ValidLevels = []string{"TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF"} -func getSink(ctx context.Context) hclog.Logger { - logger := ctx.Value(logging.SinkKey) - if logger == nil { - return nil - } - return logger.(hclog.Logger) -} +// Only show invalid log level message once across any number of level lookups. +var invalidLogLevelMessage sync.Once // RegisterTestSink sets up a logging sink, for use with test frameworks and // other cases where plugin logs don't get routed through Terraform. This @@ -71,10 +67,15 @@ func getSink(ctx context.Context) hclog.Logger { // RegisterTestSink must be called prior to any loggers being setup or // instantiated. func RegisterTestSink(ctx context.Context, t testing.T) context.Context { - return context.WithValue(ctx, logging.SinkKey, newSink(t)) + logger, loggerOptions := newSink(t) + + ctx = logging.SetSink(ctx, logger) + ctx = logging.SetSinkOptions(ctx, loggerOptions) + + return ctx } -func newSink(t testing.T) hclog.Logger { +func newSink(t testing.T) (hclog.Logger, *hclog.LoggerOptions) { logOutput := io.Writer(os.Stderr) var json bool var logLevel hclog.Level @@ -120,21 +121,29 @@ func newSink(t testing.T) hclog.Logger { } else if isValidLogLevel(envLevel) { logLevel = hclog.LevelFromString(envLevel) } else { - fmt.Fprintf(os.Stderr, "[WARN] Invalid log level: %q. Defaulting to level: OFF. Valid levels are: %+v", - envLevel, ValidLevels) + invalidLogLevelMessage.Do(func() { + fmt.Fprintf( + os.Stderr, + "[WARN] Invalid log level: %q. Defaulting to level: OFF. Valid levels are: %+v\n", + envLevel, + ValidLevels, + ) + }) } - return hclog.New(&hclog.LoggerOptions{ + loggerOptions := &hclog.LoggerOptions{ Level: logLevel, Output: logOutput, IndependentLevels: true, JSONFormat: json, - }) + } + + return hclog.New(loggerOptions), loggerOptions } func isValidLogLevel(level string) bool { - for _, l := range ValidLevels { - if level == string(l) { + for _, validLevel := range ValidLevels { + if level == validLevel { return true } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/subsystem.go b/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/subsystem.go index 96b76791f270..3445288bc754 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/subsystem.go +++ b/vendor/github.com/hashicorp/terraform-plugin-log/tfsdklog/subsystem.go @@ -4,6 +4,7 @@ import ( "context" "github.com/hashicorp/go-hclog" + "github.com/hashicorp/terraform-plugin-log/internal/hclogutils" "github.com/hashicorp/terraform-plugin-log/internal/logging" ) @@ -17,9 +18,10 @@ import ( // at other times. // // The only Options supported for subsystems are the Options for setting the -// level of the logger. +// level and additional location offset of the logger. func NewSubsystem(ctx context.Context, subsystem string, options ...logging.Option) context.Context { logger := logging.GetSDKRootLogger(ctx) + if logger == nil { // this essentially should never happen in production // the root logger for provider code should be injected @@ -28,11 +30,45 @@ func NewSubsystem(ctx context.Context, subsystem string, options ...logging.Opti // so just making this a no-op is fine return ctx } - subLogger := logger.Named(subsystem) + + loggerOptions := logging.GetSDKRootLoggerOptions(ctx) opts := logging.ApplyLoggerOpts(options...) + + // On the off-chance that the logger options are not available, fallback + // to creating a named logger. This will preserve the root logger options, + // but cannot make changes beyond the level due to the hclog.Logger + // interface. + if loggerOptions == nil { + subLogger := logger.Named(subsystem) + + if opts.AdditionalLocationOffset != 1 { + logger.Warn("Unable to create logging subsystem with AdditionalLocationOffset due to missing root logger options") + } + + if opts.Level != hclog.NoLevel { + subLogger.SetLevel(opts.Level) + } + + return logging.SetSDKSubsystemLogger(ctx, subsystem, subLogger) + } + + subLoggerOptions := hclogutils.LoggerOptionsCopy(loggerOptions) + subLoggerOptions.Name = subLoggerOptions.Name + "." + subsystem + + if opts.AdditionalLocationOffset != 1 { + subLoggerOptions.AdditionalLocationOffset = opts.AdditionalLocationOffset + } + if opts.Level != hclog.NoLevel { - subLogger.SetLevel(opts.Level) + subLoggerOptions.Level = opts.Level } + + subLogger := hclog.New(subLoggerOptions) + + if opts.IncludeRootFields { + subLogger = subLogger.With(logger.ImpliedArgs()...) + } + return logging.SetSDKSubsystemLogger(ctx, subsystem, subLogger) } @@ -42,6 +78,11 @@ func NewSubsystem(ctx context.Context, subsystem string, options ...logging.Opti func SubsystemWith(ctx context.Context, subsystem, key string, value interface{}) context.Context { logger := logging.GetSDKSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetSDKRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return ctx + } // create a new logger if one doesn't exist logger = logging.GetSDKSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewSDKSubsystemLoggerWarning) } @@ -49,61 +90,96 @@ func SubsystemWith(ctx context.Context, subsystem, key string, value interface{} } // SubsystemTrace logs `msg` at the trace level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemTrace(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemTrace(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetSDKRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetSDKSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewSDKSubsystemLoggerWarning) } - logger.Trace(msg, args...) + logger.Trace(msg, hclogutils.MapsToArgs(additionalFields...)...) } // SubsystemDebug logs `msg` at the debug level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemDebug(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemDebug(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetSDKRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetSDKSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewSDKSubsystemLoggerWarning) } - logger.Debug(msg, args...) + logger.Debug(msg, hclogutils.MapsToArgs(additionalFields...)...) } // SubsystemInfo logs `msg` at the info level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemInfo(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemInfo(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetSDKRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetSDKSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewSDKSubsystemLoggerWarning) } - logger.Info(msg, args...) + logger.Info(msg, hclogutils.MapsToArgs(additionalFields...)...) } // SubsystemWarn logs `msg` at the warn level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemWarn(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemWarn(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetSDKRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetSDKSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewSDKSubsystemLoggerWarning) } - logger.Warn(msg, args...) + logger.Warn(msg, hclogutils.MapsToArgs(additionalFields...)...) } // SubsystemError logs `msg` at the error level to the subsystem logger -// specified in `ctx`, with `args` as structured arguments in the log output. -// `args` is expected to be pairs of key and value. -func SubsystemError(ctx context.Context, subsystem, msg string, args ...interface{}) { +// specified in `ctx`, with optional `additionalFields` structured key-value +// fields in the log output. Fields are shallow merged with any defined on the +// subsystem logger, e.g. by the `SubsystemWith()` function, and across +// multiple maps. +func SubsystemError(ctx context.Context, subsystem, msg string, additionalFields ...map[string]interface{}) { logger := logging.GetSDKSubsystemLogger(ctx, subsystem) if logger == nil { + if logging.GetSDKRootLogger(ctx) == nil { + // logging isn't set up, nothing we can do, just silently fail + // this should basically never happen in production + return + } // create a new logger if one doesn't exist logger = logging.GetSDKSubsystemLogger(NewSubsystem(ctx, subsystem), subsystem).With("new_logger_warning", logging.NewSDKSubsystemLoggerWarning) } - logger.Error(msg, args...) + logger.Error(msg, hclogutils.MapsToArgs(additionalFields...)...) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest/random.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest/random.go index 12fdde9d5d20..263a1ff57638 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest/random.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest/random.go @@ -120,8 +120,8 @@ func RandIpAddress(s string) (string, error) { last.SetBytes([]byte(lastIp)) r := &big.Int{} r.Sub(last, first) - if len := r.BitLen(); len > 31 { - return "", fmt.Errorf("CIDR range is too large: %d", len) + if bitLen := r.BitLen(); bitLen > 31 { + return "", fmt.Errorf("CIDR range is too large: %d", bitLen) } max := int(r.Int64()) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/computed.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/computed.go index f47d11a4597a..c65a56401cc0 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/computed.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/computed.go @@ -4,14 +4,29 @@ import ( "context" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" ) // ComputedIf returns a CustomizeDiffFunc that sets the given key's new value // as computed if the given condition function returns true. +// +// This function is best effort and will generate a warning log on any errors. func ComputedIf(key string, f ResourceConditionFunc) schema.CustomizeDiffFunc { return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { if f(ctx, d, meta) { - d.SetNewComputed(key) + // To prevent backwards compatibility issues, this logic only + // generates a warning log instead of returning the error to + // the provider and ultimately the practitioner. Providers may + // not be aware of all situations in which the key may not be + // present in the data, such as during resource creation, so any + // further changes here should take that into account by + // documenting how to prevent the error. + if err := d.SetNewComputed(key); err != nil { + logging.HelperSchemaWarn(ctx, "unable to set attribute value to unknown", map[string]interface{}{ + logging.KeyAttributePath: key, + logging.KeyError: err, + }) + } } return nil } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/condition.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/condition.go index e85cdc7aee60..40c06e733ff0 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/condition.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/condition.go @@ -12,7 +12,7 @@ type ResourceConditionFunc func(ctx context.Context, d *schema.ResourceDiff, met // ValueChangeConditionFunc is a function type that makes a boolean decision // by comparing two values. -type ValueChangeConditionFunc func(ctx context.Context, old, new, meta interface{}) bool +type ValueChangeConditionFunc func(ctx context.Context, oldValue, newValue, meta interface{}) bool // ValueConditionFunc is a function type that makes a boolean decision based // on a given value. @@ -41,8 +41,8 @@ func If(cond ResourceConditionFunc, f schema.CustomizeDiffFunc) schema.Customize // given CustomizeDiffFunc only if the condition function returns true. func IfValueChange(key string, cond ValueChangeConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { - old, new := d.GetChange(key) - if cond(ctx, old, new, meta) { + oldValue, newValue := d.GetChange(key) + if cond(ctx, oldValue, newValue, meta) { return f(ctx, d, meta) } return nil diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/force_new.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/force_new.go index 0ffc0886f248..f94257b73033 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/force_new.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/force_new.go @@ -4,6 +4,7 @@ import ( "context" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" ) // ForceNewIf returns a CustomizeDiffFunc that flags the given key as @@ -12,10 +13,24 @@ import ( // The return value of the condition function is ignored if the old and new // values of the field compare equal, since no attribute diff is generated in // that case. +// +// This function is best effort and will generate a warning log on any errors. func ForceNewIf(key string, f ResourceConditionFunc) schema.CustomizeDiffFunc { return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { if f(ctx, d, meta) { - d.ForceNew(key) + // To prevent backwards compatibility issues, this logic only + // generates a warning log instead of returning the error to + // the provider and ultimately the practitioner. Providers may + // not be aware of all situations in which the key may not be + // present in the data, such as during resource creation, so any + // further changes here should take that into account by + // documenting how to prevent the error. + if err := d.ForceNew(key); err != nil { + logging.HelperSchemaWarn(ctx, "unable to require attribute replacement", map[string]interface{}{ + logging.KeyAttributePath: key, + logging.KeyError: err, + }) + } } return nil } @@ -31,11 +46,25 @@ func ForceNewIf(key string, f ResourceConditionFunc) schema.CustomizeDiffFunc { // only the old and new values of the given key, which leads to more compact // and explicit code in the common case where the decision can be made with // only the specific field value. +// +// This function is best effort and will generate a warning log on any errors. func ForceNewIfChange(key string, f ValueChangeConditionFunc) schema.CustomizeDiffFunc { return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { - old, new := d.GetChange(key) - if f(ctx, old, new, meta) { - d.ForceNew(key) + oldValue, newValue := d.GetChange(key) + if f(ctx, oldValue, newValue, meta) { + // To prevent backwards compatibility issues, this logic only + // generates a warning log instead of returning the error to + // the provider and ultimately the practitioner. Providers may + // not be aware of all situations in which the key may not be + // present in the data, such as during resource creation, so any + // further changes here should take that into account by + // documenting how to prevent the error. + if err := d.ForceNew(key); err != nil { + logging.HelperSchemaWarn(ctx, "unable to require attribute replacement", map[string]interface{}{ + logging.KeyAttributePath: key, + logging.KeyError: err, + }) + } } return nil } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/validate.go index 5b88e5e0be82..ad381fb8578a 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/validate.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/validate.go @@ -9,7 +9,7 @@ import ( // ValueChangeValidationFunc is a function type that validates the difference // (or lack thereof) between two values, returning an error if the change // is invalid. -type ValueChangeValidationFunc func(ctx context.Context, old, new, meta interface{}) error +type ValueChangeValidationFunc func(ctx context.Context, oldValue, newValue, meta interface{}) error // ValueValidationFunc is a function type that validates a particular value, // returning an error if the value is invalid. @@ -19,8 +19,8 @@ type ValueValidationFunc func(ctx context.Context, value, meta interface{}) erro // function to the change for the given key, returning any error produced. func ValidateChange(key string, f ValueChangeValidationFunc) schema.CustomizeDiffFunc { return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { - old, new := d.GetChange(key) - return f(ctx, old, new, meta) + oldValue, newValue := d.GetChange(key) + return f(ctx, oldValue, newValue, meta) } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/logging.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/logging.go index 01ae25dfb311..235586aed86b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/logging.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/logging.go @@ -1,7 +1,6 @@ package logging import ( - "context" "fmt" "io" "io/ioutil" @@ -11,7 +10,6 @@ import ( "syscall" "github.com/hashicorp/logutils" - "github.com/hashicorp/terraform-plugin-log/tfsdklog" testing "github.com/mitchellh/go-testing-interface" ) @@ -125,7 +123,7 @@ func LogLevel() string { // IsDebugOrHigher returns whether or not the current log level is debug or trace func IsDebugOrHigher() bool { - level := string(LogLevel()) + level := LogLevel() return level == "DEBUG" || level == "TRACE" } @@ -138,12 +136,3 @@ func isValidLogLevel(level string) bool { return false } - -// GetTestLogContext creates a context that is registered to the SDK log sink. -// This function is for internal usage only and is not supported by the project's -// compatibility promises. -func GetTestLogContext(t testing.T) context.Context { - ctx := context.Background() - ctx = tfsdklog.RegisterTestSink(ctx, t) - return ctx -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/transport.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/transport.go index bddabe647a9a..6419605e799b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/transport.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/transport.go @@ -52,7 +52,7 @@ func prettyPrintJsonLines(b []byte) string { for i, p := range parts { if b := []byte(p); json.Valid(b) { var out bytes.Buffer - json.Indent(&out, b, "", " ") + _ = json.Indent(&out, b, "", " ") // already checked for validity parts[i] = out.String() } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/environment_variables.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/environment_variables.go new file mode 100644 index 000000000000..fed6aa25c328 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/environment_variables.go @@ -0,0 +1,32 @@ +package resource + +// Environment variables for acceptance testing. Additional environment +// variable constants can be found in the internal/plugintest package. +const ( + // Environment variable to enable acceptance tests using this package's + // ParallelTest and Test functions whose TestCase does not enable the + // IsUnitTest field. Defaults to disabled, in which each test will call + // (*testing.T).Skip(). Can be set to any value to enable acceptance tests, + // however "1" is conventional. + EnvTfAcc = "TF_ACC" + + // Environment variable with hostname for the provider under acceptance + // test. The hostname is the first portion of the full provider source + // address, such as "example.com" in example.com/myorg/myprovider. Defaults + // to "registry.terraform.io". + // + // Only required if any Terraform configuration set via the TestStep + // type Config field includes a provider source, such as the terraform + // configuration block required_providers attribute. + EnvTfAccProviderHost = "TF_ACC_PROVIDER_HOST" + + // Environment variable with namespace for the provider under acceptance + // test. The namespace is the second portion of the full provider source + // address, such as "myorg" in registry.terraform.io/myorg/myprovider. + // Defaults to "-" for Terraform 0.12-0.13 compatibility and "hashicorp". + // + // Only required if any Terraform configuration set via the TestStep + // type Config field includes a provider source, such as the terraform + // configuration block required_providers attribute. + EnvTfAccProviderNamespace = "TF_ACC_PROVIDER_NAMESPACE" +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go index 2d649def0ceb..9e52348d69d5 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io/ioutil" - "log" "os" "strings" "sync" @@ -13,29 +12,120 @@ import ( "github.com/hashicorp/terraform-exec/tfexec" "github.com/hashicorp/terraform-plugin-go/tfprotov5" "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest" "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" testing "github.com/mitchellh/go-testing-interface" ) +// protov5ProviderFactory is a function which is called to start a protocol +// version 5 provider server. +type protov5ProviderFactory func() (tfprotov5.ProviderServer, error) + +// protov5ProviderFactories is a mapping of provider addresses to provider +// factory for protocol version 5 provider servers. +type protov5ProviderFactories map[string]func() (tfprotov5.ProviderServer, error) + +// merge combines provider factories. +// +// In case of an overlapping entry, the later entry will overwrite the previous +// value. +func (pf protov5ProviderFactories) merge(otherPfs ...protov5ProviderFactories) protov5ProviderFactories { + result := make(protov5ProviderFactories) + + for name, providerFactory := range pf { + result[name] = providerFactory + } + + for _, otherPf := range otherPfs { + for name, providerFactory := range otherPf { + result[name] = providerFactory + } + } + + return result +} + +// protov6ProviderFactory is a function which is called to start a protocol +// version 6 provider server. +type protov6ProviderFactory func() (tfprotov6.ProviderServer, error) + +// protov6ProviderFactories is a mapping of provider addresses to provider +// factory for protocol version 6 provider servers. +type protov6ProviderFactories map[string]func() (tfprotov6.ProviderServer, error) + +// merge combines provider factories. +// +// In case of an overlapping entry, the later entry will overwrite the previous +// value. +func (pf protov6ProviderFactories) merge(otherPfs ...protov6ProviderFactories) protov6ProviderFactories { + result := make(protov6ProviderFactories) + + for name, providerFactory := range pf { + result[name] = providerFactory + } + + for _, otherPf := range otherPfs { + for name, providerFactory := range otherPf { + result[name] = providerFactory + } + } + + return result +} + +// sdkProviderFactory is a function which is called to start a SDK provider +// server. +type sdkProviderFactory func() (*schema.Provider, error) + +// protov6ProviderFactories is a mapping of provider addresses to provider +// factory for protocol version 6 provider servers. +type sdkProviderFactories map[string]func() (*schema.Provider, error) + +// merge combines provider factories. +// +// In case of an overlapping entry, the later entry will overwrite the previous +// value. +func (pf sdkProviderFactories) merge(otherPfs ...sdkProviderFactories) sdkProviderFactories { + result := make(sdkProviderFactories) + + for name, providerFactory := range pf { + result[name] = providerFactory + } + + for _, otherPf := range otherPfs { + for name, providerFactory := range otherPf { + result[name] = providerFactory + } + } + + return result +} + type providerFactories struct { - legacy map[string]func() (*schema.Provider, error) - protov5 map[string]func() (tfprotov5.ProviderServer, error) - protov6 map[string]func() (tfprotov6.ProviderServer, error) + legacy sdkProviderFactories + protov5 protov5ProviderFactories + protov6 protov6ProviderFactories } -func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, factories providerFactories) error { +func runProviderCommand(ctx context.Context, t testing.T, f func() error, wd *plugintest.WorkingDir, factories *providerFactories) error { // don't point to this as a test failure location // point to whatever called it t.Helper() + // This should not happen, but prevent panics just in case. + if factories == nil { + err := fmt.Errorf("Provider factories are missing to run Terraform command. Please report this bug in the testing framework.") + logging.HelperResourceError(ctx, err.Error()) + return err + } + // Run the providers in the same process as the test runner using the // reattach behavior in Terraform. This ensures we get test coverage // and enables the use of delve as a debugger. - ctx, cancel := context.WithCancel(logging.GetTestLogContext(t)) + ctx, cancel := context.WithCancel(ctx) defer cancel() // this is needed so Terraform doesn't default to expecting protocol 4; @@ -43,8 +133,13 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, // plugins. os.Setenv("PLUGIN_PROTOCOL_VERSIONS", "5") - // Terraform doesn't need to reach out to Checkpoint during testing. - wd.Setenv("CHECKPOINT_DISABLE", "1") + // Acceptance testing does not need to call checkpoint as the output + // is not accessible, nor desirable if explicitly using + // TF_ACC_TERRAFORM_PATH or TF_ACC_TERRAFORM_VERSION environment variables. + // + // Avoid calling (tfexec.Terraform).SetEnv() as it will stop copying + // os.Environ() and prevents TF_VAR_ environment variable usage. + os.Setenv("CHECKPOINT_DISABLE", "1") // Terraform 0.12.X and 0.13.X+ treat namespaceless providers // differently in terms of what namespace they default to. So we're @@ -53,12 +148,12 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, // the host or namespace using environment variables. var namespaces []string host := "registry.terraform.io" - if v := os.Getenv("TF_ACC_PROVIDER_NAMESPACE"); v != "" { + if v := os.Getenv(EnvTfAccProviderNamespace); v != "" { namespaces = append(namespaces, v) } else { namespaces = append(namespaces, "-", "hashicorp") } - if v := os.Getenv("TF_ACC_PROVIDER_HOST"); v != "" { + if v := os.Getenv(EnvTfAccProviderHost); v != "" { host = v } @@ -70,12 +165,17 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, // providerName may be returned as terraform-provider-foo, and // we need just foo. So let's fix that. providerName = strings.TrimPrefix(providerName, "terraform-provider-") + providerAddress := getProviderAddr(providerName) + + logging.HelperResourceDebug(ctx, "Creating sdkv2 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) provider, err := factory() if err != nil { return fmt.Errorf("unable to create provider %q from factory: %w", providerName, err) } + logging.HelperResourceDebug(ctx, "Created sdkv2 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + // keep track of the running factory, so we can make sure it's // shut down. wg.Add(1) @@ -95,14 +195,18 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, }), NoLogOutputOverride: true, UseTFLogSink: t, - ProviderAddr: getProviderAddr(providerName), + ProviderAddr: providerAddress, } - // let's actually start the provider server + logging.HelperResourceDebug(ctx, "Starting sdkv2 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + config, closeCh, err := plugin.DebugServe(ctx, opts) if err != nil { return fmt.Errorf("unable to serve provider %q: %w", providerName, err) } + + logging.HelperResourceDebug(ctx, "Started sdkv2 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + tfexecConfig := tfexec.ReattachConfig{ Protocol: config.Protocol, ProtocolVersion: config.ProtocolVersion, @@ -137,6 +241,7 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, // providerName may be returned as terraform-provider-foo, and // we need just foo. So let's fix that. providerName = strings.TrimPrefix(providerName, "terraform-provider-") + providerAddress := getProviderAddr(providerName) // If the user has supplied the same provider in both // ProviderFactories and ProtoV5ProviderFactories, they made a @@ -150,11 +255,15 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, } } + logging.HelperResourceDebug(ctx, "Creating tfprotov5 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + provider, err := factory() if err != nil { return fmt.Errorf("unable to create provider %q from factory: %w", providerName, err) } + logging.HelperResourceDebug(ctx, "Created tfprotov5 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + // keep track of the running factory, so we can make sure it's // shut down. wg.Add(1) @@ -174,14 +283,18 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, }), NoLogOutputOverride: true, UseTFLogSink: t, - ProviderAddr: getProviderAddr(providerName), + ProviderAddr: providerAddress, } - // let's actually start the provider server + logging.HelperResourceDebug(ctx, "Starting tfprotov5 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + config, closeCh, err := plugin.DebugServe(ctx, opts) if err != nil { return fmt.Errorf("unable to serve provider %q: %w", providerName, err) } + + logging.HelperResourceDebug(ctx, "Started tfprotov5 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + tfexecConfig := tfexec.ReattachConfig{ Protocol: config.Protocol, ProtocolVersion: config.ProtocolVersion, @@ -217,6 +330,7 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, // providerName may be returned as terraform-provider-foo, and // we need just foo. So let's fix that. providerName = strings.TrimPrefix(providerName, "terraform-provider-") + providerAddress := getProviderAddr(providerName) // If the user has already registered this provider in // ProviderFactories or ProtoV5ProviderFactories, they made a @@ -230,11 +344,15 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, } } + logging.HelperResourceDebug(ctx, "Creating tfprotov6 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + provider, err := factory() if err != nil { return fmt.Errorf("unable to create provider %q from factory: %w", providerName, err) } + logging.HelperResourceDebug(ctx, "Created tfprotov6 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + // keep track of the running factory, so we can make sure it's // shut down. wg.Add(1) @@ -250,15 +368,18 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, }), NoLogOutputOverride: true, UseTFLogSink: t, - ProviderAddr: getProviderAddr(providerName), + ProviderAddr: providerAddress, } - // let's actually start the provider server + logging.HelperResourceDebug(ctx, "Starting tfprotov6 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + config, closeCh, err := plugin.DebugServe(ctx, opts) if err != nil { return fmt.Errorf("unable to serve provider %q: %w", providerName, err) } + logging.HelperResourceDebug(ctx, "Started tfprotov6 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress}) + tfexecConfig := tfexec.ReattachConfig{ Protocol: config.Protocol, ProtocolVersion: config.ProtocolVersion, @@ -290,26 +411,35 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, // set the working directory reattach info that will tell Terraform how to // connect to our various running servers. - wd.SetReattachInfo(reattachInfo) + wd.SetReattachInfo(ctx, reattachInfo) + + logging.HelperResourceTrace(ctx, "Calling wrapped Terraform CLI command") // ok, let's call whatever Terraform command the test was trying to // call, now that we know it'll attach back to those servers we just // started. err := f() if err != nil { - log.Printf("[WARN] Got error running Terraform: %s", err) + logging.HelperResourceWarn(ctx, "Error running Terraform CLI command", map[string]interface{}{logging.KeyError: err}) } + logging.HelperResourceTrace(ctx, "Called wrapped Terraform CLI command") + logging.HelperResourceDebug(ctx, "Stopping providers") + // cancel the servers so they'll return. Otherwise, this closeCh won't // get closed, and we'll hang here. cancel() + logging.HelperResourceTrace(ctx, "Waiting for providers to stop") + // wait for the servers to actually shut down; it may take a moment for // them to clean up, or whatever. // TODO: add a timeout here? // PC: do we need one? The test will time out automatically... wg.Wait() + logging.HelperResourceTrace(ctx, "Providers have successfully stopped") + // once we've run the Terraform command, let's remove the reattach // information from the WorkingDir's environment. The WorkingDir will // persist until the next call, but the server in the reattach info @@ -327,10 +457,10 @@ func runProviderCommand(t testing.T, f func() error, wd *plugintest.WorkingDir, func getProviderAddr(name string) string { host := "registry.terraform.io" namespace := "hashicorp" - if v := os.Getenv("TF_ACC_PROVIDER_NAMESPACE"); v != "" { + if v := os.Getenv(EnvTfAccProviderNamespace); v != "" { namespace = v } - if v := os.Getenv("TF_ACC_PROVIDER_HOST"); v != "" { + if v := os.Getenv(EnvTfAccProviderHost); v != "" { host = v } return strings.TrimSuffix(host, "/") + "/" + diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state_shim.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state_shim.go index 7f8c225291ee..497bcc1c9960 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state_shim.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state_shim.go @@ -226,7 +226,7 @@ func (sf *shimmedFlatmap) AddMap(prefix string, m map[string]interface{}) error err := sf.AddEntry(k, value) if err != nil { - return err + return fmt.Errorf("unable to add map key %q entry: %w", k, err) } } @@ -235,7 +235,9 @@ func (sf *shimmedFlatmap) AddMap(prefix string, m map[string]interface{}) error mapLength = fmt.Sprintf("%s.%s", prefix, "%") } - sf.AddEntry(mapLength, strconv.Itoa(len(m))) + if err := sf.AddEntry(mapLength, strconv.Itoa(len(m))); err != nil { + return fmt.Errorf("unable to add map length %q entry: %w", mapLength, err) + } return nil } @@ -245,12 +247,14 @@ func (sf *shimmedFlatmap) AddSlice(name string, elements []interface{}) error { key := fmt.Sprintf("%s.%d", name, i) err := sf.AddEntry(key, elem) if err != nil { - return err + return fmt.Errorf("unable to add slice key %q entry: %w", key, err) } } sliceLength := fmt.Sprintf("%s.#", name) - sf.AddEntry(sliceLength, strconv.Itoa(len(elements))) + if err := sf.AddEntry(sliceLength, strconv.Itoa(len(elements))); err != nil { + return fmt.Errorf("unable to add slice length %q entry: %w", sliceLength, err) + } return nil } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_providers.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_providers.go new file mode 100644 index 000000000000..c09e4657cc21 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_providers.go @@ -0,0 +1,56 @@ +package resource + +import ( + "context" + "fmt" + "strings" +) + +// providerConfig takes the list of providers in a TestCase and returns a +// config with only empty provider blocks. This is useful for Import, where no +// config is provided, but the providers must be defined. +func (c TestCase) providerConfig(_ context.Context) string { + var providerBlocks, requiredProviderBlocks strings.Builder + + // [BF] The Providers field handling predates the logic being moved to this + // method. It's not entirely clear to me at this time why this field + // is being used and not the others, but leaving it here just in case + // it does have a special purpose that wasn't being unit tested prior. + for name := range c.Providers { + providerBlocks.WriteString(fmt.Sprintf("provider %q {}\n", name)) + } + + for name, externalProvider := range c.ExternalProviders { + providerBlocks.WriteString(fmt.Sprintf("provider %q {}\n", name)) + + if externalProvider.Source == "" && externalProvider.VersionConstraint == "" { + continue + } + + requiredProviderBlocks.WriteString(fmt.Sprintf(" %s = {\n", name)) + + if externalProvider.Source != "" { + requiredProviderBlocks.WriteString(fmt.Sprintf(" source = %q\n", externalProvider.Source)) + } + + if externalProvider.VersionConstraint != "" { + requiredProviderBlocks.WriteString(fmt.Sprintf(" version = %q\n", externalProvider.VersionConstraint)) + } + + requiredProviderBlocks.WriteString(" }\n") + } + + if requiredProviderBlocks.Len() > 0 { + return fmt.Sprintf(` +terraform { + required_providers { +%[1]s + } +} + +%[2]s +`, strings.TrimSuffix(requiredProviderBlocks.String(), "\n"), providerBlocks.String()) + } + + return providerBlocks.String() +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_validate.go new file mode 100644 index 000000000000..39e5da46c9c2 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testcase_validate.go @@ -0,0 +1,85 @@ +package resource + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" +) + +// hasProviders returns true if the TestCase has set any of the +// ExternalProviders, ProtoV5ProviderFactories, ProtoV6ProviderFactories, +// ProviderFactories, or Providers fields. +func (c TestCase) hasProviders(_ context.Context) bool { + if len(c.ExternalProviders) > 0 { + return true + } + + if len(c.ProtoV5ProviderFactories) > 0 { + return true + } + + if len(c.ProtoV6ProviderFactories) > 0 { + return true + } + + if len(c.ProviderFactories) > 0 { + return true + } + + if len(c.Providers) > 0 { + return true + } + + return false +} + +// validate ensures the TestCase is valid based on the following criteria: +// +// - No overlapping ExternalProviders and Providers entries +// - No overlapping ExternalProviders and ProviderFactories entries +// - TestStep validations performed by the (TestStep).validate() method. +// +func (c TestCase) validate(ctx context.Context) error { + logging.HelperResourceTrace(ctx, "Validating TestCase") + + if len(c.Steps) == 0 { + err := fmt.Errorf("TestCase missing Steps") + logging.HelperResourceError(ctx, "TestCase validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + for name := range c.ExternalProviders { + if _, ok := c.Providers[name]; ok { + err := fmt.Errorf("TestCase provider %q set in both ExternalProviders and Providers", name) + logging.HelperResourceError(ctx, "TestCase validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + if _, ok := c.ProviderFactories[name]; ok { + err := fmt.Errorf("TestCase provider %q set in both ExternalProviders and ProviderFactories", name) + logging.HelperResourceError(ctx, "TestCase validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + } + + testCaseHasProviders := c.hasProviders(ctx) + + for stepIndex, step := range c.Steps { + stepNumber := stepIndex + 1 // Use 1-based index for humans + stepValidateReq := testStepValidateRequest{ + StepNumber: stepNumber, + TestCaseHasProviders: testCaseHasProviders, + } + + err := step.validate(ctx, stepValidateReq) + + if err != nil { + err := fmt.Errorf("TestStep %d/%d validation error: %w", stepNumber, len(c.Steps), err) + logging.HelperResourceError(ctx, "TestCase validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go index 6d82d80173de..8cb4dbaa6649 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go @@ -1,6 +1,7 @@ package resource import ( + "context" "errors" "flag" "fmt" @@ -12,13 +13,14 @@ import ( "time" "github.com/hashicorp/go-multierror" - testing "github.com/mitchellh/go-testing-interface" + "github.com/mitchellh/go-testing-interface" "github.com/hashicorp/terraform-plugin-go/tfprotov5" "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) @@ -48,7 +50,7 @@ var flagSweepAllowFailures = flag.Bool("sweep-allow-failures", false, "Enable to var flagSweepRun = flag.String("sweep-run", "", "Comma seperated list of Sweeper Tests to run") var sweeperFuncs map[string]*Sweeper -// type SweeperFunc is a signature for a function that acts as a sweeper. It +// SweeperFunc is a signature for a function that acts as a sweeper. It // accepts a string for the region that the sweeper is to be ran in. This // function must be able to construct a valid client for that region. type SweeperFunc func(r string) error @@ -84,6 +86,27 @@ func AddTestSweepers(name string, s *Sweeper) { sweeperFuncs[name] = s } +// TestMain adds sweeper functionality to the "go test" command, otherwise +// tests are executed as normal. Most provider acceptance tests are written +// using the Test() function of this package, which imposes its own +// requirements and Terraform CLI behavior. Refer to that function's +// documentation for additional details. +// +// Sweepers enable infrastructure cleanup functions to be included with +// resource definitions, typically so developers can remove all resources of +// that resource type from testing infrastructure in case of failures that +// prevented the normal resource destruction behavior of acceptance tests. +// Use the AddTestSweepers() function to configure available sweepers. +// +// Sweeper flags added to the "go test" command: +// +// -sweep: Comma-separated list of locations/regions to run available sweepers. +// -sweep-allow-failues: Enable to allow other sweepers to run after failures. +// -sweep-run: Comma-separated list of resource type sweepers to run. Defaults +// to all sweepers. +// +// Refer to the Env prefixed constants for environment variables that further +// control testing functionality. func TestMain(m interface { Run() int }) { @@ -126,7 +149,7 @@ func runSweepers(regions []string, sweepers map[string]*Sweeper, allowFailures b return sweeperRunList, fmt.Errorf("sweeper (%s) for region (%s) failed: %s", sweeper.Name, region, err) } } - elapsed := time.Now().Sub(start) + elapsed := time.Since(start) log.Printf("Completed Sweepers for region (%s) in %s", region, elapsed) log.Printf("Sweeper Tests for region (%s) ran successfully:\n", region) @@ -214,6 +237,7 @@ func runSweeperWithRegion(region string, s *Sweeper, sweepers map[string]*Sweepe depSweeper, ok := sweepers[dep] if !ok { + log.Printf("[ERROR] Sweeper (%s) has dependency (%s), but that sweeper was not found", s.Name, dep) return fmt.Errorf("sweeper (%s) has dependency (%s), but that sweeper was not found", s.Name, dep) } @@ -239,7 +263,7 @@ func runSweeperWithRegion(region string, s *Sweeper, sweepers map[string]*Sweepe start := time.Now() runE := s.F(region) - elapsed := time.Now().Sub(start) + elapsed := time.Since(start) log.Printf("[DEBUG] Completed Sweeper (%s) in region (%s) in %s", s.Name, region, elapsed) @@ -252,7 +276,8 @@ func runSweeperWithRegion(region string, s *Sweeper, sweepers map[string]*Sweepe return runE } -const TestEnvVar = "TF_ACC" +// Deprecated: Use EnvTfAcc instead. +const TestEnvVar = EnvTfAcc // TestCheckFunc is the callback type used with acceptance tests to check // the state of a resource. The state passed in is the latest state known, @@ -275,6 +300,9 @@ type ErrorCheckFunc func(error) error // // When the destroy plan is executed, the config from the last TestStep // is used to plan it. +// +// Refer to the Env prefixed constants for environment variables that further +// control testing functionality. type TestCase struct { // IsUnitTest allows a test to run regardless of the TF_ACC // environment variable. This should be used with care - only for @@ -291,6 +319,11 @@ type TestCase struct { // ProviderFactories can be specified for the providers that are valid. // + // This can also be specified at the TestStep level to enable per-step + // differences in providers, however all provider specifications must + // be done either at the TestCase level or TestStep level, otherwise the + // testing framework will raise an error and fail the test. + // // These are the providers that can be referenced within the test. Each key // is an individually addressable provider. Typically you will only pass a // single value here for the provider you are testing. Aliases are not @@ -312,6 +345,11 @@ type TestCase struct { // ProtoV5ProviderFactories serves the same purpose as ProviderFactories, // but for protocol v5 providers defined using the terraform-plugin-go // ProviderServer interface. + // + // This can also be specified at the TestStep level to enable per-step + // differences in providers, however all provider specifications must + // be done either at the TestCase level or TestStep level, otherwise the + // testing framework will raise an error and fail the test. ProtoV5ProviderFactories map[string]func() (tfprotov5.ProviderServer, error) // ProtoV6ProviderFactories serves the same purpose as ProviderFactories, @@ -319,6 +357,11 @@ type TestCase struct { // ProviderServer interface. // The version of Terraform used in acceptance testing must be greater // than or equal to v0.15.4 to use ProtoV6ProviderFactories. + // + // This can also be specified at the TestStep level to enable per-step + // differences in providers, however all provider specifications must + // be done either at the TestCase level or TestStep level, otherwise the + // testing framework will raise an error and fail the test. ProtoV6ProviderFactories map[string]func() (tfprotov6.ProviderServer, error) // Providers is the ResourceProvider that will be under test. @@ -327,11 +370,18 @@ type TestCase struct { Providers map[string]*schema.Provider // ExternalProviders are providers the TestCase relies on that should - // be downloaded from the registry during init. This is only really - // necessary to set if you're using import, as providers in your config - // will be automatically retrieved during init. Import doesn't use a - // config, however, so we allow manually specifying them here to be - // downloaded for import tests. + // be downloaded from the registry during init. + // + // This can also be specified at the TestStep level to enable per-step + // differences in providers, however all provider specifications must + // be done either at the TestCase level or TestStep level, otherwise the + // testing framework will raise an error and fail the test. + // + // This is generally unnecessary to set at the TestCase level, however + // it has existing in the testing framework prior to the introduction of + // TestStep level specification and was only necessary for performing + // import testing where the configuration contained a provider outside the + // one under test. ExternalProviders map[string]ExternalProvider // PreventPostDestroyRefresh can be set to true for cases where data sources @@ -350,16 +400,18 @@ type TestCase struct { // same state. Each step can have its own check to verify correctness. Steps []TestStep - // The settings below control the "ID-only refresh test." This is - // an enabled-by-default test that tests that a refresh can be - // refreshed with only an ID to result in the same attributes. - // This validates completeness of Refresh. - // - // IDRefreshName is the name of the resource to check. This will - // default to the first non-nil primary resource in the state. + // IDRefreshName is the name of the resource to check during ID-only + // refresh testing, which ensures that a resource can be refreshed solely + // by its identifier. This will default to the first non-nil primary + // resource in the state. It runs every TestStep. // - // IDRefreshIgnore is a list of configuration keys that will be ignored. - IDRefreshName string + // While not deprecated, most resource tests should instead prefer using + // TestStep.ImportState based testing as it works with multiple attribute + // identifiers and also verifies resource import functionality. + IDRefreshName string + + // IDRefreshIgnore is a list of configuration keys that will be ignored + // during ID-only refresh testing. IDRefreshIgnore []string } @@ -376,6 +428,9 @@ type ExternalProvider struct { // Multiple TestSteps can be sequenced in a Test to allow testing // potentially complex update logic. In general, simply create/destroy // tests will only need one step. +// +// Refer to the Env prefixed constants for environment variables that further +// control testing functionality. type TestStep struct { // ResourceName should be set to the name of the resource // that is being tested. Example: "aws_instance.foo". Various test @@ -414,6 +469,9 @@ type TestStep struct { // Config a string of the configuration to give to Terraform. If this // is set, then the TestCase will execute this step with the same logic // as a `terraform apply`. + // + // JSON Configuration Syntax can be used and is assumed whenever Config + // contains valid JSON. Config string // Check is called after the Config is applied. Use this step to @@ -452,8 +510,15 @@ type TestStep struct { // are tested alongside real resources PreventPostDestroyRefresh bool - // SkipFunc is called before applying config, but after PreConfig - // This is useful for defining test steps with platform-dependent checks + // SkipFunc enables skipping the TestStep, based on environment criteria. + // For example, this can prevent running certain steps that may be runtime + // platform or API configuration dependent. + // + // Return true with no error to skip the test step. The error return + // should be used to signify issues that prevented the function from + // completing as expected. + // + // SkipFunc is called after PreConfig but before applying the Config. SkipFunc func() (bool, error) //--------------------------------------------------------------- @@ -498,14 +563,84 @@ type TestStep struct { // fields that can't be refreshed and don't matter. ImportStateVerify bool ImportStateVerifyIgnore []string + + // ProviderFactories can be specified for the providers that are valid for + // this TestStep. When providers are specified at the TestStep level, all + // TestStep within a TestCase must declare providers. + // + // This can also be specified at the TestCase level for all TestStep, + // however all provider specifications must be done either at the TestCase + // level or TestStep level, otherwise the testing framework will raise an + // error and fail the test. + // + // These are the providers that can be referenced within the test. Each key + // is an individually addressable provider. Typically you will only pass a + // single value here for the provider you are testing. Aliases are not + // supported by the test framework, so to use multiple provider instances, + // you should add additional copies to this map with unique names. To set + // their configuration, you would reference them similar to the following: + // + // provider "my_factory_key" { + // # ... + // } + // + // resource "my_resource" "mr" { + // provider = my_factory_key + // + // # ... + // } + ProviderFactories map[string]func() (*schema.Provider, error) + + // ProtoV5ProviderFactories serves the same purpose as ProviderFactories, + // but for protocol v5 providers defined using the terraform-plugin-go + // ProviderServer interface. When providers are specified at the TestStep + // level, all TestStep within a TestCase must declare providers. + // + // This can also be specified at the TestCase level for all TestStep, + // however all provider specifications must be done either at the TestCase + // level or TestStep level, otherwise the testing framework will raise an + // error and fail the test. + ProtoV5ProviderFactories map[string]func() (tfprotov5.ProviderServer, error) + + // ProtoV6ProviderFactories serves the same purpose as ProviderFactories, + // but for protocol v6 providers defined using the terraform-plugin-go + // ProviderServer interface. + // The version of Terraform used in acceptance testing must be greater + // than or equal to v0.15.4 to use ProtoV6ProviderFactories. When providers + // are specified at the TestStep level, all TestStep within a TestCase must + // declare providers. + // + // This can also be specified at the TestCase level for all TestStep, + // however all provider specifications must be done either at the TestCase + // level or TestStep level, otherwise the testing framework will raise an + // error and fail the test. + ProtoV6ProviderFactories map[string]func() (tfprotov6.ProviderServer, error) + + // ExternalProviders are providers the TestStep relies on that should + // be downloaded from the registry during init. When providers are + // specified at the TestStep level, all TestStep within a TestCase must + // declare providers. + // + // This can also be specified at the TestCase level for all TestStep, + // however all provider specifications must be done either at the TestCase + // level or TestStep level, otherwise the testing framework will raise an + // error and fail the test. + // + // Outside specifying an earlier version of the provider under test, + // typically for state upgrader testing, this is generally only necessary + // for performing import testing where the prior TestStep configuration + // contained a provider outside the one under test. + ExternalProviders map[string]ExternalProvider } // ParallelTest performs an acceptance test on a resource, allowing concurrency -// with other ParallelTest. +// with other ParallelTest. The number of concurrent tests is controlled by the +// "go test" command -parallel flag. // // Tests will fail if they do not properly handle conditions to allow multiple // tests to occur against the same resource or service (e.g. random naming). -// All other requirements of the Test function also apply to this function. +// +// Test() function requirements and documentation also apply to this function. func ParallelTest(t testing.T, c TestCase) { t.Helper() t.Parallel() @@ -522,98 +657,100 @@ func ParallelTest(t testing.T, c TestCase) { // the "-test.v" flag) is set. Because some acceptance tests take quite // long, we require the verbose flag so users are able to see progress // output. +// +// Use the ParallelTest() function to automatically set (*testing.T).Parallel() +// to enable testing concurrency. Use the UnitTest() function to automatically +// set the TestCase type IsUnitTest field. +// +// This function will automatically find or install Terraform CLI into a +// temporary directory, based on the following behavior: +// +// - If the TF_ACC_TERRAFORM_PATH environment variable is set, that +// Terraform CLI binary is used if found and executable. If not found or +// executable, an error will be returned unless the +// TF_ACC_TERRAFORM_VERSION environment variable is also set. +// - If the TF_ACC_TERRAFORM_VERSION environment variable is set, install +// and use that Terraform CLI version. +// - If both the TF_ACC_TERRAFORM_PATH and TF_ACC_TERRAFORM_VERSION +// environment variables are unset, perform a lookup for the Terraform +// CLI binary based on the operating system PATH. If not found, the +// latest available Terraform CLI binary is installed. +// +// Refer to the Env prefixed constants for additional details about these +// environment variables, and others, that control testing functionality. func Test(t testing.T, c TestCase) { t.Helper() + ctx := context.Background() + ctx = logging.InitTestContext(ctx, t) + + err := c.validate(ctx) + + if err != nil { + logging.HelperResourceError(ctx, + "Test validation error", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("Test validation error: %s", err) + } + // We only run acceptance tests if an env var is set because they're // slow and generally require some outside configuration. You can opt out // of this with OverrideEnvVar on individual TestCases. - if os.Getenv(TestEnvVar) == "" && !c.IsUnitTest { + if os.Getenv(EnvTfAcc) == "" && !c.IsUnitTest { t.Skip(fmt.Sprintf( "Acceptance tests skipped unless env '%s' set", - TestEnvVar)) + EnvTfAcc)) return } - logging.SetOutput(t) - // Copy any explicitly passed providers to factories, this is for backwards compatibility. if len(c.Providers) > 0 { c.ProviderFactories = map[string]func() (*schema.Provider, error){} for name, p := range c.Providers { - if _, ok := c.ProviderFactories[name]; ok { - t.Fatalf("ProviderFactory for %q already exists, cannot overwrite with Provider", name) - } prov := p - c.ProviderFactories[name] = func() (*schema.Provider, error) { + c.ProviderFactories[name] = func() (*schema.Provider, error) { //nolint:unparam // required signature return prov, nil } } } + logging.HelperResourceDebug(ctx, "Starting TestCase") + // Run the PreCheck if we have it. // This is done after the auto-configure to allow providers // to override the default auto-configure parameters. if c.PreCheck != nil { + logging.HelperResourceDebug(ctx, "Calling TestCase PreCheck") + c.PreCheck() + + logging.HelperResourceDebug(ctx, "Called TestCase PreCheck") } sourceDir, err := os.Getwd() if err != nil { t.Fatalf("Error getting working dir: %s", err) } - helper := plugintest.AutoInitProviderHelper(sourceDir) + helper := plugintest.AutoInitProviderHelper(ctx, sourceDir) defer func(helper *plugintest.Helper) { err := helper.Close() if err != nil { - log.Printf("Error cleaning up temporary test files: %s", err) + logging.HelperResourceError(ctx, "Unable to clean up temporary test files", map[string]interface{}{logging.KeyError: err}) } }(helper) - runNewTest(t, c, helper) -} - -// testProviderConfig takes the list of Providers in a TestCase and returns a -// config with only empty provider blocks. This is useful for Import, where no -// config is provided, but the providers must be defined. -func testProviderConfig(c TestCase) (string, error) { - var lines []string - var requiredProviders []string - for p := range c.Providers { - lines = append(lines, fmt.Sprintf("provider %q {}\n", p)) - } - for p, v := range c.ExternalProviders { - if _, ok := c.Providers[p]; ok { - return "", fmt.Errorf("Provider %q set in both Providers and ExternalProviders for TestCase. Must be set in only one.", p) - } - if _, ok := c.ProviderFactories[p]; ok { - return "", fmt.Errorf("Provider %q set in both ProviderFactories and ExternalProviders for TestCase. Must be set in only one.", p) - } - lines = append(lines, fmt.Sprintf("provider %q {}\n", p)) - var providerBlock string - if v.VersionConstraint != "" { - providerBlock = fmt.Sprintf("%s\nversion = %q", providerBlock, v.VersionConstraint) - } - if v.Source != "" { - providerBlock = fmt.Sprintf("%s\nsource = %q", providerBlock, v.Source) - } - if providerBlock != "" { - providerBlock = fmt.Sprintf("%s = {%s\n}\n", p, providerBlock) - } - requiredProviders = append(requiredProviders, providerBlock) - } - - if len(requiredProviders) > 0 { - lines = append([]string{fmt.Sprintf("terraform {\nrequired_providers {\n%s}\n}\n\n", strings.Join(requiredProviders, ""))}, lines...) - } + runNewTest(ctx, t, c, helper) - return strings.Join(lines, ""), nil + logging.HelperResourceDebug(ctx, "Finished TestCase") } // UnitTest is a helper to force the acceptance testing harness to run in the // normal unit test suite. This should only be used for resource that don't // have any external dependencies. +// +// Test() function requirements and documentation also apply to this function. func UnitTest(t testing.T, c TestCase) { t.Helper() @@ -622,10 +759,6 @@ func UnitTest(t testing.T, c TestCase) { } func testResource(c TestStep, state *terraform.State) (*terraform.ResourceState, error) { - if c.ResourceName == "" { - return nil, fmt.Errorf("ResourceName must be set in TestStep") - } - for _, m := range state.Modules { if len(m.Resources) > 0 { if v, ok := m.Resources[c.ResourceName]; ok { @@ -643,6 +776,9 @@ func testResource(c TestStep, state *terraform.State) (*terraform.ResourceState, // // As a user testing their provider, this lets you decompose your checks // into smaller pieces more easily. +// +// ComposeTestCheckFunc returns immediately on the first TestCheckFunc error. +// To aggregrate all errors, use ComposeAggregateTestCheckFunc instead. func ComposeTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc { return func(s *terraform.State) error { for i, f := range fs { @@ -677,10 +813,48 @@ func ComposeAggregateTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc { } } -// TestCheckResourceAttrSet is a TestCheckFunc which ensures a value -// exists in state for the given name/key combination. It is useful when -// testing that computed values were set, when it is not possible to -// know ahead of time what the values will be. +// TestCheckResourceAttrSet ensures any value exists in the state for the +// given name and key combination. The opposite of this TestCheckFunc is +// TestCheckNoResourceAttr. State value checking is only recommended for +// testing Computed attributes and attribute defaults. +// +// Use this as a last resort when a more specific TestCheckFunc cannot be +// implemented, such as: +// +// - TestCheckResourceAttr: Equality checking of non-TypeSet state value. +// - TestCheckResourceAttrPair: Equality checking of non-TypeSet state +// value, based on another state value. +// - TestCheckTypeSet*: Equality checking of TypeSet state values. +// - TestMatchResourceAttr: Regular expression checking of non-TypeSet +// state value. +// - TestMatchTypeSet*: Regular expression checking on TypeSet state values. +// +// For managed resources, the name parameter is combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". +// +// resource "myprovider_thing" "example" { ... } +// +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the following special key syntax to inspect underlying +// values of a list or map attribute: +// +// - .{NUMBER}: List value at index, e.g. .0 to inspect the first element +// - .{KEY}: Map value at key, e.g. .example to inspect the example key +// value +// +// While it is possible to check nested attributes under list and map +// attributes using the special key syntax, checking a list, map, or set +// attribute directly is not supported. Use TestCheckResourceAttr with +// the special .# or .% key syntax for those situations instead. func TestCheckResourceAttrSet(name, key string) TestCheckFunc { return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { is, err := primaryInstanceState(s, name) @@ -707,15 +881,71 @@ func TestCheckModuleResourceAttrSet(mp []string, name string, key string) TestCh } func testCheckResourceAttrSet(is *terraform.InstanceState, name string, key string) error { - if val, ok := is.Attributes[key]; !ok || val == "" { - return fmt.Errorf("%s: Attribute '%s' expected to be set", name, key) + val, ok := is.Attributes[key] + + if ok && val != "" { + return nil } - return nil + if _, ok := is.Attributes[key+".#"]; ok { + return fmt.Errorf( + "%s: list or set attribute '%s' must be checked by element count key (%s) or element value keys (e.g. %s). Set element value checks should use TestCheckTypeSet functions instead.", + name, + key, + key+".#", + key+".0", + ) + } + + if _, ok := is.Attributes[key+".%"]; ok { + return fmt.Errorf( + "%s: map attribute '%s' must be checked by element count key (%s) or element value keys (e.g. %s).", + name, + key, + key+".%", + key+".examplekey", + ) + } + + return fmt.Errorf("%s: Attribute '%s' expected to be set", name, key) } -// TestCheckResourceAttr is a TestCheckFunc which validates -// the value in state for the given name/key combination. +// TestCheckResourceAttr ensures a specific value is stored in state for the +// given name and key combination. State value checking is only recommended for +// testing Computed attributes and attribute defaults. +// +// For managed resources, the name parameter is combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". +// +// resource "myprovider_thing" "example" { ... } +// +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the following special key syntax to inspect list, map, and +// set attributes: +// +// - .{NUMBER}: List value at index, e.g. .0 to inspect the first element. +// Use the TestCheckTypeSet* and TestMatchTypeSet* functions instead +// for sets. +// - .{KEY}: Map value at key, e.g. .example to inspect the example key +// value. +// - .#: Number of elements in list or set. +// - .%: Number of elements in map. +// +// The value parameter is the stringified data to check at the given key. Use +// the following attribute type rules to set the value: +// +// - Boolean: "false" or "true". +// - Float/Integer: Stringified number, such as "1.2" or "123". +// - String: No conversion necessary. func TestCheckResourceAttr(name, key, value string) TestCheckFunc { return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { is, err := primaryInstanceState(s, name) @@ -742,23 +972,40 @@ func TestCheckModuleResourceAttr(mp []string, name string, key string, value str } func testCheckResourceAttr(is *terraform.InstanceState, name string, key string, value string) error { - // Empty containers may be elided from the state. - // If the intent here is to check for an empty container, allow the key to - // also be non-existent. - emptyCheck := false - if value == "0" && (strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%")) { - emptyCheck = true - } + v, ok := is.Attributes[key] - if v, ok := is.Attributes[key]; !ok || v != value { - if emptyCheck && !ok { + if !ok { + // Empty containers may be elided from the state. + // If the intent here is to check for an empty container, allow the key to + // also be non-existent. + if value == "0" && (strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%")) { return nil } - if !ok { - return fmt.Errorf("%s: Attribute '%s' not found", name, key) + if _, ok := is.Attributes[key+".#"]; ok { + return fmt.Errorf( + "%s: list or set attribute '%s' must be checked by element count key (%s) or element value keys (e.g. %s). Set element value checks should use TestCheckTypeSet functions instead.", + name, + key, + key+".#", + key+".0", + ) + } + + if _, ok := is.Attributes[key+".%"]; ok { + return fmt.Errorf( + "%s: map attribute '%s' must be checked by element count key (%s) or element value keys (e.g. %s).", + name, + key, + key+".%", + key+".examplekey", + ) } + return fmt.Errorf("%s: Attribute '%s' not found", name, key) + } + + if v != value { return fmt.Errorf( "%s: Attribute '%s' expected %#v, got %#v", name, @@ -766,11 +1013,103 @@ func testCheckResourceAttr(is *terraform.InstanceState, name string, key string, value, v) } + return nil } -// TestCheckNoResourceAttr is a TestCheckFunc which ensures that -// NO value exists in state for the given name/key combination. +// CheckResourceAttrWithFunc is the callback type used to apply a custom checking logic +// when using TestCheckResourceAttrWith and a value is found for the given name and key. +// +// When this function returns an error, TestCheckResourceAttrWith will fail the check. +type CheckResourceAttrWithFunc func(value string) error + +// TestCheckResourceAttrWith ensures a value stored in state for the +// given name and key combination, is checked against a custom logic. +// State value checking is only recommended for testing Computed attributes +// and attribute defaults. +// +// For managed resources, the name parameter is combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". +// +// resource "myprovider_thing" "example" { ... } +// +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the following special key syntax to inspect list, map, and +// set attributes: +// +// - .{NUMBER}: List value at index, e.g. .0 to inspect the first element. +// Use the TestCheckTypeSet* and TestMatchTypeSet* functions instead +// for sets. +// - .{KEY}: Map value at key, e.g. .example to inspect the example key +// value. +// - .#: Number of elements in list or set. +// - .%: Number of elements in map. +// +// The checkValueFunc parameter is a CheckResourceAttrWithFunc, +// and it's provided with the attribute value to apply a custom checking logic, +// if it was found in the state. The function must return an error for the +// check to fail, or `nil` to succeed. +func TestCheckResourceAttrWith(name, key string, checkValueFunc CheckResourceAttrWithFunc) TestCheckFunc { + return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { + is, err := primaryInstanceState(s, name) + if err != nil { + return err + } + + err = testCheckResourceAttrSet(is, name, key) + if err != nil { + return err + } + + err = checkValueFunc(is.Attributes[key]) + if err != nil { + return fmt.Errorf("%s: Attribute %q value: %w", name, key, err) + } + + return nil + }) +} + +// TestCheckNoResourceAttr ensures no value exists in the state for the +// given name and key combination. The opposite of this TestCheckFunc is +// TestCheckResourceAttrSet. State value checking is only recommended for +// testing Computed attributes and attribute defaults. +// +// For managed resources, the name parameter is combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". +// +// resource "myprovider_thing" "example" { ... } +// +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the following special key syntax to inspect underlying +// values of a list or map attribute: +// +// - .{NUMBER}: List value at index, e.g. .0 to inspect the first element. +// - .{KEY}: Map value at key, e.g. .example to inspect the example key +// value. +// +// While it is possible to check nested attributes under list and map +// attributes using the special key syntax, checking a list, map, or set +// attribute directly is not supported. Use TestCheckResourceAttr with +// the special .# or .% key syntax for those situations instead. func TestCheckNoResourceAttr(name, key string) TestCheckFunc { return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { is, err := primaryInstanceState(s, name) @@ -797,28 +1136,76 @@ func TestCheckModuleNoResourceAttr(mp []string, name string, key string) TestChe } func testCheckNoResourceAttr(is *terraform.InstanceState, name string, key string) error { + v, ok := is.Attributes[key] + // Empty containers may sometimes be included in the state. // If the intent here is to check for an empty container, allow the value to // also be "0". - emptyCheck := false - if strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%") { - emptyCheck = true - } - - val, exists := is.Attributes[key] - if emptyCheck && val == "0" { + if v == "0" && (strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%")) { return nil } - if exists { + if ok { return fmt.Errorf("%s: Attribute '%s' found when not expected", name, key) } + if _, ok := is.Attributes[key+".#"]; ok { + return fmt.Errorf( + "%s: list or set attribute '%s' must be checked by element count key (%s) or element value keys (e.g. %s). Set element value checks should use TestCheckTypeSet functions instead.", + name, + key, + key+".#", + key+".0", + ) + } + + if _, ok := is.Attributes[key+".%"]; ok { + return fmt.Errorf( + "%s: map attribute '%s' must be checked by element count key (%s) or element value keys (e.g. %s).", + name, + key, + key+".%", + key+".examplekey", + ) + } + return nil } -// TestMatchResourceAttr is a TestCheckFunc which checks that the value -// in state for the given name/key combination matches the given regex. +// TestMatchResourceAttr ensures a value matching a regular expression is +// stored in state for the given name and key combination. State value checking +// is only recommended for testing Computed attributes and attribute defaults. +// +// For managed resources, the name parameter is combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". +// +// resource "myprovider_thing" "example" { ... } +// +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the following special key syntax to inspect list, map, and +// set attributes: +// +// - .{NUMBER}: List value at index, e.g. .0 to inspect the first element. +// Use the TestCheckTypeSet* and TestMatchTypeSet* functions instead +// for sets. +// - .{KEY}: Map value at key, e.g. .example to inspect the example key +// value. +// - .#: Number of elements in list or set. +// - .%: Number of elements in map. +// +// The value parameter is a compiled regular expression. A typical pattern is +// using the regexp.MustCompile() function, which will automatically ensure the +// regular expression is supported by the Go regular expression handlers during +// compilation. func TestMatchResourceAttr(name, key string, r *regexp.Regexp) TestCheckFunc { return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { is, err := primaryInstanceState(s, name) @@ -860,6 +1247,9 @@ func testMatchResourceAttr(is *terraform.InstanceState, name string, key string, // TestCheckResourceAttrPtr is like TestCheckResourceAttr except the // value is a pointer so that it can be updated while the test is running. // It will only be dereferenced at the point this step is run. +// +// Refer to the TestCheckResourceAttr documentation for more information about +// setting the name, key, and value parameters. func TestCheckResourceAttrPtr(name string, key string, value *string) TestCheckFunc { return func(s *terraform.State) error { return TestCheckResourceAttr(name, key, *value)(s) @@ -874,8 +1264,39 @@ func TestCheckModuleResourceAttrPtr(mp []string, name string, key string, value } } -// TestCheckResourceAttrPair is a TestCheckFunc which validates that the values -// in state for a pair of name/key combinations are equal. +// TestCheckResourceAttrPair ensures value equality in state between the first +// given name and key combination and the second name and key combination. +// State value checking is only recommended for testing Computed attributes +// and attribute defaults. +// +// For managed resources, the name parameter is combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". +// +// resource "myprovider_thing" "example" { ... } +// +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The first and second names may use any combination of managed resources +// and/or data sources. +// +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the following special key syntax to inspect list, map, and +// set attributes: +// +// - .{NUMBER}: List value at index, e.g. .0 to inspect the first element. +// Use the TestCheckTypeSet* and TestMatchTypeSet* functions instead +// for sets. +// - .{KEY}: Map value at key, e.g. .example to inspect the example key +// value. +// - .#: Number of elements in list or set. +// - .%: Number of elements in map. func TestCheckResourceAttrPair(nameFirst, keyFirst, nameSecond, keySecond string) TestCheckFunc { return checkIfIndexesIntoTypeSetPair(keyFirst, keySecond, func(s *terraform.State) error { isFirst, err := primaryInstanceState(s, nameFirst) @@ -1004,7 +1425,7 @@ func TestMatchOutput(name string, r *regexp.Regexp) TestCheckFunc { // modulePrimaryInstanceState returns the instance state for the given resource // name in a ModuleState -func modulePrimaryInstanceState(s *terraform.State, ms *terraform.ModuleState, name string) (*terraform.InstanceState, error) { +func modulePrimaryInstanceState(ms *terraform.ModuleState, name string) (*terraform.InstanceState, error) { rs, ok := ms.Resources[name] if !ok { return nil, fmt.Errorf("Not found: %s in %s", name, ms.Path) @@ -1026,14 +1447,14 @@ func modulePathPrimaryInstanceState(s *terraform.State, mp addrs.ModuleInstance, return nil, fmt.Errorf("No module found at: %s", mp) } - return modulePrimaryInstanceState(s, ms, name) + return modulePrimaryInstanceState(ms, name) } // primaryInstanceState returns the primary instance state for the given // resource name in the root module. func primaryInstanceState(s *terraform.State, name string) (*terraform.InstanceState, error) { ms := s.RootModule() - return modulePrimaryInstanceState(s, ms, name) + return modulePrimaryInstanceState(ms, name) } // indexesIntoTypeSet is a heuristic to try and identify if a flatmap style diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_config.go index 1e39294fd7f2..e28426fde3b8 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_config.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_config.go @@ -1,14 +1,21 @@ package resource import ( + "context" "errors" "fmt" - "log" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func testStepTaint(state *terraform.State, step TestStep) error { +func testStepTaint(ctx context.Context, state *terraform.State, step TestStep) error { + if len(step.Taint) == 0 { + return nil + } + + logging.HelperResourceTrace(ctx, fmt.Sprintf("Using TestStep Taint: %v", step.Taint)) + for _, p := range step.Taint { m := state.RootModule() if m == nil { @@ -18,7 +25,7 @@ func testStepTaint(state *terraform.State, step TestStep) error { if !ok { return fmt.Errorf("resource %q not found in state", p) } - log.Printf("[WARN] Test: Explicitly tainting resource %q", p) + logging.HelperResourceWarn(ctx, fmt.Sprintf("Explicitly tainting resource %q", p)) rs.Taint() } return nil diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go index 1dc73906b331..f1e607f83428 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go @@ -1,8 +1,8 @@ package resource import ( + "context" "fmt" - "log" "reflect" "strings" @@ -10,63 +10,77 @@ import ( tfjson "github.com/hashicorp/terraform-json" testing "github.com/mitchellh/go-testing-interface" - "github.com/hashicorp/terraform-plugin-go/tfprotov5" - "github.com/hashicorp/terraform-plugin-go/tfprotov6" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func runPostTestDestroy(t testing.T, c TestCase, wd *plugintest.WorkingDir, factories map[string]func() (*schema.Provider, error), v5factories map[string]func() (tfprotov5.ProviderServer, error), v6factories map[string]func() (tfprotov6.ProviderServer, error), statePreDestroy *terraform.State) error { +func runPostTestDestroy(ctx context.Context, t testing.T, c TestCase, wd *plugintest.WorkingDir, providers *providerFactories, statePreDestroy *terraform.State) error { t.Helper() - err := runProviderCommand(t, func() error { - return wd.Destroy() - }, wd, providerFactories{ - legacy: factories, - protov5: v5factories, - protov6: v6factories}) + err := runProviderCommand(ctx, t, func() error { + return wd.Destroy(ctx) + }, wd, providers) if err != nil { return err } if c.CheckDestroy != nil { + logging.HelperResourceTrace(ctx, "Using TestCase CheckDestroy") + logging.HelperResourceDebug(ctx, "Calling TestCase CheckDestroy") + if err := c.CheckDestroy(statePreDestroy); err != nil { return err } + + logging.HelperResourceDebug(ctx, "Called TestCase CheckDestroy") } return nil } -func runNewTest(t testing.T, c TestCase, helper *plugintest.Helper) { +func runNewTest(ctx context.Context, t testing.T, c TestCase, helper *plugintest.Helper) { t.Helper() spewConf := spew.NewDefaultConfig() spewConf.SortKeys = true - wd := helper.RequireNewWorkingDir(t) + wd := helper.RequireNewWorkingDir(ctx, t) + + ctx = logging.TestTerraformPathContext(ctx, wd.GetHelper().TerraformExecPath()) + ctx = logging.TestWorkingDirectoryContext(ctx, wd.GetHelper().WorkingDirectory()) + + providers := &providerFactories{ + legacy: c.ProviderFactories, + protov5: c.ProtoV5ProviderFactories, + protov6: c.ProtoV6ProviderFactories, + } defer func() { var statePreDestroy *terraform.State var err error - err = runProviderCommand(t, func() error { - statePreDestroy, err = getState(t, wd) + err = runProviderCommand(ctx, t, func() error { + statePreDestroy, err = getState(ctx, t, wd) if err != nil { return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { + logging.HelperResourceError(ctx, + "Error retrieving state, there may be dangling resources", + map[string]interface{}{logging.KeyError: err}, + ) t.Fatalf("Error retrieving state, there may be dangling resources: %s", err.Error()) return } if !stateIsEmpty(statePreDestroy) { - err := runPostTestDestroy(t, c, wd, c.ProviderFactories, c.ProtoV5ProviderFactories, c.ProtoV6ProviderFactories, statePreDestroy) + err := runPostTestDestroy(ctx, t, c, wd, providers, statePreDestroy) if err != nil { + logging.HelperResourceError(ctx, + "Error running post-test destroy, there may be dangling resources", + map[string]interface{}{logging.KeyError: err}, + ) t.Fatalf("Error running post-test destroy, there may be dangling resources: %s", err.Error()) } } @@ -74,95 +88,233 @@ func runNewTest(t testing.T, c TestCase, helper *plugintest.Helper) { wd.Close() }() - providerCfg, err := testProviderConfig(c) - if err != nil { - t.Fatal(err) - } + if c.hasProviders(ctx) { + err := wd.SetConfig(ctx, c.providerConfig(ctx)) - err = wd.SetConfig(providerCfg) - if err != nil { - t.Fatalf("Error setting test config: %s", err) - } - err = runProviderCommand(t, func() error { - return wd.Init() - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) - if err != nil { - t.Fatalf("Error running init: %s", err.Error()) - return + if err != nil { + logging.HelperResourceError(ctx, + "TestCase error setting provider configuration", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestCase error setting provider configuration: %s", err) + } + + err = runProviderCommand(ctx, t, func() error { + return wd.Init(ctx) + }, wd, providers) + + if err != nil { + logging.HelperResourceError(ctx, + "TestCase error running init", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestCase error running init: %s", err.Error()) + } } + logging.HelperResourceDebug(ctx, "Starting TestSteps") + // use this to track last step succesfully applied // acts as default for import tests var appliedCfg string - for i, step := range c.Steps { + for stepIndex, step := range c.Steps { + stepNumber := stepIndex + 1 // 1-based indexing for humans + ctx = logging.TestStepNumberContext(ctx, stepNumber) + + logging.HelperResourceDebug(ctx, "Starting TestStep") + if step.PreConfig != nil { + logging.HelperResourceDebug(ctx, "Calling TestStep PreConfig") step.PreConfig() + logging.HelperResourceDebug(ctx, "Called TestStep PreConfig") } if step.SkipFunc != nil { + logging.HelperResourceDebug(ctx, "Calling TestStep SkipFunc") + skip, err := step.SkipFunc() if err != nil { - t.Fatal(err) + logging.HelperResourceError(ctx, + "Error calling TestStep SkipFunc", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("Error calling TestStep SkipFunc: %s", err.Error()) } + + logging.HelperResourceDebug(ctx, "Called TestStep SkipFunc") + if skip { - log.Printf("[WARN] Skipping step %d/%d", i+1, len(c.Steps)) + t.Logf("Skipping step %d/%d due to SkipFunc", stepNumber, len(c.Steps)) + logging.HelperResourceWarn(ctx, "Skipping TestStep due to SkipFunc") continue } } + if step.Config != "" && !step.Destroy && len(step.Taint) > 0 { + var state *terraform.State + + err := runProviderCommand(ctx, t, func() error { + var err error + + state, err = getState(ctx, t, wd) + + if err != nil { + return err + } + + return nil + }, wd, providers) + + if err != nil { + logging.HelperResourceError(ctx, + "TestStep error reading prior state before tainting resources", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestStep %d/%d error reading prior state before tainting resources: %s", stepNumber, len(c.Steps), err) + } + + err = testStepTaint(ctx, state, step) + + if err != nil { + logging.HelperResourceError(ctx, + "TestStep error tainting resources", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestStep %d/%d error tainting resources: %s", stepNumber, len(c.Steps), err) + } + } + + if step.hasProviders(ctx) { + providers = &providerFactories{ + legacy: sdkProviderFactories(c.ProviderFactories).merge(step.ProviderFactories), + protov5: protov5ProviderFactories(c.ProtoV5ProviderFactories).merge(step.ProtoV5ProviderFactories), + protov6: protov6ProviderFactories(c.ProtoV6ProviderFactories).merge(step.ProtoV6ProviderFactories), + } + + providerCfg := step.providerConfig(ctx) + + err := wd.SetConfig(ctx, providerCfg) + + if err != nil { + logging.HelperResourceError(ctx, + "TestStep error setting provider configuration", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestStep %d/%d error setting test provider configuration: %s", stepNumber, len(c.Steps), err) + } + + err = runProviderCommand( + ctx, + t, + func() error { + return wd.Init(ctx) + }, + wd, + providers, + ) + + if err != nil { + logging.HelperResourceError(ctx, + "TestStep error running init", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("TestStep %d/%d running init: %s", stepNumber, len(c.Steps), err.Error()) + return + } + } + if step.ImportState { - err := testStepNewImportState(t, c, helper, wd, step, appliedCfg) + logging.HelperResourceTrace(ctx, "TestStep is ImportState mode") + + err := testStepNewImportState(ctx, t, helper, wd, step, appliedCfg, providers) if step.ExpectError != nil { + logging.HelperResourceDebug(ctx, "Checking TestStep ExpectError") if err == nil { - t.Fatalf("Step %d/%d error running import: expected an error but got none", i+1, len(c.Steps)) + logging.HelperResourceError(ctx, + "Error running import: expected an error but got none", + ) + t.Fatalf("Step %d/%d error running import: expected an error but got none", stepNumber, len(c.Steps)) } if !step.ExpectError.MatchString(err.Error()) { - t.Fatalf("Step %d/%d error running import, expected an error with pattern (%s), no match on: %s", i+1, len(c.Steps), step.ExpectError.String(), err) + logging.HelperResourceError(ctx, + fmt.Sprintf("Error running import: expected an error with pattern (%s)", step.ExpectError.String()), + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("Step %d/%d error running import, expected an error with pattern (%s), no match on: %s", stepNumber, len(c.Steps), step.ExpectError.String(), err) } } else { if err != nil && c.ErrorCheck != nil { + logging.HelperResourceDebug(ctx, "Calling TestCase ErrorCheck") err = c.ErrorCheck(err) + logging.HelperResourceDebug(ctx, "Called TestCase ErrorCheck") } if err != nil { - t.Fatalf("Step %d/%d error running import: %s", i+1, len(c.Steps), err) + logging.HelperResourceError(ctx, + "Error running import", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("Step %d/%d error running import: %s", stepNumber, len(c.Steps), err) } } + + logging.HelperResourceDebug(ctx, "Finished TestStep") + continue } if step.Config != "" { - err := testStepNewConfig(t, c, wd, step) + logging.HelperResourceTrace(ctx, "TestStep is Config mode") + + err := testStepNewConfig(ctx, t, c, wd, step, providers) if step.ExpectError != nil { + logging.HelperResourceDebug(ctx, "Checking TestStep ExpectError") + if err == nil { - t.Fatalf("Step %d/%d, expected an error but got none", i+1, len(c.Steps)) + logging.HelperResourceError(ctx, + "Expected an error but got none", + ) + t.Fatalf("Step %d/%d, expected an error but got none", stepNumber, len(c.Steps)) } if !step.ExpectError.MatchString(err.Error()) { - t.Fatalf("Step %d/%d, expected an error with pattern, no match on: %s", i+1, len(c.Steps), err) + logging.HelperResourceError(ctx, + fmt.Sprintf("Expected an error with pattern (%s)", step.ExpectError.String()), + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("Step %d/%d, expected an error with pattern, no match on: %s", stepNumber, len(c.Steps), err) } } else { if err != nil && c.ErrorCheck != nil { + logging.HelperResourceDebug(ctx, "Calling TestCase ErrorCheck") + err = c.ErrorCheck(err) + + logging.HelperResourceDebug(ctx, "Called TestCase ErrorCheck") } if err != nil { - t.Fatalf("Step %d/%d error: %s", i+1, len(c.Steps), err) + logging.HelperResourceError(ctx, + "Unexpected error", + map[string]interface{}{logging.KeyError: err}, + ) + t.Fatalf("Step %d/%d error: %s", stepNumber, len(c.Steps), err) } } + appliedCfg = step.Config + + logging.HelperResourceDebug(ctx, "Finished TestStep") + continue } - t.Fatal("Unsupported test mode") + t.Fatalf("Step %d/%d, unsupported test mode", stepNumber, len(c.Steps)) } } -func getState(t testing.T, wd *plugintest.WorkingDir) (*terraform.State, error) { +func getState(ctx context.Context, t testing.T, wd *plugintest.WorkingDir) (*terraform.State, error) { t.Helper() - jsonState, err := wd.State() + jsonState, err := wd.State(ctx) if err != nil { return nil, err } @@ -188,7 +340,7 @@ func planIsEmpty(plan *tfjson.Plan) bool { return true } -func testIDRefresh(c TestCase, t testing.T, wd *plugintest.WorkingDir, step TestStep, r *terraform.ResourceState) error { +func testIDRefresh(ctx context.Context, t testing.T, c TestCase, wd *plugintest.WorkingDir, step TestStep, r *terraform.ResourceState, providers *providerFactories) error { t.Helper() spewConf := spew.NewDefaultConfig() @@ -202,36 +354,29 @@ func testIDRefresh(c TestCase, t testing.T, wd *plugintest.WorkingDir, step Test // Temporarily set the config to a minimal provider config for the refresh // test. After the refresh we can reset it. - cfg, err := testProviderConfig(c) - if err != nil { - return err - } - err = wd.SetConfig(cfg) + err := wd.SetConfig(ctx, c.providerConfig(ctx)) if err != nil { t.Fatalf("Error setting import test config: %s", err) } defer func() { - err = wd.SetConfig(step.Config) + err = wd.SetConfig(ctx, step.Config) if err != nil { t.Fatalf("Error resetting test config: %s", err) } }() // Refresh! - err = runProviderCommand(t, func() error { - err = wd.Refresh() + err = runProviderCommand(ctx, t, func() error { + err = wd.Refresh(ctx) if err != nil { t.Fatalf("Error running terraform refresh: %s", err) } - state, err = getState(t, wd) + state, err = getState(ctx, t, wd) if err != nil { return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return err } @@ -246,6 +391,11 @@ func testIDRefresh(c TestCase, t testing.T, wd *plugintest.WorkingDir, step Test } actual := actualR.Primary.Attributes expected := r.Primary.Attributes + + if len(c.IDRefreshIgnore) > 0 { + logging.HelperResourceTrace(ctx, fmt.Sprintf("Using TestCase IDRefreshIgnore: %v", c.IDRefreshIgnore)) + } + // Remove fields we're ignoring for _, v := range c.IDRefreshIgnore { for k := range actual { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go index 9900cc3965df..09d18c364527 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go @@ -1,56 +1,31 @@ package resource import ( + "context" "errors" "fmt" tfjson "github.com/hashicorp/terraform-json" testing "github.com/mitchellh/go-testing-interface" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func testStepNewConfig(t testing.T, c TestCase, wd *plugintest.WorkingDir, step TestStep) error { +func testStepNewConfig(ctx context.Context, t testing.T, c TestCase, wd *plugintest.WorkingDir, step TestStep, providers *providerFactories) error { t.Helper() - var idRefreshCheck *terraform.ResourceState - idRefresh := c.IDRefreshName != "" - - if !step.Destroy { - var state *terraform.State - var err error - err = runProviderCommand(t, func() error { - state, err = getState(t, wd) - if err != nil { - return err - } - return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) - if err != nil { - return err - } - if err := testStepTaint(state, step); err != nil { - return fmt.Errorf("Error when tainting resources: %s", err) - } - } - - err := wd.SetConfig(step.Config) + err := wd.SetConfig(ctx, step.Config) if err != nil { return fmt.Errorf("Error setting config: %w", err) } // require a refresh before applying // failing to do this will result in data sources not being updated - err = runProviderCommand(t, func() error { - return wd.Refresh() - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + err = runProviderCommand(ctx, t, func() error { + return wd.Refresh(ctx) + }, wd, providers) if err != nil { return fmt.Errorf("Error running pre-apply refresh: %w", err) } @@ -59,16 +34,15 @@ func testStepNewConfig(t testing.T, c TestCase, wd *plugintest.WorkingDir, step // subsequent Apply, and use the follow-up Plan that checks for // permadiffs if !step.PlanOnly { + logging.HelperResourceDebug(ctx, "Running Terraform CLI plan and apply") + // Plan! - err := runProviderCommand(t, func() error { + err := runProviderCommand(ctx, t, func() error { if step.Destroy { - return wd.CreateDestroyPlan() + return wd.CreateDestroyPlan(ctx) } - return wd.CreatePlan() - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + return wd.CreatePlan(ctx) + }, wd, providers) if err != nil { return fmt.Errorf("Error running pre-apply plan: %w", err) } @@ -77,27 +51,21 @@ func testStepNewConfig(t testing.T, c TestCase, wd *plugintest.WorkingDir, step // that the destroy steps can verify their behavior in the // check function var stateBeforeApplication *terraform.State - err = runProviderCommand(t, func() error { - stateBeforeApplication, err = getState(t, wd) + err = runProviderCommand(ctx, t, func() error { + stateBeforeApplication, err = getState(ctx, t, wd) if err != nil { return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving pre-apply state: %w", err) } // Apply the diff, creating real resources - err = runProviderCommand(t, func() error { - return wd.Apply() - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + err = runProviderCommand(ctx, t, func() error { + return wd.Apply(ctx) + }, wd, providers) if err != nil { if step.Destroy { return fmt.Errorf("Error running destroy: %w", err) @@ -107,22 +75,21 @@ func testStepNewConfig(t testing.T, c TestCase, wd *plugintest.WorkingDir, step // Get the new state var state *terraform.State - err = runProviderCommand(t, func() error { - state, err = getState(t, wd) + err = runProviderCommand(ctx, t, func() error { + state, err = getState(ctx, t, wd) if err != nil { return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving state after apply: %w", err) } // Run any configured checks if step.Check != nil { + logging.HelperResourceTrace(ctx, "Using TestStep Check") + state.IsBinaryDrivenTest = true if step.Destroy { if err := step.Check(stateBeforeApplication); err != nil { @@ -137,44 +104,36 @@ func testStepNewConfig(t testing.T, c TestCase, wd *plugintest.WorkingDir, step } // Test for perpetual diffs by performing a plan, a refresh, and another plan + logging.HelperResourceDebug(ctx, "Running Terraform CLI plan to check for perpetual differences") // do a plan - err = runProviderCommand(t, func() error { + err = runProviderCommand(ctx, t, func() error { if step.Destroy { - return wd.CreateDestroyPlan() + return wd.CreateDestroyPlan(ctx) } - return wd.CreatePlan() - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + return wd.CreatePlan(ctx) + }, wd, providers) if err != nil { return fmt.Errorf("Error running post-apply plan: %w", err) } var plan *tfjson.Plan - err = runProviderCommand(t, func() error { + err = runProviderCommand(ctx, t, func() error { var err error - plan, err = wd.SavedPlan() + plan, err = wd.SavedPlan(ctx) return err - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving post-apply plan: %w", err) } if !planIsEmpty(plan) && !step.ExpectNonEmptyPlan { var stdout string - err = runProviderCommand(t, func() error { + err = runProviderCommand(ctx, t, func() error { var err error - stdout, err = wd.SavedPlanRawStdout() + stdout, err = wd.SavedPlanRawStdout(ctx) return err - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving formatted plan output: %w", err) } @@ -183,39 +142,30 @@ func testStepNewConfig(t testing.T, c TestCase, wd *plugintest.WorkingDir, step // do a refresh if !step.Destroy || (step.Destroy && !step.PreventPostDestroyRefresh) { - err := runProviderCommand(t, func() error { - return wd.Refresh() - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + err := runProviderCommand(ctx, t, func() error { + return wd.Refresh(ctx) + }, wd, providers) if err != nil { return fmt.Errorf("Error running post-apply refresh: %w", err) } } // do another plan - err = runProviderCommand(t, func() error { + err = runProviderCommand(ctx, t, func() error { if step.Destroy { - return wd.CreateDestroyPlan() + return wd.CreateDestroyPlan(ctx) } - return wd.CreatePlan() - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + return wd.CreatePlan(ctx) + }, wd, providers) if err != nil { return fmt.Errorf("Error running second post-apply plan: %w", err) } - err = runProviderCommand(t, func() error { + err = runProviderCommand(ctx, t, func() error { var err error - plan, err = wd.SavedPlan() + plan, err = wd.SavedPlan(ctx) return err - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving second post-apply plan: %w", err) } @@ -223,14 +173,11 @@ func testStepNewConfig(t testing.T, c TestCase, wd *plugintest.WorkingDir, step // check if plan is empty if !planIsEmpty(plan) && !step.ExpectNonEmptyPlan { var stdout string - err = runProviderCommand(t, func() error { + err = runProviderCommand(ctx, t, func() error { var err error - stdout, err = wd.SavedPlanRawStdout() + stdout, err = wd.SavedPlanRawStdout(ctx) return err - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { return fmt.Errorf("Error retrieving formatted second plan output: %w", err) } @@ -242,21 +189,29 @@ func testStepNewConfig(t testing.T, c TestCase, wd *plugintest.WorkingDir, step // ID-ONLY REFRESH // If we've never checked an id-only refresh and our state isn't // empty, find the first resource and test it. - var state *terraform.State - err = runProviderCommand(t, func() error { - state, err = getState(t, wd) + if c.IDRefreshName != "" { + logging.HelperResourceTrace(ctx, "Using TestCase IDRefreshName") + + var state *terraform.State + + err = runProviderCommand(ctx, t, func() error { + state, err = getState(ctx, t, wd) + if err != nil { + return err + } + return nil + }, wd, providers) + if err != nil { return err } - return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) - if err != nil { - return err - } - if idRefresh && idRefreshCheck == nil && !state.Empty() { + + if state.Empty() { + return nil + } + + var idRefreshCheck *terraform.ResourceState + // Find the first non-nil resource in the state for _, m := range state.Modules { if len(m.Resources) > 0 { @@ -275,7 +230,7 @@ func testStepNewConfig(t testing.T, c TestCase, wd *plugintest.WorkingDir, step // this fails. If refresh isn't read-only, then this will have // caught a different bug. if idRefreshCheck != nil { - if err := testIDRefresh(c, t, wd, step, idRefreshCheck); err != nil { + if err := testIDRefresh(ctx, t, c, wd, step, idRefreshCheck, providers); err != nil { return fmt.Errorf( "[ERROR] Test: ID-only test failed: %s", err) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go index a38c3c7dc421..ec61b055f3a2 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go @@ -1,17 +1,20 @@ package resource import ( + "context" + "fmt" "reflect" "strings" "github.com/davecgh/go-spew/spew" testing "github.com/mitchellh/go-testing-interface" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func testStepNewImportState(t testing.T, c TestCase, helper *plugintest.Helper, wd *plugintest.WorkingDir, step TestStep, cfg string) error { +func testStepNewImportState(ctx context.Context, t testing.T, helper *plugintest.Helper, wd *plugintest.WorkingDir, step TestStep, cfg string, providers *providerFactories) error { t.Helper() spewConf := spew.NewDefaultConfig() @@ -24,16 +27,13 @@ func testStepNewImportState(t testing.T, c TestCase, helper *plugintest.Helper, // get state from check sequence var state *terraform.State var err error - err = runProviderCommand(t, func() error { - state, err = getState(t, wd) + err = runProviderCommand(ctx, t, func() error { + state, err = getState(ctx, t, wd) if err != nil { return err } return nil - }, wd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, wd, providers) if err != nil { t.Fatalf("Error getting state: %s", err) } @@ -42,73 +42,89 @@ func testStepNewImportState(t testing.T, c TestCase, helper *plugintest.Helper, var importId string switch { case step.ImportStateIdFunc != nil: + logging.HelperResourceTrace(ctx, "Using TestStep ImportStateIdFunc for import identifier") + var err error + + logging.HelperResourceDebug(ctx, "Calling TestStep ImportStateIdFunc") + importId, err = step.ImportStateIdFunc(state) + if err != nil { t.Fatal(err) } + + logging.HelperResourceDebug(ctx, "Called TestStep ImportStateIdFunc") case step.ImportStateId != "": + logging.HelperResourceTrace(ctx, "Using TestStep ImportStateId for import identifier") + importId = step.ImportStateId default: + logging.HelperResourceTrace(ctx, "Using resource identifier for import identifier") + resource, err := testResource(step, state) if err != nil { t.Fatal(err) } importId = resource.Primary.ID } - importId = step.ImportStateIdPrefix + importId + + if step.ImportStateIdPrefix != "" { + logging.HelperResourceTrace(ctx, "Prepending TestStep ImportStateIdPrefix for import identifier") + + importId = step.ImportStateIdPrefix + importId + } + + logging.HelperResourceTrace(ctx, fmt.Sprintf("Using import identifier: %s", importId)) // Create working directory for import tests if step.Config == "" { + logging.HelperResourceTrace(ctx, "Using prior TestStep Config for import") + step.Config = cfg if step.Config == "" { t.Fatal("Cannot import state with no specified config") } } - importWd := helper.RequireNewWorkingDir(t) + importWd := helper.RequireNewWorkingDir(ctx, t) defer importWd.Close() - err = importWd.SetConfig(step.Config) + err = importWd.SetConfig(ctx, step.Config) if err != nil { t.Fatalf("Error setting test config: %s", err) } - err = runProviderCommand(t, func() error { - return importWd.Init() - }, importWd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + logging.HelperResourceDebug(ctx, "Running Terraform CLI init and import") + + err = runProviderCommand(ctx, t, func() error { + return importWd.Init(ctx) + }, importWd, providers) if err != nil { t.Fatalf("Error running init: %s", err) } - err = runProviderCommand(t, func() error { - return importWd.Import(step.ResourceName, importId) - }, importWd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + err = runProviderCommand(ctx, t, func() error { + return importWd.Import(ctx, step.ResourceName, importId) + }, importWd, providers) if err != nil { return err } var importState *terraform.State - err = runProviderCommand(t, func() error { - importState, err = getState(t, importWd) + err = runProviderCommand(ctx, t, func() error { + importState, err = getState(ctx, t, importWd) if err != nil { return err } return nil - }, importWd, providerFactories{ - legacy: c.ProviderFactories, - protov5: c.ProtoV5ProviderFactories, - protov6: c.ProtoV6ProviderFactories}) + }, importWd, providers) if err != nil { t.Fatalf("Error getting state: %s", err) } // Go through the imported state and verify if step.ImportStateCheck != nil { + logging.HelperResourceTrace(ctx, "Using TestStep ImportStateCheck") + var states []*terraform.InstanceState for _, r := range importState.RootModule().Resources { if r.Primary != nil { @@ -117,20 +133,27 @@ func testStepNewImportState(t testing.T, c TestCase, helper *plugintest.Helper, states = append(states, is) } } + + logging.HelperResourceDebug(ctx, "Calling TestStep ImportStateCheck") + if err := step.ImportStateCheck(states); err != nil { t.Fatal(err) } + + logging.HelperResourceDebug(ctx, "Called TestStep ImportStateCheck") } // Verify that all the states match if step.ImportStateVerify { - new := importState.RootModule().Resources - old := state.RootModule().Resources + logging.HelperResourceTrace(ctx, "Using TestStep ImportStateVerify") + + newResources := importState.RootModule().Resources + oldResources := state.RootModule().Resources - for _, r := range new { + for _, r := range newResources { // Find the existing resource var oldR *terraform.ResourceState - for r2Key, r2 := range old { + for r2Key, r2 := range oldResources { // Ensure that we do not match against data sources as they // cannot be imported and are not what we want to verify. // Mode is not present in ResourceState so we use the @@ -144,7 +167,7 @@ func testStepNewImportState(t testing.T, c TestCase, helper *plugintest.Helper, break } } - if oldR == nil { + if oldR == nil || oldR.Primary == nil { t.Fatalf( "Failed state verification, resource with ID %s not found", r.Primary.ID) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_sets.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_sets.go index ada1d6e7eca3..9b1d57c66651 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_sets.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_sets.go @@ -14,25 +14,46 @@ const ( sentinelIndex = "*" ) -// TestCheckTypeSetElemNestedAttrs is a TestCheckFunc that accepts a resource -// name, an attribute path, which should use the sentinel value '*' for indexing -// into a TypeSet. The function verifies that an element matches the whole value -// map. +// TestCheckTypeSetElemNestedAttrs ensures a subset map of values is stored in +// state for the given name and key combination of attributes nested under a +// list or set block. Use this TestCheckFunc in preference over non-set +// variants to simplify testing code and ensure compatibility with indicies, +// which can easily change with schema changes. State value checking is only +// recommended for testing Computed attributes and attribute defaults. // -// You may check for unset keys, however this will also match keys set to empty -// string. Please provide a map with at least 1 non-empty value. +// For managed resources, the name parameter is a combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". // -// map[string]string{ -// "key1": "value", -// "key2": "", -// } +// resource "myprovider_thing" "example" { ... } // -// Use this function over SDK provided TestCheckFunctions when validating a -// TypeSet where its elements are a nested object with their own attrs/values. +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the sentinel value '*' to replace the element indexing into +// a list or set. The sentinel value can be used for each list or set index, if +// there are multiple lists or sets in the attribute path. +// +// The values parameter is the map of attribute names to attribute values +// expected to be nested under the list or set. +// +// You may check for unset nested attributes, however this will also match keys +// set to an empty string. Use a map with at least 1 non-empty value. // -// Please note, if the provided value map is not granular enough, there exists -// the possibility you match an element you were not intending to, in the TypeSet. -// Provide a full mapping of attributes to be sure the unique element exists. +// map[string]string{ +// "key1": "value", +// "key2": "", +// } +// +// If the values map is not granular enough, it is possible to match an element +// you were not intending to in the set. Provide the most complete mapping of +// attributes possible to be sure the unique element exists. func TestCheckTypeSetElemNestedAttrs(name, attr string, values map[string]string) TestCheckFunc { return func(s *terraform.State) error { is, err := primaryInstanceState(s, name) @@ -64,17 +85,47 @@ func TestCheckTypeSetElemNestedAttrs(name, attr string, values map[string]string } } -// TestMatchTypeSetElemNestedAttrs is a TestCheckFunc similar to TestCheckTypeSetElemNestedAttrs -// with the exception that it verifies that an element matches a *regexp.Regexp. +// TestMatchTypeSetElemNestedAttrs ensures a subset map of values, compared by +// regular expressions, is stored in state for the given name and key +// combination of attributes nested under a list or set block. Use this +// TestCheckFunc in preference over non-set variants to simplify testing code +// and ensure compatibility with indicies, which can easily change with schema +// changes. State value checking is only recommended for testing Computed +// attributes and attribute defaults. +// +// For managed resources, the name parameter is a combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". +// +// resource "myprovider_thing" "example" { ... } +// +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the sentinel value '*' to replace the element indexing into +// a list or set. The sentinel value can be used for each list or set index, if +// there are multiple lists or sets in the attribute path. // -// You may check for unset keys, however this will also match keys set to empty -// string. Please provide a map with at least 1 non-empty value e.g. +// The values parameter is the map of attribute names to regular expressions +// for matching attribute values expected to be nested under the list or set. // -// map[string]*regexp.Regexp{ -// "key1": regexp.MustCompile("value"), -// "key2": regexp.MustCompile(""), -// } +// You may check for unset nested attributes, however this will also match keys +// set to an empty string. Use a map with at least 1 non-empty value. // +// map[string]*regexp.Regexp{ +// "key1": regexp.MustCompile(`^value`), +// "key2": regexp.MustCompile(`^$`), +// } +// +// If the values map is not granular enough, it is possible to match an element +// you were not intending to in the set. Provide the most complete mapping of +// attributes possible to be sure the unique element exists. func TestMatchTypeSetElemNestedAttrs(name, attr string, values map[string]*regexp.Regexp) TestCheckFunc { return func(s *terraform.State) error { is, err := primaryInstanceState(s, name) @@ -113,6 +164,39 @@ func TestMatchTypeSetElemNestedAttrs(name, attr string, values map[string]*regex // // Use this function over SDK provided TestCheckFunctions when validating a // TypeSet where its elements are a simple value + +// TestCheckTypeSetElemAttr ensures a specific value is stored in state for the +// given name and key combination under a list or set. Use this TestCheckFunc +// in preference over non-set variants to simplify testing code and ensure +// compatibility with indicies, which can easily change with schema changes. +// State value checking is only recommended for testing Computed attributes and +// attribute defaults. +// +// For managed resources, the name parameter is a combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". +// +// resource "myprovider_thing" "example" { ... } +// +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the sentinel value '*' to replace the element indexing into +// a list or set. The sentinel value can be used for each list or set index, if +// there are multiple lists or sets in the attribute path. +// +// The value parameter is the stringified data to check at the given key. Use +// the following attribute type rules to set the value: +// +// - Boolean: "false" or "true". +// - Float/Integer: Stringified number, such as "1.2" or "123". +// - String: No conversion necessary. func TestCheckTypeSetElemAttr(name, attr, value string) TestCheckFunc { return func(s *terraform.State) error { is, err := primaryInstanceState(s, name) @@ -129,12 +213,32 @@ func TestCheckTypeSetElemAttr(name, attr, value string) TestCheckFunc { } } -// TestCheckTypeSetElemAttrPair is a TestCheckFunc that verifies a pair of name/key -// combinations are equal where the first uses the sentinel value to index into a -// TypeSet. +// TestCheckTypeSetElemAttrPair ensures value equality in state between the +// first given name and key combination and the second name and key +// combination. State value checking is only recommended for testing Computed +// attributes and attribute defaults. +// +// For managed resources, the name parameter is a combination of the resource +// type, a period (.), and the name label. The name for the below example +// configuration would be "myprovider_thing.example". +// +// resource "myprovider_thing" "example" { ... } +// +// For data sources, the name parameter is a combination of the keyword "data", +// a period (.), the data source type, a period (.), and the name label. The +// name for the below example configuration would be +// "data.myprovider_thing.example". +// +// data "myprovider_thing" "example" { ... } +// +// The first and second names may use any combination of managed resources +// and/or data sources. // -// E.g., TestCheckTypeSetElemAttrPair("aws_autoscaling_group.bar", "availability_zones.*", "data.aws_availability_zones.available", "names.0") -// E.g., TestCheckTypeSetElemAttrPair("aws_spot_fleet_request.bar", "launch_specification.*.instance_type", "data.data.aws_ec2_instance_type_offering.available", "instance_type") +// The key parameter is an attribute path in Terraform CLI 0.11 and earlier +// "flatmap" syntax. Keys start with the attribute name of a top-level +// attribute. Use the sentinel value '*' to replace the element indexing into +// a list or set. The sentinel value can be used for each list or set index, if +// there are multiple lists or sets in the attribute path. func TestCheckTypeSetElemAttrPair(nameFirst, keyFirst, nameSecond, keySecond string) TestCheckFunc { return func(s *terraform.State) error { isFirst, err := primaryInstanceState(s, nameFirst) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_providers.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_providers.go new file mode 100644 index 000000000000..35d4a9bf57fb --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_providers.go @@ -0,0 +1,48 @@ +package resource + +import ( + "context" + "fmt" + "strings" +) + +// providerConfig takes the list of providers in a TestStep and returns a +// config with only empty provider blocks. This is useful for Import, where no +// config is provided, but the providers must be defined. +func (s TestStep) providerConfig(_ context.Context) string { + var providerBlocks, requiredProviderBlocks strings.Builder + + for name, externalProvider := range s.ExternalProviders { + providerBlocks.WriteString(fmt.Sprintf("provider %q {}\n", name)) + + if externalProvider.Source == "" && externalProvider.VersionConstraint == "" { + continue + } + + requiredProviderBlocks.WriteString(fmt.Sprintf(" %s = {\n", name)) + + if externalProvider.Source != "" { + requiredProviderBlocks.WriteString(fmt.Sprintf(" source = %q\n", externalProvider.Source)) + } + + if externalProvider.VersionConstraint != "" { + requiredProviderBlocks.WriteString(fmt.Sprintf(" version = %q\n", externalProvider.VersionConstraint)) + } + + requiredProviderBlocks.WriteString(" }\n") + } + + if requiredProviderBlocks.Len() > 0 { + return fmt.Sprintf(` +terraform { + required_providers { +%[1]s + } +} + +%[2]s +`, strings.TrimSuffix(requiredProviderBlocks.String(), "\n"), providerBlocks.String()) + } + + return providerBlocks.String() +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_validate.go new file mode 100644 index 000000000000..e9239328c690 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/teststep_validate.go @@ -0,0 +1,99 @@ +package resource + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" +) + +// testStepValidateRequest contains data for the (TestStep).validate() method. +type testStepValidateRequest struct { + // StepNumber is the index of the TestStep in the TestCase.Steps. + StepNumber int + + // TestCaseHasProviders is enabled if the TestCase has set any of + // ExternalProviders, ProtoV5ProviderFactories, ProtoV6ProviderFactories, + // or ProviderFactories. + TestCaseHasProviders bool +} + +// hasProviders returns true if the TestStep has set any of the +// ExternalProviders, ProtoV5ProviderFactories, ProtoV6ProviderFactories, or +// ProviderFactories fields. +func (s TestStep) hasProviders(_ context.Context) bool { + if len(s.ExternalProviders) > 0 { + return true + } + + if len(s.ProtoV5ProviderFactories) > 0 { + return true + } + + if len(s.ProtoV6ProviderFactories) > 0 { + return true + } + + if len(s.ProviderFactories) > 0 { + return true + } + + return false +} + +// validate ensures the TestStep is valid based on the following criteria: +// +// - Config or ImportState is set. +// - Providers are not specified (ExternalProviders, +// ProtoV5ProviderFactories, ProtoV6ProviderFactories, ProviderFactories) +// if specified at the TestCase level. +// - Providers are specified (ExternalProviders, ProtoV5ProviderFactories, +// ProtoV6ProviderFactories, ProviderFactories) if not specified at the +// TestCase level. +// - No overlapping ExternalProviders and ProviderFactories entries +// - ResourceName is not empty when ImportState is true, ImportStateIdFunc +// is not set, and ImportStateId is not set. +// +func (s TestStep) validate(ctx context.Context, req testStepValidateRequest) error { + ctx = logging.TestStepNumberContext(ctx, req.StepNumber) + + logging.HelperResourceTrace(ctx, "Validating TestStep") + + if s.Config == "" && !s.ImportState { + err := fmt.Errorf("TestStep missing Config or ImportState") + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + for name := range s.ExternalProviders { + if _, ok := s.ProviderFactories[name]; ok { + err := fmt.Errorf("TestStep provider %q set in both ExternalProviders and ProviderFactories", name) + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + } + + hasProviders := s.hasProviders(ctx) + + if req.TestCaseHasProviders && hasProviders { + err := fmt.Errorf("Providers must only be specified either at the TestCase or TestStep level") + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + if !req.TestCaseHasProviders && !hasProviders { + err := fmt.Errorf("Providers must be specified at the TestCase level or in all TestStep") + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + + if s.ImportState { + if s.ImportStateId == "" && s.ImportStateIdFunc == nil && s.ResourceName == "" { + err := fmt.Errorf("TestStep ImportState must be specified with ImportStateId, ImportStateIdFunc, or ResourceName") + logging.HelperResourceError(ctx, "TestStep validation error", map[string]interface{}{logging.KeyError: err}) + return err + } + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader.go index c7721bcd366f..855bc4028a16 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader.go @@ -171,7 +171,7 @@ func addrToSchema(addr []string, schemaMap map[string]*Schema) []*Schema { // "foo.#" for a list "foo" and that the indexes are "foo.0", "foo.1", etc. // after that point. func readListField( - r FieldReader, addr []string, schema *Schema) (FieldReadResult, error) { + r FieldReader, addr []string) (FieldReadResult, error) { addrPadded := make([]string, len(addr)+1) copy(addrPadded, addr) addrPadded[len(addrPadded)-1] = "#" diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_config.go index 3f1f5e8ab1bf..cd4a993a35ce 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_config.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_config.go @@ -100,7 +100,7 @@ func (r *ConfigFieldReader) readField( case TypeBool, TypeFloat, TypeInt, TypeString: return r.readPrimitive(k, schema) case TypeList: - return readListField(&nestedConfigFieldReader{r}, address, schema) + return readListField(&nestedConfigFieldReader{r}, address) case TypeMap: return r.readMap(k, schema) case TypeSet: @@ -203,7 +203,7 @@ func (r *ConfigFieldReader) readMap(k string, schema *Schema) (FieldReadResult, err := mapValuesToPrimitive(k, result, schema) if err != nil { - return FieldReadResult{}, nil + return FieldReadResult{}, nil //nolint:nilerr // Leave legacy flatmap handling } var value interface{} @@ -258,7 +258,7 @@ func (r *ConfigFieldReader) readSet( // Create the set that will be our result set := schema.ZeroValue().(*Set) - raw, err := readListField(&nestedConfigFieldReader{r}, address, schema) + raw, err := readListField(&nestedConfigFieldReader{r}, address) if err != nil { return FieldReadResult{}, err } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_diff.go index 642e7f32eb3e..ca3b714b1dd5 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_diff.go @@ -67,7 +67,7 @@ func (r *DiffFieldReader) ReadField(address []string) (FieldReadResult, error) { case TypeBool, TypeInt, TypeFloat, TypeString: res, err = r.readPrimitive(address, schema) case TypeList: - res, err = readListField(r, address, schema) + res, err = readListField(r, address) case TypeMap: res, err = r.readMap(address, schema) case TypeSet: @@ -128,7 +128,7 @@ func (r *DiffFieldReader) readMap( key := address[len(address)-1] err = mapValuesToPrimitive(key, result, schema) if err != nil { - return FieldReadResult{}, nil + return FieldReadResult{}, nil //nolint:nilerr // Leave legacy flatmap handling } var resultVal interface{} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_map.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_map.go index 092dd7f68599..6fa191522740 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_map.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_map.go @@ -24,7 +24,7 @@ func (r *MapFieldReader) ReadField(address []string) (FieldReadResult, error) { case TypeBool, TypeInt, TypeFloat, TypeString: return r.readPrimitive(address, schema) case TypeList: - return readListField(r, address, schema) + return readListField(r, address) case TypeMap: return r.readMap(k, schema) case TypeSet: @@ -63,7 +63,7 @@ func (r *MapFieldReader) readMap(k string, schema *Schema) (FieldReadResult, err err := mapValuesToPrimitive(k, result, schema) if err != nil { - return FieldReadResult{}, nil + return FieldReadResult{}, nil //nolint:nilerr // Leave legacy flatmap handling } var resultVal interface{} @@ -159,11 +159,8 @@ func (r *MapFieldReader) readSet( // "ports.1", but the "state" map might have those plus "ports.2". // We don't want "ports.2" countActual[idx] = struct{}{} - if len(countActual) >= countExpected { - return false - } - return true + return len(countActual) < countExpected }) if !completed && err != nil { return FieldReadResult{}, err diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_writer_map.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_writer_map.go index 85d05be4c3bc..39c708b27fa0 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_writer_map.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_writer_map.go @@ -100,13 +100,13 @@ func (w *MapFieldWriter) set(addr []string, value interface{}) error { case TypeBool, TypeInt, TypeFloat, TypeString: return w.setPrimitive(addr, value, schema) case TypeList: - return w.setList(addr, value, schema) + return w.setList(addr, value) case TypeMap: - return w.setMap(addr, value, schema) + return w.setMap(addr, value) case TypeSet: return w.setSet(addr, value, schema) case typeObject: - return w.setObject(addr, value, schema) + return w.setObject(addr, value) default: panic(fmt.Sprintf("Unknown type: %#v", schema.Type)) } @@ -114,8 +114,7 @@ func (w *MapFieldWriter) set(addr []string, value interface{}) error { func (w *MapFieldWriter) setList( addr []string, - v interface{}, - schema *Schema) error { + v interface{}) error { k := strings.Join(addr, ".") setElement := func(idx string, value interface{}) error { addrCopy := make([]string, len(addr), len(addr)+1) @@ -148,7 +147,7 @@ func (w *MapFieldWriter) setList( if err != nil { for i := range vs { is := strconv.FormatInt(int64(i), 10) - setElement(is, nil) + _ = setElement(is, nil) // best effort; error returned below } return err @@ -160,8 +159,7 @@ func (w *MapFieldWriter) setList( func (w *MapFieldWriter) setMap( addr []string, - value interface{}, - schema *Schema) error { + value interface{}) error { k := strings.Join(addr, ".") v := reflect.ValueOf(value) vs := make(map[string]interface{}) @@ -176,7 +174,7 @@ func (w *MapFieldWriter) setMap( return fmt.Errorf("%s: must be a map", k) } if v.Type().Key().Kind() != reflect.String { - return fmt.Errorf("%s: keys must strings", k) + return fmt.Errorf("%s: keys must be strings", k) } for _, mk := range v.MapKeys() { mv := v.MapIndex(mk) @@ -207,8 +205,7 @@ func (w *MapFieldWriter) setMap( func (w *MapFieldWriter) setObject( addr []string, - value interface{}, - schema *Schema) error { + value interface{}) error { // Set the entire object. First decode into a proper structure var v map[string]interface{} if err := mapstructure.Decode(value, &v); err != nil { @@ -228,11 +225,13 @@ func (w *MapFieldWriter) setObject( } if err != nil { for k1 := range v { - w.set(append(addrCopy, k1), nil) + _ = w.set(append(addrCopy, k1), nil) // best effort; error returned below } + + return err } - return err + return nil } func (w *MapFieldWriter) setPrimitive( @@ -271,7 +270,7 @@ func (w *MapFieldWriter) setPrimitive( if err := mapstructure.Decode(v, &n); err != nil { return fmt.Errorf("%s: %s", k, err) } - set = strconv.FormatFloat(float64(n), 'G', -1, 64) + set = strconv.FormatFloat(n, 'G', -1, 64) default: return fmt.Errorf("Unknown type: %#v", schema.Type) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/grpc_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/grpc_provider.go index 4ed1253decfb..ec3ed07c1021 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/grpc_provider.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/grpc_provider.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "log" "strconv" "sync" @@ -16,12 +15,15 @@ import ( "github.com/hashicorp/terraform-plugin-go/tftypes" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plans/objchange" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -const newExtraKey = "_new_extra_shim" +const ( + newExtraKey = "_new_extra_shim" +) func NewGRPCProviderServer(p *Provider) *GRPCProviderServer { return &GRPCProviderServer{ @@ -53,6 +55,7 @@ func mergeStop(ctx context.Context, cancel context.CancelFunc, stopCh chan struc // It creates a goroutine to wait for the server stop and propagates // cancellation to the derived grpc context. func (s *GRPCProviderServer) StopContext(ctx context.Context) context.Context { + ctx = logging.InitContext(ctx) s.stopMu.Lock() defer s.stopMu.Unlock() @@ -61,7 +64,10 @@ func (s *GRPCProviderServer) StopContext(ctx context.Context) context.Context { return stoppable } -func (s *GRPCProviderServer) GetProviderSchema(_ context.Context, req *tfprotov5.GetProviderSchemaRequest) (*tfprotov5.GetProviderSchemaResponse, error) { +func (s *GRPCProviderServer) GetProviderSchema(ctx context.Context, req *tfprotov5.GetProviderSchemaRequest) (*tfprotov5.GetProviderSchemaResponse, error) { + ctx = logging.InitContext(ctx) + + logging.HelperSchemaTrace(ctx, "Getting provider schema") resp := &tfprotov5.GetProviderSchemaResponse{ ResourceSchemas: make(map[string]*tfprotov5.Schema), @@ -69,24 +75,28 @@ func (s *GRPCProviderServer) GetProviderSchema(_ context.Context, req *tfprotov5 } resp.Provider = &tfprotov5.Schema{ - Block: convert.ConfigSchemaToProto(s.getProviderSchemaBlock()), + Block: convert.ConfigSchemaToProto(ctx, s.getProviderSchemaBlock()), } resp.ProviderMeta = &tfprotov5.Schema{ - Block: convert.ConfigSchemaToProto(s.getProviderMetaSchemaBlock()), + Block: convert.ConfigSchemaToProto(ctx, s.getProviderMetaSchemaBlock()), } for typ, res := range s.provider.ResourcesMap { + logging.HelperSchemaTrace(ctx, "Found resource type", map[string]interface{}{logging.KeyResourceType: typ}) + resp.ResourceSchemas[typ] = &tfprotov5.Schema{ Version: int64(res.SchemaVersion), - Block: convert.ConfigSchemaToProto(res.CoreConfigSchema()), + Block: convert.ConfigSchemaToProto(ctx, res.CoreConfigSchema()), } } for typ, dat := range s.provider.DataSourcesMap { + logging.HelperSchemaTrace(ctx, "Found data source type", map[string]interface{}{logging.KeyDataSourceType: typ}) + resp.DataSourceSchemas[typ] = &tfprotov5.Schema{ Version: int64(dat.SchemaVersion), - Block: convert.ConfigSchemaToProto(dat.CoreConfigSchema()), + Block: convert.ConfigSchemaToProto(ctx, dat.CoreConfigSchema()), } } @@ -111,14 +121,17 @@ func (s *GRPCProviderServer) getDatasourceSchemaBlock(name string) *configschema return dat.CoreConfigSchema() } -func (s *GRPCProviderServer) PrepareProviderConfig(_ context.Context, req *tfprotov5.PrepareProviderConfigRequest) (*tfprotov5.PrepareProviderConfigResponse, error) { +func (s *GRPCProviderServer) PrepareProviderConfig(ctx context.Context, req *tfprotov5.PrepareProviderConfigRequest) (*tfprotov5.PrepareProviderConfigResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.PrepareProviderConfigResponse{} + logging.HelperSchemaTrace(ctx, "Preparing provider configuration") + schemaBlock := s.getProviderSchemaBlock() configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -156,8 +169,7 @@ func (s *GRPCProviderServer) PrepareProviderConfig(_ context.Context, req *tfpro // find a default value if it exists def, err := attrSchema.DefaultValue() if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("error getting default for %q: %s", getAttr.Name, err)) - return val, err + return val, fmt.Errorf("error getting default for %q: %w", getAttr.Name, err) } // no default @@ -171,41 +183,43 @@ func (s *GRPCProviderServer) PrepareProviderConfig(_ context.Context, req *tfpro // helper/schema used to allow setting "" to a bool if val.Type() == cty.Bool && tmpVal.RawEquals(cty.StringVal("")) { // return a warning about the conversion - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, "provider set empty string as default value for bool "+getAttr.Name) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, "provider set empty string as default value for bool "+getAttr.Name) tmpVal = cty.False } val, err = ctyconvert.Convert(tmpVal, val.Type()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("error setting default for %q: %s", getAttr.Name, err)) + return val, fmt.Errorf("error setting default for %q: %w", getAttr.Name, err) } - return val, err + return val, nil }) if err != nil { - // any error here was already added to the diagnostics + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } configVal, err = schemaBlock.CoerceValue(configVal) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(configVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + if err := validateConfigNulls(ctx, configVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, s.provider.Validate(config)) + logging.HelperSchemaTrace(ctx, "Calling downstream") + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, s.provider.Validate(config)) + logging.HelperSchemaTrace(ctx, "Called downstream") preparedConfigMP, err := msgpack.Marshal(configVal, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -214,54 +228,61 @@ func (s *GRPCProviderServer) PrepareProviderConfig(_ context.Context, req *tfpro return resp, nil } -func (s *GRPCProviderServer) ValidateResourceTypeConfig(_ context.Context, req *tfprotov5.ValidateResourceTypeConfigRequest) (*tfprotov5.ValidateResourceTypeConfigResponse, error) { +func (s *GRPCProviderServer) ValidateResourceTypeConfig(ctx context.Context, req *tfprotov5.ValidateResourceTypeConfigRequest) (*tfprotov5.ValidateResourceTypeConfigResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.ValidateResourceTypeConfigResponse{} schemaBlock := s.getResourceSchemaBlock(req.TypeName) configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, s.provider.ValidateResource(req.TypeName, config)) + logging.HelperSchemaTrace(ctx, "Calling downstream") + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, s.provider.ValidateResource(req.TypeName, config)) + logging.HelperSchemaTrace(ctx, "Called downstream") return resp, nil } -func (s *GRPCProviderServer) ValidateDataSourceConfig(_ context.Context, req *tfprotov5.ValidateDataSourceConfigRequest) (*tfprotov5.ValidateDataSourceConfigResponse, error) { +func (s *GRPCProviderServer) ValidateDataSourceConfig(ctx context.Context, req *tfprotov5.ValidateDataSourceConfigRequest) (*tfprotov5.ValidateDataSourceConfigResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.ValidateDataSourceConfigResponse{} schemaBlock := s.getDatasourceSchemaBlock(req.TypeName) configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(configVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + if err := validateConfigNulls(ctx, configVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, s.provider.ValidateDataSource(req.TypeName, config)) + logging.HelperSchemaTrace(ctx, "Calling downstream") + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, s.provider.ValidateDataSource(req.TypeName, config)) + logging.HelperSchemaTrace(ctx, "Called downstream") return resp, nil } func (s *GRPCProviderServer) UpgradeResourceState(ctx context.Context, req *tfprotov5.UpgradeResourceStateRequest) (*tfprotov5.UpgradeResourceStateResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.UpgradeResourceStateResponse{} res, ok := s.provider.ResourcesMap[req.TypeName] if !ok { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) return resp, nil } schemaBlock := s.getResourceSchemaBlock(req.TypeName) @@ -275,9 +296,11 @@ func (s *GRPCProviderServer) UpgradeResourceState(ctx context.Context, req *tfpr // We first need to upgrade a flatmap state if it exists. // There should never be both a JSON and Flatmap state in the request. case len(req.RawState.Flatmap) > 0: + logging.HelperSchemaTrace(ctx, "Upgrading flatmap state") + jsonMap, version, err = s.upgradeFlatmapState(ctx, version, req.RawState.Flatmap, res) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } // if there's a JSON state, we need to decode it. @@ -288,29 +311,31 @@ func (s *GRPCProviderServer) UpgradeResourceState(ctx context.Context, req *tfpr err = json.Unmarshal(req.RawState.JSON, &jsonMap) } if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } default: - log.Println("[DEBUG] no state provided to upgrade") + logging.HelperSchemaDebug(ctx, "no state provided to upgrade") return resp, nil } // complete the upgrade of the JSON states + logging.HelperSchemaTrace(ctx, "Upgrading JSON state") + jsonMap, err = s.upgradeJSONState(ctx, version, jsonMap, res) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } // The provider isn't required to clean out removed fields - s.removeAttributes(jsonMap, schemaBlock.ImpliedType()) + s.removeAttributes(ctx, jsonMap, schemaBlock.ImpliedType()) // now we need to turn the state into the default json representation, so // that it can be re-decoded using the actual schema. val, err := JSONMapToStateValue(jsonMap, schemaBlock) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -319,7 +344,7 @@ func (s *GRPCProviderServer) UpgradeResourceState(ctx context.Context, req *tfpr // First we need to CoerceValue to ensure that all object types match. val, err = schemaBlock.CoerceValue(val) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } // Normalize the value and fill in any missing blocks. @@ -328,7 +353,7 @@ func (s *GRPCProviderServer) UpgradeResourceState(ctx context.Context, req *tfpr // encode the final state to the expected msgpack format newStateMP, err := msgpack.Marshal(val, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -341,7 +366,7 @@ func (s *GRPCProviderServer) UpgradeResourceState(ctx context.Context, req *tfpr // map[string]interface{}. // upgradeFlatmapState returns the json map along with the corresponding schema // version. -func (s *GRPCProviderServer) upgradeFlatmapState(ctx context.Context, version int, m map[string]string, res *Resource) (map[string]interface{}, int, error) { +func (s *GRPCProviderServer) upgradeFlatmapState(_ context.Context, version int, m map[string]string, res *Resource) (map[string]interface{}, int, error) { // this will be the version we've upgraded so, defaulting to the given // version in case no migration was called. upgradedVersion := version @@ -433,7 +458,7 @@ func (s *GRPCProviderServer) upgradeJSONState(ctx context.Context, version int, // Remove any attributes no longer present in the schema, so that the json can // be correctly decoded. -func (s *GRPCProviderServer) removeAttributes(v interface{}, ty cty.Type) { +func (s *GRPCProviderServer) removeAttributes(ctx context.Context, v interface{}, ty cty.Type) { // we're only concerned with finding maps that corespond to object // attributes switch v := v.(type) { @@ -442,7 +467,7 @@ func (s *GRPCProviderServer) removeAttributes(v interface{}, ty cty.Type) { if ty.IsListType() || ty.IsSetType() { eTy := ty.ElementType() for _, eV := range v { - s.removeAttributes(eV, eTy) + s.removeAttributes(ctx, eV, eTy) } } return @@ -451,20 +476,20 @@ func (s *GRPCProviderServer) removeAttributes(v interface{}, ty cty.Type) { if ty.IsMapType() { eTy := ty.ElementType() for _, eV := range v { - s.removeAttributes(eV, eTy) + s.removeAttributes(ctx, eV, eTy) } return } if ty == cty.DynamicPseudoType { - log.Printf("[DEBUG] ignoring dynamic block: %#v\n", v) + logging.HelperSchemaDebug(ctx, "ignoring dynamic block", map[string]interface{}{"block": v}) return } if !ty.IsObjectType() { // This shouldn't happen, and will fail to decode further on, so // there's no need to handle it here. - log.Printf("[WARN] unexpected type %#v for map in json state", ty) + logging.HelperSchemaWarn(ctx, "unexpected type for map in JSON state", map[string]interface{}{"type": ty}) return } @@ -472,17 +497,21 @@ func (s *GRPCProviderServer) removeAttributes(v interface{}, ty cty.Type) { for attr, attrV := range v { attrTy, ok := attrTypes[attr] if !ok { - log.Printf("[DEBUG] attribute %q no longer present in schema", attr) + logging.HelperSchemaDebug(ctx, "attribute no longer present in schema", map[string]interface{}{"attribute": attr}) delete(v, attr) continue } - s.removeAttributes(attrV, attrTy) + s.removeAttributes(ctx, attrV, attrTy) } } } -func (s *GRPCProviderServer) StopProvider(_ context.Context, _ *tfprotov5.StopProviderRequest) (*tfprotov5.StopProviderResponse, error) { +func (s *GRPCProviderServer) StopProvider(ctx context.Context, _ *tfprotov5.StopProviderRequest) (*tfprotov5.StopProviderResponse, error) { + ctx = logging.InitContext(ctx) + + logging.HelperSchemaTrace(ctx, "Stopping provider") + s.stopMu.Lock() defer s.stopMu.Unlock() @@ -491,25 +520,28 @@ func (s *GRPCProviderServer) StopProvider(_ context.Context, _ *tfprotov5.StopPr // reset the stop signal s.stopCh = make(chan struct{}) + logging.HelperSchemaTrace(ctx, "Stopped provider") + return &tfprotov5.StopProviderResponse{}, nil } func (s *GRPCProviderServer) ConfigureProvider(ctx context.Context, req *tfprotov5.ConfigureProviderRequest) (*tfprotov5.ConfigureProviderResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.ConfigureProviderResponse{} schemaBlock := s.getProviderSchemaBlock() configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } s.provider.TerraformVersion = req.TerraformVersion // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(configVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + if err := validateConfigNulls(ctx, configVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -520,13 +552,18 @@ func (s *GRPCProviderServer) ConfigureProvider(ctx context.Context, req *tfproto // function. Ideally a provider should migrate to the context aware API that receives // request scoped contexts, however this is a large undertaking for very large providers. ctxHack := context.WithValue(ctx, StopContextKey, s.StopContext(context.Background())) + + logging.HelperSchemaTrace(ctx, "Calling downstream") diags := s.provider.Configure(ctxHack, config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, diags) + logging.HelperSchemaTrace(ctx, "Called downstream") + + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, diags) return resp, nil } func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *tfprotov5.ReadResourceRequest) (*tfprotov5.ReadResourceResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.ReadResourceResponse{ // helper/schema did previously handle private data during refresh, but // core is now going to expect this to be maintained in order to @@ -536,20 +573,20 @@ func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *tfprotov5.Re res, ok := s.provider.ResourcesMap[req.TypeName] if !ok { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) return resp, nil } schemaBlock := s.getResourceSchemaBlock(req.TypeName) stateVal, err := msgpack.Unmarshal(req.CurrentState.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } instanceState, err := res.ShimInstanceStateFromValue(stateVal) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } instanceState.RawState = stateVal @@ -557,7 +594,7 @@ func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *tfprotov5.Re private := make(map[string]interface{}) if len(req.Private) > 0 { if err := json.Unmarshal(req.Private, &private); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } } @@ -567,14 +604,14 @@ func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *tfprotov5.Re if pmSchemaBlock != nil && req.ProviderMeta != nil { providerSchemaVal, err := msgpack.Unmarshal(req.ProviderMeta.MsgPack, pmSchemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } instanceState.ProviderMeta = providerSchemaVal } newInstanceState, diags := res.RefreshWithoutUpgrade(ctx, instanceState, s.provider.Meta()) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, diags) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, diags) if diags.HasError() { return resp, nil } @@ -585,7 +622,7 @@ func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *tfprotov5.Re // to see a null value (in the cty sense) in that case. newStateMP, err := msgpack.Marshal(cty.NullVal(schemaBlock.ImpliedType()), schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) } resp.NewState = &tfprotov5.DynamicValue{ MsgPack: newStateMP, @@ -598,7 +635,7 @@ func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *tfprotov5.Re newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(newInstanceState.Attributes, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -607,7 +644,7 @@ func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *tfprotov5.Re newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -619,6 +656,7 @@ func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *tfprotov5.Re } func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprotov5.PlanResourceChangeRequest) (*tfprotov5.PlanResourceChangeResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.PlanResourceChangeResponse{} // This is a signal to Terraform Core that we're doing the best we can to @@ -627,18 +665,18 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot // forward to any new SDK implementations, since setting it prevents us // from catching certain classes of provider bug that can lead to // confusing downstream errors. - resp.UnsafeToUseLegacyTypeSystem = true + resp.UnsafeToUseLegacyTypeSystem = true //nolint:staticcheck res, ok := s.provider.ResourcesMap[req.TypeName] if !ok { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) return resp, nil } schemaBlock := s.getResourceSchemaBlock(req.TypeName) priorStateVal, err := msgpack.Unmarshal(req.PriorState.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -646,7 +684,7 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot proposedNewStateVal, err := msgpack.Unmarshal(req.ProposedNewState.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -659,13 +697,13 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } priorState, err := res.ShimInstanceStateFromValue(priorStateVal) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } priorState.RawState = priorStateVal @@ -674,7 +712,7 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot priorPrivate := make(map[string]interface{}) if len(req.PriorPrivate) > 0 { if err := json.Unmarshal(req.PriorPrivate, &priorPrivate); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } } @@ -685,15 +723,15 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot if pmSchemaBlock != nil && req.ProviderMeta != nil { providerSchemaVal, err := msgpack.Unmarshal(req.ProviderMeta.MsgPack, pmSchemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } priorState.ProviderMeta = providerSchemaVal } // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(proposedNewStateVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + if err := validateConfigNulls(ctx, proposedNewStateVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -702,7 +740,7 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot diff, err := res.SimpleDiff(ctx, priorState, cfg, s.provider.Meta()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -734,22 +772,27 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot // now we need to apply the diff to the prior state, so get the planned state plannedAttrs, err := diff.Apply(priorState.Attributes, schemaBlock) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) + return resp, nil + } + plannedStateVal, err := hcl2shim.HCL2ValueFromFlatmap(plannedAttrs, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } plannedStateVal, err = schemaBlock.CoerceValue(plannedStateVal) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } plannedStateVal = normalizeNullValues(plannedStateVal, proposedNewStateVal, false) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -777,7 +820,7 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot plannedMP, err := msgpack.Marshal(plannedStateVal, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } resp.PlannedState = &tfprotov5.DynamicValue{ @@ -787,12 +830,12 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot // encode any timeouts into the diff Meta t := &ResourceTimeout{} if err := t.ConfigDecode(res, cfg); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } if err := t.DiffEncode(diff); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -815,7 +858,7 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot // the Meta field gets encoded into PlannedPrivate plannedPrivate, err := json.Marshal(privateMap) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } resp.PlannedPrivate = plannedPrivate @@ -842,7 +885,7 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot requiresReplace, err := hcl2shim.RequiresReplace(requiresNew, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -855,6 +898,7 @@ func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *tfprot } func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *tfprotov5.ApplyResourceChangeRequest) (*tfprotov5.ApplyResourceChangeResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.ApplyResourceChangeResponse{ // Start with the existing state as a fallback NewState: req.PriorState, @@ -862,39 +906,39 @@ func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *tfpro res, ok := s.provider.ResourcesMap[req.TypeName] if !ok { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) return resp, nil } schemaBlock := s.getResourceSchemaBlock(req.TypeName) priorStateVal, err := msgpack.Unmarshal(req.PriorState.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } plannedStateVal, err := msgpack.Unmarshal(req.PlannedState.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } priorState, err := res.ShimInstanceStateFromValue(priorStateVal) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } private := make(map[string]interface{}) if len(req.PlannedPrivate) > 0 { if err := json.Unmarshal(req.PlannedPrivate, &private); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } } @@ -916,7 +960,7 @@ func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *tfpro } else { diff, err = DiffFromValues(ctx, priorStateVal, plannedStateVal, configVal, stripResourceModifiers(res)) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } } @@ -968,14 +1012,14 @@ func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *tfpro if pmSchemaBlock != nil && req.ProviderMeta != nil { providerSchemaVal, err := msgpack.Unmarshal(req.ProviderMeta.MsgPack, pmSchemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } priorState.ProviderMeta = providerSchemaVal } newInstanceState, diags := res.Apply(ctx, priorState, diff, s.provider.Meta()) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, diags) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, diags) newStateVal := cty.NullVal(schemaBlock.ImpliedType()) @@ -985,7 +1029,7 @@ func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *tfpro if destroy || newInstanceState == nil || newInstanceState.Attributes == nil || newInstanceState.ID == "" { newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } resp.NewState = &tfprotov5.DynamicValue{ @@ -998,7 +1042,7 @@ func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *tfpro // entire object, even if the new state was nil. newStateVal, err = StateValueFromInstanceState(newInstanceState, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -1008,7 +1052,7 @@ func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *tfpro newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } resp.NewState = &tfprotov5.DynamicValue{ @@ -1017,7 +1061,7 @@ func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *tfpro meta, err := json.Marshal(newInstanceState.Meta) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } resp.Private = meta @@ -1028,12 +1072,13 @@ func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *tfpro // forward to any new SDK implementations, since setting it prevents us // from catching certain classes of provider bug that can lead to // confusing downstream errors. - resp.UnsafeToUseLegacyTypeSystem = true + resp.UnsafeToUseLegacyTypeSystem = true //nolint:staticcheck return resp, nil } func (s *GRPCProviderServer) ImportResourceState(ctx context.Context, req *tfprotov5.ImportResourceStateRequest) (*tfprotov5.ImportResourceStateResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.ImportResourceStateResponse{} info := &terraform.InstanceInfo{ @@ -1042,7 +1087,7 @@ func (s *GRPCProviderServer) ImportResourceState(ctx context.Context, req *tfpro newInstanceStates, err := s.provider.ImportState(ctx, info, req.ID) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -1058,7 +1103,7 @@ func (s *GRPCProviderServer) ImportResourceState(ctx context.Context, req *tfpro schemaBlock := s.getResourceSchemaBlock(resourceType) newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(is.Attributes, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -1067,13 +1112,13 @@ func (s *GRPCProviderServer) ImportResourceState(ctx context.Context, req *tfpro newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } meta, err := json.Marshal(is.Meta) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -1092,19 +1137,20 @@ func (s *GRPCProviderServer) ImportResourceState(ctx context.Context, req *tfpro } func (s *GRPCProviderServer) ReadDataSource(ctx context.Context, req *tfprotov5.ReadDataSourceRequest) (*tfprotov5.ReadDataSourceResponse, error) { + ctx = logging.InitContext(ctx) resp := &tfprotov5.ReadDataSourceResponse{} schemaBlock := s.getDatasourceSchemaBlock(req.TypeName) configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(configVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + if err := validateConfigNulls(ctx, configVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -1114,12 +1160,12 @@ func (s *GRPCProviderServer) ReadDataSource(ctx context.Context, req *tfprotov5. // the old behavior res, ok := s.provider.DataSourcesMap[req.TypeName] if !ok { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown data source: %s", req.TypeName)) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("unknown data source: %s", req.TypeName)) return resp, nil } diff, err := res.Diff(ctx, nil, config, s.provider.Meta()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -1131,14 +1177,14 @@ func (s *GRPCProviderServer) ReadDataSource(ctx context.Context, req *tfprotov5. // now we can get the new complete data source newInstanceState, diags := res.ReadDataApply(ctx, diff, s.provider.Meta()) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, diags) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, diags) if diags.HasError() { return resp, nil } newStateVal, err := StateValueFromInstanceState(newInstanceState, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } @@ -1146,7 +1192,7 @@ func (s *GRPCProviderServer) ReadDataSource(ctx context.Context, req *tfprotov5. newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err) return resp, nil } resp.State = &tfprotov5.DynamicValue{ @@ -1439,7 +1485,7 @@ func normalizeNullValues(dst, src cty.Value, apply bool) cty.Value { // appears in a list-like attribute (list, set, tuple) will present a nil value // to helper/schema which can panic. Return an error to the user in this case, // indicating the attribute with the null value. -func validateConfigNulls(v cty.Value, path cty.Path) []*tfprotov5.Diagnostic { +func validateConfigNulls(ctx context.Context, v cty.Value, path cty.Path) []*tfprotov5.Diagnostic { var diags []*tfprotov5.Diagnostic if v.IsNull() || !v.IsKnown() { return diags @@ -1468,8 +1514,8 @@ func validateConfigNulls(v cty.Value, path cty.Path) []*tfprotov5.Diagnostic { continue } - d := validateConfigNulls(ev, append(path, cty.IndexStep{Key: kv})) - diags = convert.AppendProtoDiag(diags, d) + d := validateConfigNulls(ctx, ev, append(path, cty.IndexStep{Key: kv})) + diags = convert.AppendProtoDiag(ctx, diags, d) } case v.Type().IsMapType() || v.Type().IsObjectType(): @@ -1483,8 +1529,8 @@ func validateConfigNulls(v cty.Value, path cty.Path) []*tfprotov5.Diagnostic { case v.Type().IsObjectType(): step = cty.GetAttrStep{Name: kv.AsString()} } - d := validateConfigNulls(ev, append(path, step)) - diags = convert.AppendProtoDiag(diags, d) + d := validateConfigNulls(ctx, ev, append(path, step)) + diags = convert.AppendProtoDiag(ctx, diags, d) } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/provider.go index 0d1f8e23c051..91a21b389089 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/provider.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/provider.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/terraform-plugin-go/tfprotov5" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/meta" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) @@ -265,7 +266,7 @@ func (p *Provider) Configure(ctx context.Context, c *terraform.ResourceConfig) d } if p.configured { - log.Printf("[WARN] Previously configured provider being re-configured. This can cause issues in concurrent testing if the configurations are not equal.") + logging.HelperSchemaWarn(ctx, "Previously configured provider being re-configured. This can cause issues in concurrent testing if the configurations are not equal.") } sm := schemaMap(p.Schema) @@ -378,11 +379,15 @@ func (p *Provider) ImportState( results := []*ResourceData{data} if r.Importer.State != nil || r.Importer.StateContext != nil { var err error + logging.HelperSchemaTrace(ctx, "Calling downstream") + if r.Importer.StateContext != nil { results, err = r.Importer.StateContext(ctx, data, p.meta) } else { results, err = r.Importer.State(data, p.meta) } + logging.HelperSchemaTrace(ctx, "Called downstream") + if err != nil { return nil, err } @@ -391,6 +396,21 @@ func (p *Provider) ImportState( // Convert the results to InstanceState values and return it states := make([]*terraform.InstanceState, len(results)) for i, r := range results { + if r == nil { + return nil, fmt.Errorf("The provider returned a missing resource during ImportResourceState. " + + "This is generally a bug in the resource implementation for import. " + + "Resource import code should return an error for missing resources and skip returning a missing or empty ResourceData. " + + "Please report this to the provider developers.") + } + + if r.Id() == "" { + return nil, fmt.Errorf("The provider returned a resource missing an identifier during ImportResourceState. " + + "This is generally a bug in the resource implementation for import. " + + "Resource import code should not call d.SetId(\"\") or create an empty ResourceData. " + + "If the resource is missing, instead return an error. " + + "Please report this to the provider developers.") + } + states[i] = r.State() } @@ -398,10 +418,10 @@ func (p *Provider) ImportState( // isn't obvious so we circumvent that with a friendlier error. for _, s := range states { if s == nil { - return nil, fmt.Errorf( - "nil entry in ImportState results. This is always a bug with\n" + - "the resource that is being imported. Please report this as\n" + - "a bug to Terraform.") + return nil, fmt.Errorf("The provider returned a missing resource during ImportResourceState. " + + "This is generally a bug in the resource implementation for import. " + + "Resource import code should return an error for missing resources. " + + "Please report this to the provider developers.") } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource.go index b0a8631caa79..5b40bec8964c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource.go @@ -4,12 +4,12 @@ import ( "context" "errors" "fmt" - "log" "strconv" "github.com/hashicorp/go-cty/cty" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) @@ -31,35 +31,44 @@ var ReservedResourceFields = []string{ "provisioner", } -// Resource represents a thing in Terraform that has a set of configurable -// attributes and a lifecycle (create, read, update, delete). +// Resource is an abstraction for multiple Terraform concepts: // -// The Resource schema is an abstraction that allows provider writers to -// worry only about CRUD operations while off-loading validation, diff -// generation, etc. to this higher level library. +// - Managed Resource: An infrastructure component with a schema, lifecycle +// operations such as create, read, update, and delete +// (CRUD), and optional implementation details such as +// import support, upgrade state support, and difference +// customization. +// - Data Resource: Also known as a data source. An infrastructure component +// with a schema and only the read lifecycle operation. +// - Block: When implemented within a Schema type Elem field, a configuration +// block that contains nested schema information such as attributes +// and blocks. // -// In spite of the name, this struct is not used only for terraform resources, -// but also for data sources. In the case of data sources, the Create, -// Update and Delete functions must not be provided. +// To fully implement managed resources, the Provider type ResourcesMap field +// should include a reference to an implementation of this type. To fully +// implement data resources, the Provider type DataSourcesMap field should +// include a reference to an implementation of this type. +// +// Each field further documents any constraints based on the Terraform concept +// being implemented. type Resource struct { - // Schema is the schema for the configuration of this resource. - // - // The keys of this map are the configuration keys, and the values - // describe the schema of the configuration value. + // Schema is the structure and type information for this component. This + // field is required for all Resource concepts. // - // The schema is used to represent both configurable data as well - // as data that might be computed in the process of creating this - // resource. + // The keys of this map are the names used in a practitioner configuration, + // such as the attribute or block name. The values describe the structure + // and type information of that attribute or block. Schema map[string]*Schema // SchemaVersion is the version number for this resource's Schema - // definition. The current SchemaVersion stored in the state for each - // resource. Provider authors can increment this version number - // when Schema semantics change. If the State's SchemaVersion is less than - // the current SchemaVersion, the InstanceState is yielded to the - // MigrateState callback, where the provider can make whatever changes it - // needs to update the state to be compatible to the latest version of the - // Schema. + // definition. This field is only valid when the Resource is a managed + // resource. + // + // The current SchemaVersion stored in the state for each resource. + // Provider authors can increment this version number when Schema semantics + // change in an incompatible manner. If the state's SchemaVersion is less + // than the current SchemaVersion, the MigrateState and StateUpgraders + // functionality is executed to upgrade the state information. // // When unset, SchemaVersion defaults to 0, so provider authors can start // their Versioning at any integer >= 1 @@ -67,6 +76,7 @@ type Resource struct { // MigrateState is responsible for updating an InstanceState with an old // version to the format expected by the current version of the Schema. + // This field is only valid when the Resource is a managed resource. // // It is called during Refresh if the State's stored SchemaVersion is less // than the current SchemaVersion of the Resource. @@ -86,7 +96,8 @@ type Resource struct { // StateUpgraders contains the functions responsible for upgrading an // existing state with an old schema version to a newer schema. It is // called specifically by Terraform when the stored schema version is less - // than the current SchemaVersion of the Resource. + // than the current SchemaVersion of the Resource. This field is only valid + // when the Resource is a managed resource. // // StateUpgraders map specific schema versions to a StateUpgrader // function. The registered versions are expected to be ordered, @@ -95,57 +106,261 @@ type Resource struct { // MigrateState. StateUpgraders []StateUpgrader - // The functions below are the CRUD operations for this resource. + // Create is called when the provider must create a new instance of a + // managed resource. This field is only valid when the Resource is a + // managed resource. Only one of Create, CreateContext, or + // CreateWithoutTimeout should be implemented. // - // Deprecated: Please use the context aware equivalents instead. Only one of - // the operations or context aware equivalent can be set, not both. + // The *ResourceData parameter contains the plan and state data for this + // managed resource instance. The available data in the Get* methods is the + // the proposed state, which is the merged data of the practitioner + // configuration and any CustomizeDiff field logic. + // + // The SetId method must be called with a non-empty value for the managed + // resource instance to be properly saved into the Terraform state and + // avoid a "inconsistent result after apply" error. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The error return parameter, if not nil, will be converted into an error + // diagnostic when passed back to Terraform. + // + // Deprecated: Use CreateContext or CreateWithoutTimeout instead. This + // implementation does not support request cancellation initiated by + // Terraform, such as a system or practitioner sending SIGINT (Ctrl-c). + // This implementation also does not support warning diagnostics. Create CreateFunc - // Deprecated: Please use the context aware equivalents instead. + + // Read is called when the provider must refresh the state of a managed + // resource instance or data resource instance. This field is only valid + // when the Resource is a managed resource or data resource. Only one of + // Read, ReadContext, or ReadWithoutTimeout should be implemented. + // + // The *ResourceData parameter contains the state data for this managed + // resource instance or data resource instance. + // + // Managed resources can signal to Terraform that the managed resource + // instance no longer exists and potentially should be recreated by calling + // the SetId method with an empty string ("") parameter and without + // returning an error. + // + // Data resources that are designed to return state for a singular + // infrastructure component should conventionally return an error if that + // infrastructure does not exist and omit any calls to the + // SetId method. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The error return parameter, if not nil, will be converted into an error + // diagnostic when passed back to Terraform. + // + // Deprecated: Use ReadContext or ReadWithoutTimeout instead. This + // implementation does not support request cancellation initiated by + // Terraform, such as a system or practitioner sending SIGINT (Ctrl-c). + // This implementation also does not support warning diagnostics. Read ReadFunc - // Deprecated: Please use the context aware equivalents instead. + + // Update is called when the provider must update an instance of a + // managed resource. This field is only valid when the Resource is a + // managed resource. Only one of Update, UpdateContext, or + // UpdateWithoutTimeout should be implemented. + // + // This implementation is optional. If omitted, all Schema must enable + // the ForceNew field and any practitioner changes that would have + // caused and update will instead destroy and recreate the infrastructure + // compontent. + // + // The *ResourceData parameter contains the plan and state data for this + // managed resource instance. The available data in the Get* methods is the + // the proposed state, which is the merged data of the prior state, + // practitioner configuration, and any CustomizeDiff field logic. The + // available data for the GetChange* and HasChange* methods is the prior + // state and proposed state. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The error return parameter, if not nil, will be converted into an error + // diagnostic when passed back to Terraform. + // + // Deprecated: Use UpdateContext or UpdateWithoutTimeout instead. This + // implementation does not support request cancellation initiated by + // Terraform, such as a system or practitioner sending SIGINT (Ctrl-c). + // This implementation also does not support warning diagnostics. Update UpdateFunc - // Deprecated: Please use the context aware equivalents instead. + + // Delete is called when the provider must destroy the instance of a + // managed resource. This field is only valid when the Resource is a + // managed resource. Only one of Delete, DeleteContext, or + // DeleteWithoutTimeout should be implemented. + // + // The *ResourceData parameter contains the state data for this managed + // resource instance. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The error return parameter, if not nil, will be converted into an error + // diagnostic when passed back to Terraform. + // + // Deprecated: Use DeleteContext or DeleteWithoutTimeout instead. This + // implementation does not support request cancellation initiated by + // Terraform, such as a system or practitioner sending SIGINT (Ctrl-c). + // This implementation also does not support warning diagnostics. Delete DeleteFunc // Exists is a function that is called to check if a resource still - // exists. If this returns false, then this will affect the diff + // exists. This field is only valid when the Resource is a managed + // resource. + // + // If this returns false, then this will affect the diff // accordingly. If this function isn't set, it will not be called. You // can also signal existence in the Read method by calling d.SetId("") // if the Resource is no longer present and should be removed from state. // The *ResourceData passed to Exists should _not_ be modified. // - // Deprecated: ReadContext should be able to encapsulate the logic of Exists + // Deprecated: Remove in preference of ReadContext or ReadWithoutTimeout. Exists ExistsFunc - // The functions below are the CRUD operations for this resource. + // CreateContext is called when the provider must create a new instance of + // a managed resource. This field is only valid when the Resource is a + // managed resource. Only one of Create, CreateContext, or + // CreateWithoutTimeout should be implemented. + // + // The Context parameter stores SDK information, such as loggers and + // timeout deadlines. It also is wired to receive any cancellation from + // Terraform such as a system or practitioner sending SIGINT (Ctrl-c). // - // The only optional operation is Update. If Update is not - // implemented, then updates will not be supported for this resource. + // By default, CreateContext has a 20 minute timeout. Use the Timeouts + // field to control the default duration or implement CreateWithoutTimeout + // instead of CreateContext to remove the default timeout. // - // The ResourceData parameter in the functions below are used to - // query configuration and changes for the resource as well as to set - // the ID, computed data, etc. + // The *ResourceData parameter contains the plan and state data for this + // managed resource instance. The available data in the Get* methods is the + // the proposed state, which is the merged data of the practitioner + // configuration and any CustomizeDiff field logic. // - // The interface{} parameter is the result of the ConfigureFunc in - // the provider for this resource. If the provider does not define - // a ConfigureFunc, this will be nil. This parameter should be used - // to store API clients, configuration structures, etc. + // The SetId method must be called with a non-empty value for the managed + // resource instance to be properly saved into the Terraform state and + // avoid a "inconsistent result after apply" error. // - // These functions are passed a context configured to timeout with whatever - // was set as the timeout for this operation. Useful for forwarding on to - // backend SDK's that accept context. The context will also cancel if - // Terraform sends a cancellation signal. + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. // - // These functions return diagnostics, allowing developers to build - // a list of warnings and errors to be presented to the Terraform user. - // The AttributePath of those diagnostics should be built within these - // functions, please consult go-cty documentation for building a cty.Path + // The diagnostics return parameter, if not nil, can contain any + // combination and multiple of warning and/or error diagnostics. CreateContext CreateContextFunc - ReadContext ReadContextFunc + + // ReadContext is called when the provider must refresh the state of a managed + // resource instance or data resource instance. This field is only valid + // when the Resource is a managed resource or data resource. Only one of + // Read, ReadContext, or ReadWithoutTimeout should be implemented. + // + // The Context parameter stores SDK information, such as loggers and + // timeout deadlines. It also is wired to receive any cancellation from + // Terraform such as a system or practitioner sending SIGINT (Ctrl-c). + // + // By default, ReadContext has a 20 minute timeout. Use the Timeouts + // field to control the default duration or implement ReadWithoutTimeout + // instead of ReadContext to remove the default timeout. + // + // The *ResourceData parameter contains the state data for this managed + // resource instance or data resource instance. + // + // Managed resources can signal to Terraform that the managed resource + // instance no longer exists and potentially should be recreated by calling + // the SetId method with an empty string ("") parameter and without + // returning an error. + // + // Data resources that are designed to return state for a singular + // infrastructure component should conventionally return an error if that + // infrastructure does not exist and omit any calls to the + // SetId method. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The diagnostics return parameter, if not nil, can contain any + // combination and multiple of warning and/or error diagnostics. + ReadContext ReadContextFunc + + // UpdateContext is called when the provider must update an instance of a + // managed resource. This field is only valid when the Resource is a + // managed resource. Only one of Update, UpdateContext, or + // UpdateWithoutTimeout should be implemented. + // + // This implementation is optional. If omitted, all Schema must enable + // the ForceNew field and any practitioner changes that would have + // caused and update will instead destroy and recreate the infrastructure + // compontent. + // + // The Context parameter stores SDK information, such as loggers and + // timeout deadlines. It also is wired to receive any cancellation from + // Terraform such as a system or practitioner sending SIGINT (Ctrl-c). + // + // By default, UpdateContext has a 20 minute timeout. Use the Timeouts + // field to control the default duration or implement UpdateWithoutTimeout + // instead of UpdateContext to remove the default timeout. + // + // The *ResourceData parameter contains the plan and state data for this + // managed resource instance. The available data in the Get* methods is the + // the proposed state, which is the merged data of the prior state, + // practitioner configuration, and any CustomizeDiff field logic. The + // available data for the GetChange* and HasChange* methods is the prior + // state and proposed state. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The diagnostics return parameter, if not nil, can contain any + // combination and multiple of warning and/or error diagnostics. UpdateContext UpdateContextFunc + + // DeleteContext is called when the provider must destroy the instance of a + // managed resource. This field is only valid when the Resource is a + // managed resource. Only one of Delete, DeleteContext, or + // DeleteWithoutTimeout should be implemented. + // + // The Context parameter stores SDK information, such as loggers and + // timeout deadlines. It also is wired to receive any cancellation from + // Terraform such as a system or practitioner sending SIGINT (Ctrl-c). + // + // By default, DeleteContext has a 20 minute timeout. Use the Timeouts + // field to control the default duration or implement DeleteWithoutTimeout + // instead of DeleteContext to remove the default timeout. + // + // The *ResourceData parameter contains the state data for this managed + // resource instance. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The diagnostics return parameter, if not nil, can contain any + // combination and multiple of warning and/or error diagnostics. DeleteContext DeleteContextFunc - // CreateWithoutTimeout is equivalent to CreateContext with no context timeout. + // CreateWithoutTimeout is called when the provider must create a new + // instance of a managed resource. This field is only valid when the + // Resource is a managed resource. Only one of Create, CreateContext, or + // CreateWithoutTimeout should be implemented. // // Most resources should prefer CreateContext with properly implemented // operation timeout values, however there are cases where operation @@ -153,9 +368,34 @@ type Resource struct { // logic, such as a mutex, to prevent remote system errors. Since these // operations would have an indeterminate timeout that scales with the // number of resources, this allows resources to control timeout behavior. + // + // The Context parameter stores SDK information, such as loggers. It also + // is wired to receive any cancellation from Terraform such as a system or + // practitioner sending SIGINT (Ctrl-c). + // + // The *ResourceData parameter contains the plan and state data for this + // managed resource instance. The available data in the Get* methods is the + // the proposed state, which is the merged data of the practitioner + // configuration and any CustomizeDiff field logic. + // + // The SetId method must be called with a non-empty value for the managed + // resource instance to be properly saved into the Terraform state and + // avoid a "inconsistent result after apply" error. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The diagnostics return parameter, if not nil, can contain any + // combination and multiple of warning and/or error diagnostics. CreateWithoutTimeout CreateContextFunc - // ReadWithoutTimeout is equivalent to ReadContext with no context timeout. + // ReadWithoutTimeout is called when the provider must refresh the state of + // a managed resource instance or data resource instance. This field is + // only valid when the Resource is a managed resource or data resource. + // Only one of Read, ReadContext, or ReadWithoutTimeout should be + // implemented. // // Most resources should prefer ReadContext with properly implemented // operation timeout values, however there are cases where operation @@ -163,9 +403,37 @@ type Resource struct { // logic, such as a mutex, to prevent remote system errors. Since these // operations would have an indeterminate timeout that scales with the // number of resources, this allows resources to control timeout behavior. + // + // The Context parameter stores SDK information, such as loggers. It also + // is wired to receive any cancellation from Terraform such as a system or + // practitioner sending SIGINT (Ctrl-c). + // + // The *ResourceData parameter contains the state data for this managed + // resource instance or data resource instance. + // + // Managed resources can signal to Terraform that the managed resource + // instance no longer exists and potentially should be recreated by calling + // the SetId method with an empty string ("") parameter and without + // returning an error. + // + // Data resources that are designed to return state for a singular + // infrastructure component should conventionally return an error if that + // infrastructure does not exist and omit any calls to the + // SetId method. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The diagnostics return parameter, if not nil, can contain any + // combination and multiple of warning and/or error diagnostics. ReadWithoutTimeout ReadContextFunc - // UpdateWithoutTimeout is equivalent to UpdateContext with no context timeout. + // UpdateWithoutTimeout is called when the provider must update an instance + // of a managed resource. This field is only valid when the Resource is a + // managed resource. Only one of Update, UpdateContext, or + // UpdateWithoutTimeout should be implemented. // // Most resources should prefer UpdateContext with properly implemented // operation timeout values, however there are cases where operation @@ -173,9 +441,36 @@ type Resource struct { // logic, such as a mutex, to prevent remote system errors. Since these // operations would have an indeterminate timeout that scales with the // number of resources, this allows resources to control timeout behavior. + // + // This implementation is optional. If omitted, all Schema must enable + // the ForceNew field and any practitioner changes that would have + // caused and update will instead destroy and recreate the infrastructure + // compontent. + // + // The Context parameter stores SDK information, such as loggers. It also + // is wired to receive any cancellation from Terraform such as a system or + // practitioner sending SIGINT (Ctrl-c). + // + // The *ResourceData parameter contains the plan and state data for this + // managed resource instance. The available data in the Get* methods is the + // the proposed state, which is the merged data of the prior state, + // practitioner configuration, and any CustomizeDiff field logic. The + // available data for the GetChange* and HasChange* methods is the prior + // state and proposed state. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The diagnostics return parameter, if not nil, can contain any + // combination and multiple of warning and/or error diagnostics. UpdateWithoutTimeout UpdateContextFunc - // DeleteWithoutTimeout is equivalent to DeleteContext with no context timeout. + // DeleteWithoutTimeout is called when the provider must destroy the + // instance of a managed resource. This field is only valid when the + // Resource is a managed resource. Only one of Delete, DeleteContext, or + // DeleteWithoutTimeout should be implemented. // // Most resources should prefer DeleteContext with properly implemented // operation timeout values, however there are cases where operation @@ -183,15 +478,37 @@ type Resource struct { // logic, such as a mutex, to prevent remote system errors. Since these // operations would have an indeterminate timeout that scales with the // number of resources, this allows resources to control timeout behavior. + // + // The Context parameter stores SDK information, such as loggers. It also + // is wired to receive any cancellation from Terraform such as a system or + // practitioner sending SIGINT (Ctrl-c). + // + // The *ResourceData parameter contains the state data for this managed + // resource instance. + // + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. + // + // The diagnostics return parameter, if not nil, can contain any + // combination and multiple of warning and/or error diagnostics. DeleteWithoutTimeout DeleteContextFunc - // CustomizeDiff is a custom function for working with the diff that - // Terraform has created for this resource - it can be used to customize the - // diff that has been created, diff values not controlled by configuration, - // or even veto the diff altogether and abort the plan. It is passed a - // *ResourceDiff, a structure similar to ResourceData but lacking most write - // functions like Set, while introducing new functions that work with the - // diff such as SetNew, SetNewComputed, and ForceNew. + // CustomizeDiff is called after a difference (plan) has been generated + // for the Resource and allows for customizations, such as setting values + // not controlled by configuration, conditionally triggering resource + // recreation, or implementing additional validation logic to abort a plan. + // This field is only valid when the Resource is a managed resource. + // + // The Context parameter stores SDK information, such as loggers. It also + // is wired to receive any cancellation from Terraform such as a system or + // practitioner sending SIGINT (Ctrl-c). + // + // The *ResourceDiff parameter is similar to ResourceData but replaces the + // Set method with other difference handling methods, such as SetNew, + // SetNewComputed, and ForceNew. In general, only Schema with Computed + // enabled can have those methods executed against them. // // The phases Terraform runs this in, and the state available via functions // like Get and GetChange, are as follows: @@ -205,41 +522,60 @@ type Resource struct { // // This function needs to be resilient to support all scenarios. // - // For the most part, only computed fields can be customized by this - // function. + // The interface{} parameter is the result of the Provider type + // ConfigureFunc field execution. If the Provider does not define + // a ConfigureFunc, this will be nil. This parameter is conventionally + // used to store API clients and other provider instance specific data. // - // This function is only allowed on regular resources (not data sources). + // The error return parameter, if not nil, will be converted into an error + // diagnostic when passed back to Terraform. CustomizeDiff CustomizeDiffFunc - // Importer is the ResourceImporter implementation for this resource. + // Importer is called when the provider must import an instance of a + // managed resource. This field is only valid when the Resource is a + // managed resource. + // // If this is nil, then this resource does not support importing. If // this is non-nil, then it supports importing and ResourceImporter // must be validated. The validity of ResourceImporter is verified // by InternalValidate on Resource. Importer *ResourceImporter - // If non-empty, this string is emitted as a warning during Validate. + // If non-empty, this string is emitted as the details of a warning + // diagnostic during validation (validate, plan, and apply operations). + // This field is only valid when the Resource is a managed resource or + // data resource. DeprecationMessage string - // Timeouts allow users to specify specific time durations in which an - // operation should time out, to allow them to extend an action to suit their - // usage. For example, a user may specify a large Creation timeout for their - // AWS RDS Instance due to it's size, or restoring from a snapshot. - // Resource implementors must enable Timeout support by adding the allowed - // actions (Create, Read, Update, Delete, Default) to the Resource struct, and - // accessing them in the matching methods. + // Timeouts configures the default time duration allowed before a create, + // read, update, or delete operation is considered timed out, which returns + // an error to practitioners. This field is only valid when the Resource is + // a managed resource or data resource. + // + // When implemented, practitioners can add a timeouts configuration block + // within their managed resource or data resource configuration to further + // customize the create, read, update, or delete operation timeouts. For + // example, a configuration may specify a longer create timeout for a + // database resource due to its data size. + // + // The ResourceData that is passed to create, read, update, and delete + // functionality can access the merged time duration of the Resource + // default timeouts configured in this field and the practitioner timeouts + // configuration via the Timeout method. Practitioner configuration + // always overrides any default values set here, whether shorter or longer. Timeouts *ResourceTimeout // Description is used as the description for docs, the language server and // other user facing usage. It can be plain-text or markdown depending on the - // global DescriptionKind setting. + // global DescriptionKind setting. This field is valid for any Resource. Description string // UseJSONNumber should be set when state upgraders will expect // json.Numbers instead of float64s for numbers. This is added as a // toggle for backwards compatibility for type assertions, but should // be used in all new resources to avoid bugs with sufficiently large - // user input. + // user input. This field is only valid when the Resource is a managed + // resource. // // See github.com/hashicorp/terraform-plugin-sdk/issues/655 for more // details. @@ -300,6 +636,7 @@ type DeleteContextFunc func(context.Context, *ResourceData, interface{}) diag.Di type StateMigrateFunc func( int, *terraform.InstanceState, interface{}) (*terraform.InstanceState, error) +// Implementation of a single schema version state upgrade. type StateUpgrader struct { // Version is the version schema that this Upgrader will handle, converting // it to Version+1. @@ -318,7 +655,36 @@ type StateUpgrader struct { Upgrade StateUpgradeFunc } -// See StateUpgrader +// Function signature for a schema version state upgrade handler. +// +// The Context parameter stores SDK information, such as loggers. It also +// is wired to receive any cancellation from Terraform such as a system or +// practitioner sending SIGINT (Ctrl-c). +// +// The map[string]interface{} parameter contains the previous schema version +// state data for a managed resource instance. The keys are top level attribute +// or block names mapped to values that can be type asserted similar to +// fetching values using the ResourceData Get* methods: +// +// - TypeBool: bool +// - TypeFloat: float +// - TypeInt: int +// - TypeList: []interface{} +// - TypeMap: map[string]interface{} +// - TypeSet: *Set +// - TypeString: string +// +// In certain scenarios, the map may be nil, so checking for that condition +// upfront is recommended to prevent potential panics. +// +// The interface{} parameter is the result of the Provider type +// ConfigureFunc field execution. If the Provider does not define +// a ConfigureFunc, this will be nil. This parameter is conventionally +// used to store API clients and other provider instance specific data. +// +// The map[string]interface{} return parameter should contain the upgraded +// schema version state data for a managed resource instance. Values must +// align to the typing mentioned above. type StateUpgradeFunc func(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) // See Resource documentation. @@ -412,16 +778,16 @@ func (r *Resource) Apply( rt := ResourceTimeout{} if _, ok := d.Meta[TimeoutKey]; ok { if err := rt.DiffDecode(d); err != nil { - log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) + logging.HelperSchemaError(ctx, "Error decoding ResourceTimeout", map[string]interface{}{logging.KeyError: err}) } } else if s != nil { if _, ok := s.Meta[TimeoutKey]; ok { if err := rt.StateDecode(s); err != nil { - log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) + logging.HelperSchemaError(ctx, "Error decoding ResourceTimeout", map[string]interface{}{logging.KeyError: err}) } } } else { - log.Printf("[DEBUG] No meta timeoutkey found in Apply()") + logging.HelperSchemaDebug(ctx, "No meta timeoutkey found in Apply()") } data.timeouts = &rt @@ -436,7 +802,10 @@ func (r *Resource) Apply( if d.Destroy || d.RequiresNew() { if s.ID != "" { // Destroy the resource since it is created + logging.HelperSchemaTrace(ctx, "Calling downstream") diags = append(diags, r.delete(ctx, data, meta)...) + logging.HelperSchemaTrace(ctx, "Called downstream") + if diags.HasError() { return r.recordCurrentSchemaVersion(data.State()), diags } @@ -464,7 +833,9 @@ func (r *Resource) Apply( if data.Id() == "" { // We're creating, it is a new resource. data.MarkNewResource() + logging.HelperSchemaTrace(ctx, "Calling downstream") diags = append(diags, r.create(ctx, data, meta)...) + logging.HelperSchemaTrace(ctx, "Called downstream") } else { if !r.updateFuncSet() { return s, append(diags, diag.Diagnostic{ @@ -472,7 +843,9 @@ func (r *Resource) Apply( Summary: "doesn't support update", }) } + logging.HelperSchemaTrace(ctx, "Calling downstream") diags = append(diags, r.update(ctx, data, meta)...) + logging.HelperSchemaTrace(ctx, "Called downstream") } return r.recordCurrentSchemaVersion(data.State()), diags @@ -499,10 +872,10 @@ func (r *Resource) Diff( if instanceDiff != nil { if err := t.DiffEncode(instanceDiff); err != nil { - log.Printf("[ERR] Error encoding timeout to instance diff: %s", err) + logging.HelperSchemaError(ctx, "Error encoding timeout to instance diff", map[string]interface{}{logging.KeyError: err}) } } else { - log.Printf("[DEBUG] Instance Diff is nil in Diff()") + logging.HelperSchemaDebug(ctx, "Instance Diff is nil in Diff()") } return instanceDiff, err @@ -566,7 +939,10 @@ func (r *Resource) ReadDataApply( return nil, diag.FromErr(err) } + logging.HelperSchemaTrace(ctx, "Calling downstream") diags := r.read(ctx, data, meta) + logging.HelperSchemaTrace(ctx, "Called downstream") + state := data.State() if state != nil && state.ID == "" { // Data sources can set an ID if they want, but they aren't @@ -595,7 +971,7 @@ func (r *Resource) RefreshWithoutUpgrade( rt := ResourceTimeout{} if _, ok := s.Meta[TimeoutKey]; ok { if err := rt.StateDecode(s); err != nil { - log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) + logging.HelperSchemaError(ctx, "Error decoding ResourceTimeout", map[string]interface{}{logging.KeyError: err}) } } @@ -612,7 +988,10 @@ func (r *Resource) RefreshWithoutUpgrade( data.providerMeta = s.ProviderMeta } + logging.HelperSchemaTrace(ctx, "Calling downstream") exists, err := r.Exists(data, meta) + logging.HelperSchemaTrace(ctx, "Called downstream") + if err != nil { return s, diag.FromErr(err) } @@ -632,12 +1011,16 @@ func (r *Resource) RefreshWithoutUpgrade( data.providerMeta = s.ProviderMeta } + logging.HelperSchemaTrace(ctx, "Calling downstream") diags := r.read(ctx, data, meta) + logging.HelperSchemaTrace(ctx, "Called downstream") + state := data.State() if state != nil && state.ID == "" { state = nil } + schemaMap(r.Schema).handleDiffSuppressOnRefresh(ctx, s, state) return r.recordCurrentSchemaVersion(state), diags } @@ -737,8 +1120,8 @@ func (r *Resource) InternalValidate(topSchemaMap schemaMap, writable bool) error } } - for k, f := range tsm { - if isReservedResourceFieldName(k, f) { + for k := range tsm { + if isReservedResourceFieldName(k) { return fmt.Errorf("%s is a reserved field name", k) } } @@ -844,13 +1227,13 @@ func validateResourceID(s *Schema) error { // ID should at least be computed. If unspecified it will be set to Computed and Optional, // but Optional is unnecessary if undesired. - if s.Computed != true { + if !s.Computed { return fmt.Errorf(`the "id" attribute must be marked Computed`) } return nil } -func isReservedResourceFieldName(name string, s *Schema) bool { +func isReservedResourceFieldName(name string) bool { for _, reservedName := range ReservedResourceFields { if name == reservedName { return true diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_data.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_data.go index 46ac3f2a41ba..396b5bc6f150 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_data.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_data.go @@ -528,7 +528,7 @@ func (d *ResourceData) getChange( func (d *ResourceData) get(addr []string, source getSource) getResult { d.once.Do(d.init) - level := "set" + var level string flags := source & ^getSourceLevelMask exact := flags&getSourceExact != 0 source = source & getSourceLevelMask diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_diff.go index 1fdc48cca7af..27575b29770a 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_diff.go @@ -270,16 +270,16 @@ func (d *ResourceDiff) GetChangedKeysPrefix(prefix string) []string { // diffChange helps to implement resourceDiffer and derives its change values // from ResourceDiff's own change data, in addition to existing diff, config, and state. func (d *ResourceDiff) diffChange(key string) (interface{}, interface{}, bool, bool, bool) { - old, new, customized := d.getChange(key) + oldValue, newValue, customized := d.getChange(key) - if !old.Exists { - old.Value = nil + if !oldValue.Exists { + oldValue.Value = nil } - if !new.Exists || d.removed(key) { - new.Value = nil + if !newValue.Exists || d.removed(key) { + newValue.Value = nil } - return old.Value, new.Value, !reflect.DeepEqual(old.Value, new.Value), new.Computed, customized + return oldValue.Value, newValue.Value, !reflect.DeepEqual(oldValue.Value, newValue.Value), newValue.Computed, customized } // SetNew is used to set a new diff value for the mentioned key. The value must @@ -308,12 +308,12 @@ func (d *ResourceDiff) SetNewComputed(key string) error { } // setDiff performs common diff setting behaviour. -func (d *ResourceDiff) setDiff(key string, new interface{}, computed bool) error { +func (d *ResourceDiff) setDiff(key string, newValue interface{}, computed bool) error { if err := d.clear(key); err != nil { return err } - if err := d.newWriter.WriteField(strings.Split(key, "."), new, computed); err != nil { + if err := d.newWriter.WriteField(strings.Split(key, "."), newValue, computed); err != nil { return fmt.Errorf("Cannot set new diff value for key %s: %s", key, err) } @@ -374,8 +374,8 @@ func (d *ResourceDiff) Get(key string) interface{} { // results from the exact levels for the new diff, then from state and diff as // per normal. func (d *ResourceDiff) GetChange(key string) (interface{}, interface{}) { - old, new, _ := d.getChange(key) - return old.Value, new.Value + oldValue, newValue, _ := d.getChange(key) + return oldValue.Value, newValue.Value } // GetOk functions the same way as ResourceData.GetOk, but it also checks the @@ -422,19 +422,29 @@ func (d *ResourceDiff) NewValueKnown(key string) bool { return !r.Computed } +// HasChanges returns whether or not any of the given keys has been changed. +func (d *ResourceDiff) HasChanges(keys ...string) bool { + for _, key := range keys { + if d.HasChange(key) { + return true + } + } + return false +} + // HasChange checks to see if there is a change between state and the diff, or // in the overridden diff. func (d *ResourceDiff) HasChange(key string) bool { - old, new := d.GetChange(key) + oldValue, newValue := d.GetChange(key) // If the type implements the Equal interface, then call that // instead of just doing a reflect.DeepEqual. An example where this is // needed is *Set - if eq, ok := old.(Equal); ok { - return !eq.Equal(new) + if eq, ok := oldValue.(Equal); ok { + return !eq.Equal(newValue) } - return !reflect.DeepEqual(old, new) + return !reflect.DeepEqual(oldValue, newValue) } // Id returns the ID of this resource. @@ -506,16 +516,16 @@ func (d *ResourceDiff) GetRawPlan() cty.Value { // results from the exact levels for the new diff, then from state and diff as // per normal. func (d *ResourceDiff) getChange(key string) (getResult, getResult, bool) { - old := d.get(strings.Split(key, "."), "state") - var new getResult + oldValue := d.get(strings.Split(key, "."), "state") + var newValue getResult for p := range d.updatedKeys { if childAddrOf(key, p) { - new = d.getExact(strings.Split(key, "."), "newDiff") - return old, new, true + newValue = d.getExact(strings.Split(key, "."), "newDiff") + return oldValue, newValue, true } } - new = d.get(strings.Split(key, "."), "newDiff") - return old, new, false + newValue = d.get(strings.Split(key, "."), "newDiff") + return oldValue, newValue, false } // removed checks to see if the key is present in the existing, pre-customized diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_timeout.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_timeout.go index cee0b67811f7..2594677f5e50 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_timeout.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_timeout.go @@ -137,7 +137,13 @@ func (t *ResourceTimeout) ConfigDecode(s *Resource, c *terraform.ResourceConfig) *timeout = rt } - return nil + + // This early return, which makes this function handle a single + // timeout configuration block, should likely not be here but the + // SDK has never raised an error for multiple blocks nor made any + // precedence decisions for them in the past. + // It is left here for compatibility reasons. + return nil //nolint:staticcheck } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/schema.go index 8d5c22e04e3c..7cbd58589175 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/schema.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/schema.go @@ -23,17 +23,24 @@ import ( "strings" "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/terraform-plugin-log/tfsdklog" "github.com/mitchellh/copystructure" "github.com/mitchellh/mapstructure" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -// Schema is used to describe the structure of a value. +// Schema describes the structure and type information of a value, whether +// sourced from configuration, plan, or state data. Schema is used in Provider +// and Resource types (for managed resources and data resources) and is +// fundamental to the implementations of ResourceData and ResourceDiff. // -// Read the documentation of the struct elements for important details. +// The Type field must always be set. At least one of Required, Optional, +// Optional and Computed, or Computed must be enabled unless the Schema is +// directly an implementation of an Elem field of another Schema. type Schema struct { // Type is the type of the value and must be one of the ValueType values. // @@ -71,14 +78,37 @@ type Schema struct { // behavior, and SchemaConfigModeBlock is not permitted. ConfigMode SchemaConfigMode - // If one of these is set, then this item can come from the configuration. - // Both cannot be set. If Optional is set, the value is optional. If - // Required is set, the value is required. + // Required indicates whether the practitioner must enter a value in the + // configuration for this attribute. Required cannot be used with Computed + // Default, DefaultFunc, DiffSuppressFunc, DiffSuppressOnRefresh, + // InputDefault, Optional, or StateFunc. At least one of Required, + // Optional, Optional and Computed, or Computed must be enabled. + Required bool + + // Optional indicates whether the practitioner can choose to not enter + // a value in the configuration for this attribute. Optional cannot be used + // with Required. // - // One of these must be set if the value is not computed. That is: - // value either comes from the config, is computed, or is both. + // If also using Default or DefaultFunc, Computed should also be enabled, + // otherwise Terraform can output warning logs or "inconsistent result + // after apply" errors. Optional bool - Required bool + + // Computed indicates whether the provider may return its own value for + // this attribute or not. Computed cannot be used with Required. If + // Required and Optional are both false, the attribute will be considered + // "read only" for the practitioner, with only the provider able to set + // its value. + Computed bool + + // ForceNew indicates whether a change in this value requires the + // replacement (destroy and create) of the managed resource instance, + // rather than an in-place update. This field is only valid when the + // encapsulating Resource is a managed resource. + // + // If conditional replacement logic is needed, use the Resource type + // CustomizeDiff field to call the ResourceDiff type ForceNew method. + ForceNew bool // If this is non-nil, the provided function will be used during diff // of this field. If this is nil, a default diff for the type of the @@ -87,31 +117,74 @@ type Schema struct { // This allows comparison based on something other than primitive, list // or map equality - for example SSH public keys may be considered // equivalent regardless of trailing whitespace. + // + // If CustomizeDiffFunc makes this field ForceNew=true, the + // following DiffSuppressFunc will come in with the value of old being + // empty, as if creating a new resource. + // + // By default, DiffSuppressFunc is considered only when deciding whether + // a configuration value is significantly different than the prior state + // value during planning. Set DiffSuppressOnRefresh to opt in to checking + // this also during the refresh step. DiffSuppressFunc SchemaDiffSuppressFunc - // If this is non-nil, then this will be a default value that is used - // when this item is not set in the configuration. + // DiffSuppressOnRefresh enables using the DiffSuppressFunc to ignore + // normalization-classified changes returned by the resource type's + // "Read" or "ReadContext" function, in addition to the default behavior of + // doing so during planning. + // + // This is a particularly good choice for attributes which take strings + // containing "microsyntaxes" where various different values are packed + // together in some serialization where there are many ways to express the + // same information. For example, attributes which accept JSON data can + // include different whitespace characters without changing meaning, and + // case-insensitive identifiers may refer to the same object using different + // characters. // - // DefaultFunc can be specified to compute a dynamic default. - // Only one of Default or DefaultFunc can be set. If DefaultFunc is - // used then its return value should be stable to avoid generating - // confusing/perpetual diffs. + // This is valid only for attributes of primitive types, because + // DiffSuppressFunc itself is only compatible with primitive types. // - // Changing either Default or the return value of DefaultFunc can be - // a breaking change, especially if the attribute in question has - // ForceNew set. If a default needs to change to align with changing - // assumptions in an upstream API then it may be necessary to also use - // the MigrateState function on the resource to change the state to match, - // or have the Read function adjust the state value to align with the - // new default. + // The key benefit of activating this flag is that the result of Read or + // ReadContext will be cleaned of normalization-only changes in the same + // way as the planning result would normaly be, which therefore prevents + // churn for downstream expressions deriving from this attribute and + // prevents incorrect "Values changed outside of Terraform" messages + // when the remote API returns values which have the same meaning as the + // prior state but in a different serialization. // - // If Required is true above, then Default cannot be set. DefaultFunc - // can be set with Required. If the DefaultFunc returns nil, then there - // will be no default and the user will be asked to fill it in. + // This is an opt-in because it was a later addition to the DiffSuppressFunc + // functionality which would cause some significant changes in behavior + // for existing providers if activated everywhere all at once. + DiffSuppressOnRefresh bool + + // Default indicates a value to set if this attribute is not set in the + // configuration. Default cannot be used with DefaultFunc or Required. + // Default is only supported if the Type is TypeBool, TypeFloat, TypeInt, + // or TypeString. Default cannot be used if the Schema is directly an + // implementation of an Elem field of another Schema, such as trying to + // set a default value for a TypeList or TypeSet. // - // If either of these is set, then the user won't be asked for input - // for this key if the default is not nil. - Default interface{} + // Changing either Default can be a breaking change, especially if the + // attribute has ForceNew enabled. If a default needs to change to align + // with changing assumptions in an upstream API, then it may be necessary + // to also implement resource state upgrade functionality to change the + // state to match or update read operation logic to align with the new + // default. + Default interface{} + + // DefaultFunc can be specified to compute a dynamic default when this + // attribute is not set in the configuration. DefaultFunc cannot be used + // with Default. For legacy reasons, DefaultFunc can be used with Required + // attributes in a Provider schema, which will prompt practitioners for + // input if the result of this function is nil. + // + // The return value should be stable to avoid generating confusing + // plan differences. Changing the return value can be a breaking change, + // especially if ForceNew is enabled. If a default needs to change to align + // with changing assumptions in an upstream API, then it may be necessary + // to also implement resource state upgrade functionality to change the + // state to match or update read operation logic to align with the new + // default. DefaultFunc SchemaDefaultFunc // Description is used as the description for docs, the language server and @@ -124,85 +197,125 @@ type Schema struct { // asked for. If Input is asked, this will be the default value offered. InputDefault string - // The fields below relate to diffs. - // - // If Computed is true, then the result of this value is computed - // (unless specified by config) on creation. - // - // If ForceNew is true, then a change in this resource necessitates - // the creation of a new resource. - // // StateFunc is a function called to change the value of this before // storing it in the state (and likewise before comparing for diffs). // The use for this is for example with large strings, you may want // to simply store the hash of it. - Computed bool - ForceNew bool StateFunc SchemaStateFunc - // The following fields are only set for a TypeList, TypeSet, or TypeMap. + // Elem represents the element type for a TypeList, TypeSet, or TypeMap + // attribute or block. The only valid types are *Schema and *Resource. + // Only TypeList and TypeSet support *Resource. + // + // If the Elem is a *Schema, the surrounding Schema represents a single + // attribute with a single element type for underlying elements. In + // practitioner configurations, an equals sign (=) is required to set + // the value. Refer to the following documentation: + // + // https://www.terraform.io/docs/language/syntax/configuration.html + // + // The underlying *Schema is only required to implement Type. ValidateFunc + // or ValidateDiagFunc can be used to validate each element value. + // + // If the Elem is a *Resource, the surrounding Schema represents a + // configuration block. Blocks can contain underlying attributes or blocks. + // In practitioner configurations, an equals sign (=) cannot be used to + // set the value. Blocks are instead repeated as necessary, or require + // the use of dynamic block expressions. Refer to the following + // documentation: // - // Elem represents the element type. For a TypeMap, it must be a *Schema - // with a Type that is one of the primitives: TypeString, TypeBool, - // TypeInt, or TypeFloat. Otherwise it may be either a *Schema or a - // *Resource. If it is *Schema, the element type is just a simple value. - // If it is *Resource, the element type is a complex structure, - // potentially managed via its own CRUD actions on the API. + // https://www.terraform.io/docs/language/syntax/configuration.html + // https://www.terraform.io/docs/language/expressions/dynamic-blocks.html + // + // The underlying *Resource must only implement the Schema field. Elem interface{} - // The following fields are only set for a TypeList or TypeSet. - // // MaxItems defines a maximum amount of items that can exist within a - // TypeSet or TypeList. Specific use cases would be if a TypeSet is being - // used to wrap a complex structure, however more than one instance would - // cause instability. - // + // TypeSet or TypeList. + MaxItems int + // MinItems defines a minimum amount of items that can exist within a - // TypeSet or TypeList. Specific use cases would be if a TypeSet is being - // used to wrap a complex structure, however less than one instance would - // cause instability. + // TypeSet or TypeList. // // If the field Optional is set to true then MinItems is ignored and thus // effectively zero. - MaxItems int MinItems int - // The following fields are only valid for a TypeSet type. - // - // Set defines a function to determine the unique ID of an item so that - // a proper set can be built. + // Set defines custom hash algorithm for each TypeSet element. If not + // defined, the SDK implements a default hash algorithm based on the + // underlying structure and type information of the Elem field. Set SchemaSetFunc // ComputedWhen is a set of queries on the configuration. Whenever any // of these things is changed, it will require a recompute (this requires // that Computed is set to true). // - // NOTE: This currently does not work. + // Deprecated: This functionality is not implemented and this field + // declaration should be removed. ComputedWhen []string - // ConflictsWith is a set of schema keys that conflict with this schema. - // This will only check that they're set in the _config_. This will not - // raise an error for a malfunctioning resource that sets a conflicting - // key. - // - // ExactlyOneOf is a set of schema keys that, when set, only one of the - // keys in that list can be specified. It will error if none are - // specified as well. + // ConflictsWith is a set of attribute paths, including this attribute, + // whose configurations cannot be set simultaneously. This implements the + // validation logic declaratively within the schema and can trigger earlier + // in Terraform operations, rather than using create or update logic which + // only triggers during apply. // - // AtLeastOneOf is a set of schema keys that, when set, at least one of - // the keys in that list must be specified. - // - // RequiredWith is a set of schema keys that must be set simultaneously. + // Only absolute attribute paths, ones starting with top level attribute + // names, are supported. Attribute paths cannot be accurately declared + // for TypeList (if MaxItems is greater than 1), TypeMap, or TypeSet + // attributes. To reference an attribute under a single configuration block + // (TypeList with Elem of *Resource and MaxItems of 1), the syntax is + // "parent_block_name.0.child_attribute_name". ConflictsWith []string - ExactlyOneOf []string - AtLeastOneOf []string - RequiredWith []string - // When Deprecated is set, this attribute is deprecated. + // ExactlyOneOf is a set of attribute paths, including this attribute, + // where only one attribute out of all specified can be configured. It will + // return a validation error if none are specified as well. This implements + // the validation logic declaratively within the schema and can trigger + // earlier in Terraform operations, rather than using create or update + // logic which only triggers during apply. + // + // Only absolute attribute paths, ones starting with top level attribute + // names, are supported. Attribute paths cannot be accurately declared + // for TypeList (if MaxItems is greater than 1), TypeMap, or TypeSet + // attributes. To reference an attribute under a single configuration block + // (TypeList with Elem of *Resource and MaxItems of 1), the syntax is + // "parent_block_name.0.child_attribute_name". + ExactlyOneOf []string + + // AtLeastOneOf is a set of attribute paths, including this attribute, + // in which at least one of the attributes must be configured. This + // implements the validation logic declaratively within the schema and can + // trigger earlier in Terraform operations, rather than using create or + // update logic which only triggers during apply. // - // A deprecated field still works, but will probably stop working in near - // future. This string is the message shown to the user with instructions on - // how to address the deprecation. + // Only absolute attribute paths, ones starting with top level attribute + // names, are supported. Attribute paths cannot be accurately declared + // for TypeList (if MaxItems is greater than 1), TypeMap, or TypeSet + // attributes. To reference an attribute under a single configuration block + // (TypeList with Elem of *Resource and MaxItems of 1), the syntax is + // "parent_block_name.0.child_attribute_name". + AtLeastOneOf []string + + // RequiredWith is a set of attribute paths, including this attribute, + // that must be set simultaneously. This implements the validation logic + // declaratively within the schema and can trigger earlier in Terraform + // operations, rather than using create or update logic which only triggers + // during apply. + // + // Only absolute attribute paths, ones starting with top level attribute + // names, are supported. Attribute paths cannot be accurately declared + // for TypeList (if MaxItems is greater than 1), TypeMap, or TypeSet + // attributes. To reference an attribute under a single configuration block + // (TypeList with Elem of *Resource and MaxItems of 1), the syntax is + // "parent_block_name.0.child_attribute_name". + RequiredWith []string + + // Deprecated indicates the message to include in a warning diagnostic to + // practitioners when this attribute is configured. Typically this is used + // to signal that this attribute will be removed in the future and provide + // next steps to the practitioner, such as using a different attribute, + // different resource, or if it should just be removed. Deprecated string // ValidateFunc allows individual fields to define arbitrary validation @@ -238,9 +351,28 @@ type Schema struct { ValidateDiagFunc SchemaValidateDiagFunc // Sensitive ensures that the attribute's value does not get displayed in - // logs or regular output. It should be used for passwords or other - // secret fields. Future versions of Terraform may encrypt these - // values. + // the Terraform user interface output. It should be used for password or + // other values which should be hidden. + // + // Terraform does not support conditional sensitivity, so if the value may + // only be sensitive in certain scenarios, a pragmatic choice will be + // necessary upfront of whether or not to always hide the value. Some + // providers may opt to split up resources based on sensitivity, to ensure + // that practitioners without sensitive values do not have values + // unnecessarily hidden. + // + // Terraform does not support passing sensitivity from configurations to + // providers. For example, if a sensitive value is configured via another + // attribute, this attribute is not marked Sensitive, and the value is used + // in this attribute value, the sensitivity is not transitive. The value + // will be displayed as normal. + // + // Sensitive values propagate when referenced in other parts of a + // configuration unless the nonsensitive() configuration function is used. + // Certain configuration usage may also expand the sensitivity. For + // example, including the sensitive value in a set may mark the whole set + // as sensitive. Any outputs containing a sensitive value must enable the + // output sensitive argument. Sensitive bool } @@ -260,7 +392,7 @@ const ( // suppress it from the plan if necessary. // // Return true if the diff should be suppressed, false to retain it. -type SchemaDiffSuppressFunc func(k, old, new string, d *ResourceData) bool +type SchemaDiffSuppressFunc func(k, oldValue, newValue string, d *ResourceData) bool // SchemaDefaultFunc is a function called to return a default value for // a field. @@ -487,11 +619,11 @@ func (m schemaMap) Data( // DeepCopy returns a copy of this schemaMap. The copy can be safely modified // without affecting the original. func (m *schemaMap) DeepCopy() schemaMap { - copy, err := copystructure.Config{Lock: true}.Copy(m) + copiedMap, err := copystructure.Config{Lock: true}.Copy(m) if err != nil { panic(err) } - return *copy.(*schemaMap) + return *copiedMap.(*schemaMap) } // Diff returns the diff for a resource given the schema map, @@ -522,7 +654,7 @@ func (m schemaMap) Diff( } for k, schema := range m { - err := m.diff(k, schema, result, d, false) + err := m.diff(ctx, k, schema, result, d, false) if err != nil { return nil, err } @@ -540,11 +672,16 @@ func (m schemaMap) Diff( if !result.DestroyTainted && customizeDiff != nil { mc := m.DeepCopy() rd := newResourceDiff(mc, c, s, result) - if err := customizeDiff(ctx, rd, meta); err != nil { + + logging.HelperSchemaTrace(ctx, "Calling downstream") + err := customizeDiff(ctx, rd, meta) + logging.HelperSchemaTrace(ctx, "Called downstream") + + if err != nil { return nil, err } for _, k := range rd.UpdatedKeys() { - err := m.diff(k, mc[k], result, rd, false) + err := m.diff(ctx, k, mc[k], result, rd, false) if err != nil { return nil, err } @@ -571,7 +708,7 @@ func (m schemaMap) Diff( // Perform the diff again for k, schema := range m { - err := m.diff(k, schema, result2, d, false) + err := m.diff(ctx, k, schema, result2, d, false) if err != nil { return nil, err } @@ -585,7 +722,7 @@ func (m schemaMap) Diff( return nil, err } for _, k := range rd.UpdatedKeys() { - err := m.diff(k, mc[k], result2, rd, false) + err := m.diff(ctx, k, mc[k], result2, rd, false) if err != nil { return nil, err } @@ -757,6 +894,10 @@ func (m schemaMap) internalValidate(topSchemaMap schemaMap, attrsOnly bool) erro } } + if v.DiffSuppressOnRefresh && v.DiffSuppressFunc == nil { + return fmt.Errorf("%s: cannot set DiffSuppressOnRefresh without DiffSuppressFunc", k) + } + if v.Type == TypeList || v.Type == TypeSet { if v.Elem == nil { return fmt.Errorf("%s: Elem must be set for lists", k) @@ -941,10 +1082,12 @@ type resourceDiffer interface { GetChange(string) (interface{}, interface{}) GetOk(string) (interface{}, bool) HasChange(string) bool + HasChanges(...string) bool Id() string } func (m schemaMap) diff( + ctx context.Context, k string, schema *Schema, diff *terraform.InstanceDiff, @@ -959,11 +1102,11 @@ func (m schemaMap) diff( case TypeBool, TypeInt, TypeFloat, TypeString: err = m.diffString(k, schema, unsupressedDiff, d, all) case TypeList: - err = m.diffList(k, schema, unsupressedDiff, d, all) + err = m.diffList(ctx, k, schema, unsupressedDiff, d, all) case TypeMap: err = m.diffMap(k, schema, unsupressedDiff, d, all) case TypeSet: - err = m.diffSet(k, schema, unsupressedDiff, d, all) + err = m.diffSet(ctx, k, schema, unsupressedDiff, d, all) default: err = fmt.Errorf("%s: unknown type %#v", k, schema.Type) } @@ -980,6 +1123,7 @@ func (m schemaMap) diff( continue } + logging.HelperSchemaDebug(ctx, "Ignoring change due to DiffSuppressFunc", map[string]interface{}{logging.KeyAttributePath: attrK}) attrV = &terraform.ResourceAttrDiff{ Old: attrV.Old, New: attrV.Old, @@ -993,6 +1137,7 @@ func (m schemaMap) diff( } func (m schemaMap) diffList( + ctx context.Context, k string, schema *Schema, diff *terraform.InstanceDiff, @@ -1091,7 +1236,7 @@ func (m schemaMap) diffList( for i := 0; i < maxLen; i++ { for k2, schema := range t.Schema { subK := fmt.Sprintf("%s.%d.%s", k, i, k2) - err := m.diff(subK, schema, diff, d, all) + err := m.diff(ctx, subK, schema, diff, d, all) if err != nil { return err } @@ -1107,7 +1252,7 @@ func (m schemaMap) diffList( // just diff each. for i := 0; i < maxLen; i++ { subK := fmt.Sprintf("%s.%d", k, i) - err := m.diff(subK, &t2, diff, d, all) + err := m.diff(ctx, subK, &t2, diff, d, all) if err != nil { return err } @@ -1232,6 +1377,7 @@ func (m schemaMap) diffMap( } func (m schemaMap) diffSet( + ctx context.Context, k string, schema *Schema, diff *terraform.InstanceDiff, @@ -1337,7 +1483,7 @@ func (m schemaMap) diffSet( // This is a complex resource for k2, schema := range t.Schema { subK := fmt.Sprintf("%s.%s.%s", k, code, k2) - err := m.diff(subK, schema, diff, d, true) + err := m.diff(ctx, subK, schema, diff, d, true) if err != nil { return err } @@ -1351,7 +1497,7 @@ func (m schemaMap) diffSet( // This is just a primitive element, so go through each and // just diff each. subK := fmt.Sprintf("%s.%s", k, code) - err := m.diff(subK, &t2, diff, d, true) + err := m.diff(ctx, subK, &t2, diff, d, true) if err != nil { return err } @@ -1426,6 +1572,60 @@ func (m schemaMap) diffString( return nil } +// handleDiffSuppressOnRefresh visits each of the attributes set in "new" and, +// if the corresponding schema sets both DiffSuppressFunc and +// DiffSuppressOnRefresh, checks whether the new value is materially different +// than the old and if not it overwrites the new value with the old one, +// in-place. +func (m schemaMap) handleDiffSuppressOnRefresh(ctx context.Context, oldState, newState *terraform.InstanceState) { + if newState == nil || oldState == nil { + return // nothing to do, then + } + + // We'll populate this in the loop below only if we find at least one + // attribute which needs this analysis. + var d *ResourceData + + oldAttrs := oldState.Attributes + newAttrs := newState.Attributes + for k, newV := range newAttrs { + oldV, ok := oldAttrs[k] + if !ok { + continue // no old value to compare with + } + if newV == oldV { + continue // no change to test + } + + schemaList := addrToSchema(strings.Split(k, "."), m) + if len(schemaList) == 0 { + continue // no schema? weird, but not our responsibility to handle + } + schema := schemaList[len(schemaList)-1] + if !schema.DiffSuppressOnRefresh || schema.DiffSuppressFunc == nil { + continue // not relevant + } + + if d == nil { + // We populate "d" only on demand, to avoid the cost for most + // existing schemas where DiffSuppressOnRefresh won't be set. + var err error + d, err = m.Data(newState, nil) + if err != nil { + // Should not happen if we got far enough to be doing this + // analysis, but if it does then we'll bail out. + tfsdklog.Warn(ctx, fmt.Sprintf("schemaMap.handleDiffSuppressOnRefresh failed to construct ResourceData: %s", err)) + return + } + } + + if schema.DiffSuppressFunc(k, oldV, newV, d) { + tfsdklog.Debug(ctx, fmt.Sprintf("ignoring change of %q due to DiffSuppressFunc", k)) + newState.Attributes[k] = oldV // keep the old value, then + } + } +} + func (m schemaMap) validate( k string, schema *Schema, @@ -2048,8 +2248,19 @@ func (m schemaMap) validatePrimitive( // decode a float as an integer. // the config shims only use int for integral number values + // also accept a string, just as the TypeBool and TypeFloat cases do if v, ok := raw.(int); ok { decoded = v + } else if _, ok := raw.(string); ok { + var n int + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: path, + }) + } + decoded = n } else { return append(diags, diag.Diagnostic{ Severity: diag.Error, @@ -2058,7 +2269,7 @@ func (m schemaMap) validatePrimitive( }) } case TypeFloat: - // Verify that we can parse this as an int + // Verify that we can parse this as a float var n float64 if err := mapstructure.WeakDecode(raw, &n); err != nil { return append(diags, diag.Diagnostic{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/set.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/set.go index 48755c22d1a3..b937ab6e5619 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/set.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/set.go @@ -3,12 +3,12 @@ package schema import ( "bytes" "fmt" - "github.com/google/go-cmp/cmp" "reflect" "sort" "strconv" "sync" + "github.com/google/go-cmp/cmp" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/hashcode" ) @@ -238,6 +238,6 @@ func (s *Set) listCode() []string { for k := range s.m { keys = append(keys, k) } - sort.Sort(sort.StringSlice(keys)) + sort.Strings(keys) return keys } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/suppress_json_diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/suppress_json_diff.go index 741ca0ac2e93..c99b73846eec 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/suppress_json_diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/suppress_json_diff.go @@ -6,13 +6,13 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -func SuppressJsonDiff(k, old, new string, d *schema.ResourceData) bool { - oldMap, err := ExpandJsonFromString(old) +func SuppressJsonDiff(k, oldValue, newValue string, d *schema.ResourceData) bool { + oldMap, err := ExpandJsonFromString(oldValue) if err != nil { return false } - newMap, err := ExpandJsonFromString(new) + newMap, err := ExpandJsonFromString(newValue) if err != nil { return false } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/map.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/map.go index 3e8068a8c090..9e4510b1e55f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/map.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/map.go @@ -17,12 +17,12 @@ func MapKeyLenBetween(min, max int) schema.SchemaValidateDiagFunc { var diags diag.Diagnostics for _, key := range sortedKeys(v.(map[string]interface{})) { - len := len(key) - if len < min || len > max { + keyLen := len(key) + if keyLen < min || keyLen > max { diags = append(diags, diag.Diagnostic{ Severity: diag.Error, Summary: "Bad map key length", - Detail: fmt.Sprintf("Map key lengths should be in the range (%d - %d): %s (length = %d)", min, max, key, len), + Detail: fmt.Sprintf("Map key lengths should be in the range (%d - %d): %s (length = %d)", min, max, key, keyLen), AttributePath: append(path, cty.IndexStep{Key: cty.StringVal(key)}), }) } @@ -53,12 +53,12 @@ func MapValueLenBetween(min, max int) schema.SchemaValidateDiagFunc { continue } - len := len(val.(string)) - if len < min || len > max { + valLen := len(val.(string)) + if valLen < min || valLen > max { diags = append(diags, diag.Diagnostic{ Severity: diag.Error, Summary: "Bad map value length", - Detail: fmt.Sprintf("Map value lengths should be in the range (%d - %d): %s => %v (length = %d)", min, max, key, val, len), + Detail: fmt.Sprintf("Map value lengths should be in the range (%d - %d): %s => %v (length = %d)", min, max, key, val, valLen), AttributePath: append(path, cty.IndexStep{Key: cty.StringVal(key)}), }) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/meta.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/meta.go index f1376c2d394a..b0515c8d0854 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/meta.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/meta.go @@ -66,8 +66,21 @@ func ToDiagFunc(validator schema.SchemaValidateFunc) schema.SchemaValidateDiagFu return func(i interface{}, p cty.Path) diag.Diagnostics { var diags diag.Diagnostics - attr := p[len(p)-1].(cty.GetAttrStep) - ws, es := validator(i, attr.Name) + // A practitioner-friendly key for any SchemaValidateFunc output. + // Generally this should be the last attribute name on the path. + // If not found for some unexpected reason, an empty string is fine + // as the diagnostic will have the full attribute path anyways. + var key string + + // Reverse search for last cty.GetAttrStep + for i := len(p) - 1; i >= 0; i-- { + if pathStep, ok := p[i].(cty.GetAttrStep); ok { + key = pathStep.Name + break + } + } + + ws, es := validator(i, key) for _, w := range ws { diags = append(diags, diag.Diagnostic{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/strings.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/strings.go index c0c17d01164e..e739a1a1bfac 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/strings.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/strings.go @@ -138,7 +138,7 @@ func StringInSlice(valid []string, ignoreCase bool) schema.SchemaValidateFunc { } for _, str := range valid { - if v == str || (ignoreCase && strings.ToLower(v) == strings.ToLower(str)) { + if v == str || (ignoreCase && strings.EqualFold(v, str)) { return warnings, errors } } @@ -160,7 +160,7 @@ func StringNotInSlice(invalid []string, ignoreCase bool) schema.SchemaValidateFu } for _, str := range invalid { - if v == str || (ignoreCase && strings.ToLower(v) == strings.ToLower(str)) { + if v == str || (ignoreCase && strings.EqualFold(v, str)) { errors = append(errors, fmt.Errorf("expected %s to not be any of %v, got %s", k, invalid, v)) return warnings, errors } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/testing.go index 596c5754a48e..d861f5a2af9c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/testing.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/testing.go @@ -5,7 +5,6 @@ import ( testing "github.com/mitchellh/go-testing-interface" - "github.com/hashicorp/go-cty/cty" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) @@ -16,12 +15,6 @@ type testCase struct { expectedErr *regexp.Regexp } -type diagTestCase struct { - val interface{} - f schema.SchemaValidateDiagFunc - expectedErr *regexp.Regexp -} - func runTestCases(t testing.T, cases []testCase) { t.Helper() @@ -52,29 +45,6 @@ func matchAnyError(errs []error, r *regexp.Regexp) bool { return false } -func runDiagTestCases(t testing.T, cases []diagTestCase) { - t.Helper() - - for i, tc := range cases { - p := cty.Path{ - cty.GetAttrStep{Name: "test_property"}, - } - diags := tc.f(tc.val, p) - - if !diags.HasError() && tc.expectedErr == nil { - continue - } - - if diags.HasError() && tc.expectedErr == nil { - t.Fatalf("expected test case %d to produce no errors, got %v", i, diags) - } - - if !matchAnyDiagSummary(diags, tc.expectedErr) { - t.Fatalf("expected test case %d to produce error matching \"%s\", got %v", i, tc.expectedErr, diags) - } - } -} - func matchAnyDiagSummary(ds diag.Diagnostics, r *regexp.Regexp) bool { for _, d := range ds { if r.MatchString(d.Summary) { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/time.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/time.go index df3e2620c6f7..fde3a019923b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/time.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/time.go @@ -7,7 +7,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -// IsDayOfTheWeek id a SchemaValidateFunc which tests if the provided value is of type string and a valid english day of the week +// IsDayOfTheWeek is a SchemaValidateFunc which tests if the provided value is of type string and a valid english day of the week func IsDayOfTheWeek(ignoreCase bool) schema.SchemaValidateFunc { return StringInSlice([]string{ "Monday", @@ -20,7 +20,7 @@ func IsDayOfTheWeek(ignoreCase bool) schema.SchemaValidateFunc { }, ignoreCase) } -// IsMonth id a SchemaValidateFunc which tests if the provided value is of type string and a valid english month +// IsMonth is a SchemaValidateFunc which tests if the provided value is of type string and a valid english month func IsMonth(ignoreCase bool) schema.SchemaValidateFunc { return StringInSlice([]string{ "January", diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module_instance.go index f31d833d2a8d..113d3d675ab6 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module_instance.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module_instance.go @@ -92,7 +92,6 @@ func parseModuleInstancePrefix(traversal hcl.Traversal) (ModuleInstance, hcl.Tra "Invalid address operator", "Module address prefix must be followed by dot and then a name.", )) - break } if next != "module" { @@ -122,7 +121,6 @@ func parseModuleInstancePrefix(traversal hcl.Traversal) (ModuleInstance, hcl.Tra "Invalid address operator", "Prefix \"module.\" must be followed by a module name.", )) - break } remain = remain[1:] step := ModuleInstanceStep{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/flatmap.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/flatmap.go index e620e76a90e2..b96e17c58533 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/flatmap.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/flatmap.go @@ -85,15 +85,15 @@ func flatmapValueFromHCL2Map(m map[string]string, prefix string, val cty.Value) return } - len := 0 + valLen := 0 for it := val.ElementIterator(); it.Next(); { ak, av := it.Element() name := ak.AsString() flatmapValueFromHCL2Value(m, prefix+name, av) - len++ + valLen++ } if !val.Type().IsObjectType() { // objects don't have an explicit count included, since their attribute count is fixed - m[prefix+"%"] = strconv.Itoa(len) + m[prefix+"%"] = strconv.Itoa(valLen) } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/context.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/context.go new file mode 100644 index 000000000000..5bce8140fdb7 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/context.go @@ -0,0 +1,75 @@ +package logging + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-log/tfsdklog" + helperlogging "github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging" + testing "github.com/mitchellh/go-testing-interface" +) + +// InitContext creates SDK logger contexts when the provider is running in +// "production" (not under acceptance testing). The incoming context will +// already have the root SDK logger and root provider logger setup from +// terraform-plugin-go tf5server RPC handlers. +func InitContext(ctx context.Context) context.Context { + ctx = tfsdklog.NewSubsystem(ctx, SubsystemHelperSchema, + // All calls are through the HelperSchema* helper functions + tfsdklog.WithAdditionalLocationOffset(1), + tfsdklog.WithLevelFromEnv(EnvTfLogSdkHelperSchema), + // Propagate tf_req_id, tf_rpc, etc. fields + tfsdklog.WithRootFields(), + ) + + return ctx +} + +// InitTestContext registers the terraform-plugin-log/tfsdklog test sink, +// configures the standard library log package, and creates SDK logger +// contexts. The incoming context is expected to be devoid of logging setup. +// +// The standard library log package handling is important as provider code +// under test may be using that package or another logging library outside of +// terraform-plugin-log. +func InitTestContext(ctx context.Context, t testing.T) context.Context { + helperlogging.SetOutput(t) + + ctx = tfsdklog.RegisterTestSink(ctx, t) + ctx = tfsdklog.NewRootSDKLogger(ctx, tfsdklog.WithLevelFromEnv(EnvTfLogSdk)) + ctx = tfsdklog.NewSubsystem(ctx, SubsystemHelperResource, + // All calls are through the HelperResource* helper functions + tfsdklog.WithAdditionalLocationOffset(1), + tfsdklog.WithLevelFromEnv(EnvTfLogSdkHelperResource), + ) + ctx = TestNameContext(ctx, t.Name()) + + return ctx +} + +// TestNameContext adds the current test name to loggers. +func TestNameContext(ctx context.Context, testName string) context.Context { + ctx = tfsdklog.SubsystemWith(ctx, SubsystemHelperResource, KeyTestName, testName) + + return ctx +} + +// TestStepNumberContext adds the current test step number to loggers. +func TestStepNumberContext(ctx context.Context, stepNumber int) context.Context { + ctx = tfsdklog.SubsystemWith(ctx, SubsystemHelperResource, KeyTestStepNumber, stepNumber) + + return ctx +} + +// TestTerraformPathContext adds the current test Terraform CLI path to loggers. +func TestTerraformPathContext(ctx context.Context, terraformPath string) context.Context { + ctx = tfsdklog.SubsystemWith(ctx, SubsystemHelperResource, KeyTestTerraformPath, terraformPath) + + return ctx +} + +// TestWorkingDirectoryContext adds the current test working directory to loggers. +func TestWorkingDirectoryContext(ctx context.Context, workingDirectory string) context.Context { + ctx = tfsdklog.SubsystemWith(ctx, SubsystemHelperResource, KeyTestWorkingDirectory, workingDirectory) + + return ctx +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/environment_variables.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/environment_variables.go new file mode 100644 index 000000000000..db1a27a8147b --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/environment_variables.go @@ -0,0 +1,24 @@ +package logging + +// Environment variables. +const ( + // EnvTfLogSdk is an environment variable that sets the logging level of + // the root SDK logger, while the provider is under test. In "production" + // usage, this environment variable is handled by terraform-plugin-go. + // + // Terraform CLI's logging must be explicitly turned on before this + // environment varable can be used to reduce the SDK logging levels. It + // cannot be used to show only SDK logging unless all other logging levels + // are turned off. + EnvTfLogSdk = "TF_LOG_SDK" + + // EnvTfLogSdkHelperResource is an environment variable that sets the logging + // level of SDK helper/resource loggers. Infers root SDK logging level, if + // unset. + EnvTfLogSdkHelperResource = "TF_LOG_SDK_HELPER_RESOURCE" + + // EnvTfLogSdkHelperSchema is an environment variable that sets the logging + // level of SDK helper/schema loggers. Infers root SDK logging level, if + // unset. + EnvTfLogSdkHelperSchema = "TF_LOG_SDK_HELPER_SCHEMA" +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/helper_resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/helper_resource.go new file mode 100644 index 000000000000..a889601c7c4c --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/helper_resource.go @@ -0,0 +1,32 @@ +package logging + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-log/tfsdklog" +) + +const ( + // SubsystemHelperResource is the tfsdklog subsystem name for helper/resource. + SubsystemHelperResource = "helper_resource" +) + +// HelperResourceTrace emits a helper/resource subsystem log at TRACE level. +func HelperResourceTrace(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemTrace(ctx, SubsystemHelperResource, msg, additionalFields...) +} + +// HelperResourceDebug emits a helper/resource subsystem log at DEBUG level. +func HelperResourceDebug(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemDebug(ctx, SubsystemHelperResource, msg, additionalFields...) +} + +// HelperResourceWarn emits a helper/resource subsystem log at WARN level. +func HelperResourceWarn(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemWarn(ctx, SubsystemHelperResource, msg, additionalFields...) +} + +// HelperResourceError emits a helper/resource subsystem log at ERROR level. +func HelperResourceError(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemError(ctx, SubsystemHelperResource, msg, additionalFields...) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/helper_schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/helper_schema.go new file mode 100644 index 000000000000..b2fe71d15d62 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/helper_schema.go @@ -0,0 +1,32 @@ +package logging + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-log/tfsdklog" +) + +const ( + // SubsystemHelperSchema is the tfsdklog subsystem name for helper/schema. + SubsystemHelperSchema = "helper_schema" +) + +// HelperSchemaDebug emits a helper/schema subsystem log at DEBUG level. +func HelperSchemaDebug(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemDebug(ctx, SubsystemHelperSchema, msg, additionalFields...) +} + +// HelperSchemaError emits a helper/schema subsystem log at ERROR level. +func HelperSchemaError(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemError(ctx, SubsystemHelperSchema, msg, additionalFields...) +} + +// HelperSchemaTrace emits a helper/schema subsystem log at TRACE level. +func HelperSchemaTrace(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemTrace(ctx, SubsystemHelperSchema, msg, additionalFields...) +} + +// HelperSchemaWarn emits a helper/schema subsystem log at WARN level. +func HelperSchemaWarn(ctx context.Context, msg string, additionalFields ...map[string]interface{}) { + tfsdklog.SubsystemWarn(ctx, SubsystemHelperSchema, msg, additionalFields...) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/keys.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/keys.go new file mode 100644 index 000000000000..03931b024735 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging/keys.go @@ -0,0 +1,54 @@ +package logging + +// Structured logging keys. +// +// Practitioners or tooling reading logs may be depending on these keys, so be +// conscious of that when changing them. +// +// Refer to the terraform-plugin-go logging keys as well, which should be +// equivalent to these when possible. +const ( + // Attribute path representation, which is typically in flatmap form such + // as parent.0.child in this project. + KeyAttributePath = "tf_attribute_path" + + // The type of data source being operated on, such as "archive_file" + KeyDataSourceType = "tf_data_source_type" + + // Underlying Go error string when logging an error. + KeyError = "error" + + // The full address of the provider, such as + // registry.terraform.io/hashicorp/random + KeyProviderAddress = "tf_provider_addr" + + // The type of resource being operated on, such as "random_pet" + KeyResourceType = "tf_resource_type" + + // The name of the test being executed. + KeyTestName = "test_name" + + // The TestStep number of the test being executed. Starts at 1. + KeyTestStepNumber = "test_step_number" + + // The Terraform CLI logging level (TF_LOG) used for an acceptance test. + KeyTestTerraformLogLevel = "test_terraform_log_level" + + // The Terraform CLI logging level (TF_LOG_CORE) used for an acceptance test. + KeyTestTerraformLogCoreLevel = "test_terraform_log_core_level" + + // The Terraform CLI logging level (TF_LOG_PROVIDER) used for an acceptance test. + KeyTestTerraformLogProviderLevel = "test_terraform_log_provider_level" + + // The path to the Terraform CLI logging file used for an acceptance test. + // + // This should match where the rest of the acceptance test logs are going + // already, but is provided for troubleshooting in case it does not. + KeyTestTerraformLogPath = "test_terraform_log_path" + + // The path to the Terraform CLI used for an acceptance test. + KeyTestTerraformPath = "test_terraform_path" + + // The working directory of the acceptance test. + KeyTestWorkingDirectory = "test_working_directory" +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/diagnostics.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/diagnostics.go index 252456747dee..e02c1e443944 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/diagnostics.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/diagnostics.go @@ -1,34 +1,61 @@ package convert import ( - "fmt" + "context" "github.com/hashicorp/go-cty/cty" "github.com/hashicorp/terraform-plugin-go/tfprotov5" "github.com/hashicorp/terraform-plugin-go/tftypes" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" ) // AppendProtoDiag appends a new diagnostic from a warning string or an error. // This panics if d is not a string or error. -func AppendProtoDiag(diags []*tfprotov5.Diagnostic, d interface{}) []*tfprotov5.Diagnostic { +func AppendProtoDiag(ctx context.Context, diags []*tfprotov5.Diagnostic, d interface{}) []*tfprotov5.Diagnostic { switch d := d.(type) { case cty.PathError: ap := PathToAttributePath(d.Path) - diags = append(diags, &tfprotov5.Diagnostic{ + diagnostic := &tfprotov5.Diagnostic{ Severity: tfprotov5.DiagnosticSeverityError, Summary: d.Error(), Attribute: ap, - }) + } + + if diagnostic.Summary == "" { + logging.HelperSchemaWarn(ctx, "detected empty error string for diagnostic in AppendProtoDiag for cty.PathError type") + diagnostic.Summary = "Empty Error String" + diagnostic.Detail = "This is always a bug in the provider and should be reported to the provider developers." + } + + diags = append(diags, diagnostic) case diag.Diagnostics: diags = append(diags, DiagsToProto(d)...) case error: - diags = append(diags, &tfprotov5.Diagnostic{ + if d == nil { + logging.HelperSchemaDebug(ctx, "skipping diagnostic for nil error in AppendProtoDiag") + return diags + } + + diagnostic := &tfprotov5.Diagnostic{ Severity: tfprotov5.DiagnosticSeverityError, Summary: d.Error(), - }) + } + + if diagnostic.Summary == "" { + logging.HelperSchemaWarn(ctx, "detected empty error string for diagnostic in AppendProtoDiag for error type") + diagnostic.Summary = "Error Missing Message" + diagnostic.Detail = "This is always a bug in the provider and should be reported to the provider developers." + } + + diags = append(diags, diagnostic) case string: + if d == "" { + logging.HelperSchemaDebug(ctx, "skipping diagnostic for empty string in AppendProtoDiag") + return diags + } + diags = append(diags, &tfprotov5.Diagnostic{ Severity: tfprotov5.DiagnosticSeverityWarning, Summary: d, @@ -68,19 +95,18 @@ func ProtoToDiags(ds []*tfprotov5.Diagnostic) diag.Diagnostics { func DiagsToProto(diags diag.Diagnostics) []*tfprotov5.Diagnostic { var ds []*tfprotov5.Diagnostic for _, d := range diags { - if err := d.Validate(); err != nil { - panic(fmt.Errorf("Invalid diagnostic: %s. This is always a bug in the provider implementation", err)) - } protoDiag := &tfprotov5.Diagnostic{ + Severity: tfprotov5.DiagnosticSeverityError, Summary: d.Summary, Detail: d.Detail, Attribute: PathToAttributePath(d.AttributePath), } - if d.Severity == diag.Error { - protoDiag.Severity = tfprotov5.DiagnosticSeverityError - } else if d.Severity == diag.Warning { + if d.Severity == diag.Warning { protoDiag.Severity = tfprotov5.DiagnosticSeverityWarning } + if d.Summary == "" { + protoDiag.Summary = "Empty Summary: This is always a bug in the provider and should be reported to the provider developers." + } ds = append(ds, protoDiag) } return ds @@ -93,13 +119,13 @@ func AttributePathToPath(ap *tftypes.AttributePath) cty.Path { return p } for _, step := range ap.Steps() { - switch step.(type) { + switch step := step.(type) { case tftypes.AttributeName: - p = p.GetAttr(string(step.(tftypes.AttributeName))) + p = p.GetAttr(string(step)) case tftypes.ElementKeyString: - p = p.Index(cty.StringVal(string(step.(tftypes.ElementKeyString)))) + p = p.Index(cty.StringVal(string(step))) case tftypes.ElementKeyInt: - p = p.Index(cty.NumberIntVal(int64(step.(tftypes.ElementKeyInt)))) + p = p.Index(cty.NumberIntVal(int64(step))) } } return p diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/schema.go index c5dbf5b8fde7..07d0b89783ce 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/schema.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/schema.go @@ -1,8 +1,8 @@ package convert import ( + "context" "fmt" - "log" "reflect" "sort" @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-go/tfprotov5" "github.com/hashicorp/terraform-plugin-go/tftypes" "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" ) func tftypeFromCtyType(in cty.Type) (tftypes.Type, error) { @@ -128,10 +129,10 @@ func ctyTypeFromTFType(in tftypes.Type) (cty.Type, error) { // ConfigSchemaToProto takes a *configschema.Block and converts it to a // tfprotov5.SchemaBlock for a grpc response. -func ConfigSchemaToProto(b *configschema.Block) *tfprotov5.SchemaBlock { +func ConfigSchemaToProto(ctx context.Context, b *configschema.Block) *tfprotov5.SchemaBlock { block := &tfprotov5.SchemaBlock{ Description: b.Description, - DescriptionKind: protoStringKind(b.DescriptionKind), + DescriptionKind: protoStringKind(ctx, b.DescriptionKind), Deprecated: b.Deprecated, } @@ -141,7 +142,7 @@ func ConfigSchemaToProto(b *configschema.Block) *tfprotov5.SchemaBlock { attr := &tfprotov5.SchemaAttribute{ Name: name, Description: a.Description, - DescriptionKind: protoStringKind(a.DescriptionKind), + DescriptionKind: protoStringKind(ctx, a.DescriptionKind), Optional: a.Optional, Computed: a.Computed, Required: a.Required, @@ -160,16 +161,16 @@ func ConfigSchemaToProto(b *configschema.Block) *tfprotov5.SchemaBlock { for _, name := range sortedKeys(b.BlockTypes) { b := b.BlockTypes[name] - block.BlockTypes = append(block.BlockTypes, protoSchemaNestedBlock(name, b)) + block.BlockTypes = append(block.BlockTypes, protoSchemaNestedBlock(ctx, name, b)) } return block } -func protoStringKind(k configschema.StringKind) tfprotov5.StringKind { +func protoStringKind(ctx context.Context, k configschema.StringKind) tfprotov5.StringKind { switch k { default: - log.Printf("[TRACE] unexpected configschema.StringKind: %d", k) + logging.HelperSchemaTrace(ctx, fmt.Sprintf("Unexpected configschema.StringKind: %d", k)) return tfprotov5.StringKindPlain case configschema.StringPlain: return tfprotov5.StringKindPlain @@ -178,7 +179,7 @@ func protoStringKind(k configschema.StringKind) tfprotov5.StringKind { } } -func protoSchemaNestedBlock(name string, b *configschema.NestedBlock) *tfprotov5.SchemaNestedBlock { +func protoSchemaNestedBlock(ctx context.Context, name string, b *configschema.NestedBlock) *tfprotov5.SchemaNestedBlock { var nesting tfprotov5.SchemaNestedBlockNestingMode switch b.Nesting { case configschema.NestingSingle: @@ -196,7 +197,7 @@ func protoSchemaNestedBlock(name string, b *configschema.NestedBlock) *tfprotov5 } return &tfprotov5.SchemaNestedBlock{ TypeName: name, - Block: ConfigSchemaToProto(&b.Block), + Block: ConfigSchemaToProto(ctx, &b.Block), Nesting: nesting, MinItems: int64(b.MinItems), MaxItems: int64(b.MaxItems), @@ -205,20 +206,20 @@ func protoSchemaNestedBlock(name string, b *configschema.NestedBlock) *tfprotov5 // ProtoToConfigSchema takes the GetSchema_Block from a grpc response and converts it // to a terraform *configschema.Block. -func ProtoToConfigSchema(b *tfprotov5.SchemaBlock) *configschema.Block { +func ProtoToConfigSchema(ctx context.Context, b *tfprotov5.SchemaBlock) *configschema.Block { block := &configschema.Block{ Attributes: make(map[string]*configschema.Attribute), BlockTypes: make(map[string]*configschema.NestedBlock), Description: b.Description, - DescriptionKind: schemaStringKind(b.DescriptionKind), + DescriptionKind: schemaStringKind(ctx, b.DescriptionKind), Deprecated: b.Deprecated, } for _, a := range b.Attributes { attr := &configschema.Attribute{ Description: a.Description, - DescriptionKind: schemaStringKind(a.DescriptionKind), + DescriptionKind: schemaStringKind(ctx, a.DescriptionKind), Required: a.Required, Optional: a.Optional, Computed: a.Computed, @@ -236,16 +237,16 @@ func ProtoToConfigSchema(b *tfprotov5.SchemaBlock) *configschema.Block { } for _, b := range b.BlockTypes { - block.BlockTypes[b.TypeName] = schemaNestedBlock(b) + block.BlockTypes[b.TypeName] = schemaNestedBlock(ctx, b) } return block } -func schemaStringKind(k tfprotov5.StringKind) configschema.StringKind { +func schemaStringKind(ctx context.Context, k tfprotov5.StringKind) configschema.StringKind { switch k { default: - log.Printf("[TRACE] unexpected tfprotov5.StringKind: %d", k) + logging.HelperSchemaTrace(ctx, fmt.Sprintf("Unexpected tfprotov5.StringKind: %d", k)) return configschema.StringPlain case tfprotov5.StringKindPlain: return configschema.StringPlain @@ -254,7 +255,7 @@ func schemaStringKind(k tfprotov5.StringKind) configschema.StringKind { } } -func schemaNestedBlock(b *tfprotov5.SchemaNestedBlock) *configschema.NestedBlock { +func schemaNestedBlock(ctx context.Context, b *tfprotov5.SchemaNestedBlock) *configschema.NestedBlock { var nesting configschema.NestingMode switch b.Nesting { case tfprotov5.SchemaNestedBlockNestingModeSingle: @@ -278,7 +279,7 @@ func schemaNestedBlock(b *tfprotov5.SchemaNestedBlock) *configschema.NestedBlock MaxItems: int(b.MaxItems), } - nested := ProtoToConfigSchema(b.Block) + nested := ProtoToConfigSchema(ctx, b.Block) nb.Block = *nested return nb } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/config.go index 2c544e9e50cc..c238145aaab5 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/config.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/config.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/hc-install/product" "github.com/hashicorp/hc-install/releases" "github.com/hashicorp/hc-install/src" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" ) // Config is used to configure the test helper. In most normal test programs @@ -29,11 +30,11 @@ type Config struct { // DiscoverConfig uses environment variables and other means to automatically // discover a reasonable test helper configuration. -func DiscoverConfig(sourceDir string) (*Config, error) { - tfVersion := strings.TrimPrefix(os.Getenv("TF_ACC_TERRAFORM_VERSION"), "v") - tfPath := os.Getenv("TF_ACC_TERRAFORM_PATH") +func DiscoverConfig(ctx context.Context, sourceDir string) (*Config, error) { + tfVersion := strings.TrimPrefix(os.Getenv(EnvTfAccTerraformVersion), "v") + tfPath := os.Getenv(EnvTfAccTerraformPath) - tempDir := os.Getenv("TF_ACC_TEMP_DIR") + tempDir := os.Getenv(EnvTfAccTempDir) tfDir, err := ioutil.TempDir(tempDir, "plugintest-terraform") if err != nil { return nil, fmt.Errorf("failed to create temp dir: %w", err) @@ -42,6 +43,8 @@ func DiscoverConfig(sourceDir string) (*Config, error) { var sources []src.Source switch { case tfPath != "": + logging.HelperResourceTrace(ctx, fmt.Sprintf("Adding potential Terraform CLI source of exact path: %s", tfPath)) + sources = append(sources, &fs.AnyVersion{ ExactBinPath: tfPath, }) @@ -52,12 +55,17 @@ func DiscoverConfig(sourceDir string) (*Config, error) { return nil, fmt.Errorf("invalid Terraform version: %w", err) } + logging.HelperResourceTrace(ctx, fmt.Sprintf("Adding potential Terraform CLI source of releases.hashicorp.com exact version %q for installation in: %s", tfVersion, tfDir)) + sources = append(sources, &releases.ExactVersion{ InstallDir: tfDir, Product: product.Terraform, Version: tfVersion, }) default: + logging.HelperResourceTrace(ctx, "Adding potential Terraform CLI source of local filesystem PATH lookup") + logging.HelperResourceTrace(ctx, fmt.Sprintf("Adding potential Terraform CLI source of checkpoint.hashicorp.com latest version for installation in: %s", tfDir)) + sources = append(sources, &fs.AnyVersion{ Product: &product.Terraform, }) @@ -70,9 +78,13 @@ func DiscoverConfig(sourceDir string) (*Config, error) { installer := install.NewInstaller() tfExec, err := installer.Ensure(context.Background(), sources) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to find or install Terraform CLI from %+v: %w", sources, err) } + ctx = logging.TestTerraformPathContext(ctx, tfExec) + + logging.HelperResourceDebug(ctx, "Found Terraform CLI") + return &Config{ SourceDir: sourceDir, TerraformExec: tfExec, diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/environment_variables.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/environment_variables.go new file mode 100644 index 000000000000..6fd001a07d0b --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/environment_variables.go @@ -0,0 +1,108 @@ +package plugintest + +// Environment variables +const ( + // Environment variable with acceptance testing temporary directory for + // testing files and Terraform CLI installation, if installation is + // required. By default, the operating system temporary directory is used. + // + // Setting TF_ACC_TERRAFORM_PATH does not override this value for Terraform + // CLI installation, if installation is required. + EnvTfAccTempDir = "TF_ACC_TEMP_DIR" + + // Environment variable with level to filter Terraform logs during + // acceptance testing. This value sets TF_LOG in a safe manner when + // executing Terraform CLI commands, which would otherwise interfere + // with the testing framework using TF_LOG to set the Go standard library + // log package level. + // + // This value takes precedence over TF_LOG_CORE, due to precedence rules + // in the Terraform core code, so it is not possible to set this to a level + // and also TF_LOG_CORE=OFF. Use TF_LOG_CORE and TF_LOG_PROVIDER in that + // case instead. + // + // If not set, but TF_ACC_LOG_PATH or TF_LOG_PATH_MASK is set, it defaults + // to TRACE. If Terraform CLI is version 0.14 or earlier, it will have no + // separate affect from the TF_ACC_LOG_PATH or TF_LOG_PATH_MASK behavior, + // as those earlier versions of Terraform are unreliable with the logging + // level being outside TRACE. + EnvTfAccLog = "TF_ACC_LOG" + + // Environment variable with path to save Terraform logs during acceptance + // testing. This value sets TF_LOG_PATH in a safe manner when executing + // Terraform CLI commands, which would otherwise be ignored since it could + // interfere with how the underlying execution is performed. + // + // If TF_LOG_PATH_MASK is set, it takes precedence over this value. + EnvTfAccLogPath = "TF_ACC_LOG_PATH" + + // Environment variable with level to filter Terraform core logs during + // acceptance testing. This value sets TF_LOG_CORE separate from + // TF_LOG_PROVIDER when calling Terraform. + // + // This value has no affect when TF_ACC_LOG is set (which sets Terraform's + // TF_LOG), due to precedence rules in the Terraform core code. Use + // TF_LOG_CORE and TF_LOG_PROVIDER in that case instead. + // + // If not set, defaults to TF_ACC_LOG behaviors. + EnvTfLogCore = "TF_LOG_CORE" + + // Environment variable with path containing the string %s, which is + // replaced with the test name, to save separate Terraform logs during + // acceptance testing. This value sets TF_LOG_PATH in a safe manner when + // executing Terraform CLI commands, which would otherwise be ignored since + // it could interfere with how the underlying execution is performed. + // + // Takes precedence over TF_ACC_LOG_PATH. + EnvTfLogPathMask = "TF_LOG_PATH_MASK" + + // Environment variable with level to filter Terraform provider logs during + // acceptance testing. This value sets TF_LOG_PROVIDER separate from + // TF_LOG_CORE. + // + // During testing, this only affects external providers whose logging goes + // through Terraform. The logging for the provider under test is controlled + // by the testing framework as it is running the provider code. Provider + // code using the Go standard library log package is controlled by TF_LOG + // for historical compatibility. + // + // This value takes precedence over TF_ACC_LOG for external provider logs, + // due to rules in the Terraform core code. + // + // If not set, defaults to TF_ACC_LOG behaviors. + EnvTfLogProvider = "TF_LOG_PROVIDER" + + // Environment variable with acceptance testing Terraform CLI version to + // download from releases.hashicorp.com, checksum verify, and install. The + // value can be any valid Terraform CLI version, such as 1.1.6, with or + // without a prepended v character. + // + // Setting this value takes precedence over using an available Terraform + // binary in the operation system PATH, or if not found, installing the + // latest version according to checkpoint.hashicorp.com. + // + // By default, the binary is installed in the operating system temporary + // directory, however that directory can be overridden with the + // TF_ACC_TEMP_DIR environment variable. + // + // If TF_ACC_TERRAFORM_PATH is also set, this installation method is + // only invoked when a binary does not exist at that path. No version + // checks are performed against an existing TF_ACC_TERRAFORM_PATH. + EnvTfAccTerraformVersion = "TF_ACC_TERRAFORM_VERSION" + + // Acceptance testing path to Terraform CLI binary. + // + // Setting this value takes precedence over using an available Terraform + // binary in the operation system PATH, or if not found, installing the + // latest version according to checkpoint.hashicorp.com. This value does + // not override TF_ACC_TEMP_DIR for Terraform CLI installation, if + // installation is required. + // + // If TF_ACC_TERRAFORM_VERSION is not set, the binary must exist and be + // executable, or an error will be returned. + // + // If TF_ACC_TERRAFORM_VERSION is also set, that Terraform CLI version + // will be installed if a binary is not found at the given path. No version + // checks are performed against an existing binary. + EnvTfAccTerraformPath = "TF_ACC_TERRAFORM_PATH" +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/guard.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/guard.go index 56eaa0c16dc6..ad796be08c6b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/guard.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/guard.go @@ -2,54 +2,8 @@ package plugintest import ( "fmt" - "os" - "testing" ) -// AcceptanceTest is a test guard that will produce a log and call SkipNow on -// the given TestControl if the environment variable TF_ACC isn't set to -// indicate that the caller wants to run acceptance tests. -// -// Call this immediately at the start of each acceptance test function to -// signal that it may cost money and thus requires this opt-in enviromment -// variable. -// -// For the purpose of this function, an "acceptance test" is any est that -// reaches out to services that are not directly controlled by the test program -// itself, particularly if those requests may lead to service charges. For any -// system where it is possible and realistic to run a local instance of the -// service for testing (e.g. in a daemon launched by the test program itself), -// prefer to do this and _don't_ call AcceptanceTest, thus allowing tests to be -// run more easily and without external cost by contributors. -func AcceptanceTest(t TestControl) { - t.Helper() - if os.Getenv("TF_ACC") != "" { - t.Log("TF_ACC is not set") - t.SkipNow() - } -} - -// LongTest is a test guard that will produce a log and call SkipNow on the -// given TestControl if the test harness is currently running in "short mode". -// -// What is considered a "long test" will always be pretty subjective, but test -// implementers should think of this in terms of what seems like it'd be -// inconvenient to run repeatedly for quick feedback while testing a new feature -// under development. -// -// When testing resource types that always take several minutes to complete -// operations, consider having a single general test that covers the basic -// functionality and then mark any other more specific tests as long tests so -// that developers can quickly smoke-test a particular feature when needed -// but can still run the full set of tests for a feature when needed. -func LongTest(t TestControl) { - t.Helper() - if testing.Short() { - t.Log("skipping long test because of short mode") - t.SkipNow() - } -} - // TestControl is an interface requiring a subset of *testing.T which is used // by the test guards and helpers in this package. Most callers can simply // pass their *testing.T value here, but the interface allows other @@ -65,6 +19,7 @@ type TestControl interface { Log(args ...interface{}) FailNow() SkipNow() + Name() string } // testingT wraps a TestControl to recover some of the convenience behaviors diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/helper.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/helper.go index 4b130b499dda..0411eae0a873 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/helper.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/helper.go @@ -1,16 +1,17 @@ package plugintest import ( + "context" + "errors" "fmt" "io/ioutil" "os" + "strings" "github.com/hashicorp/terraform-exec/tfexec" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" ) -const subprocessCurrentSigil = "4acd63807899403ca4859f5bb948d2c6" -const subprocessPreviousSigil = "2279afb8cf71423996be1fd65d32f13b" - // AutoInitProviderHelper is the main entrypoint for testing provider plugins // using this package. It is intended to be called during TestMain to prepare // for provider testing. @@ -20,8 +21,8 @@ const subprocessPreviousSigil = "2279afb8cf71423996be1fd65d32f13b" // available for upgrade tests, and then will return an object containing the // results of that initialization which can then be stored in a global variable // for use in other tests. -func AutoInitProviderHelper(sourceDir string) *Helper { - helper, err := AutoInitHelper(sourceDir) +func AutoInitProviderHelper(ctx context.Context, sourceDir string) *Helper { + helper, err := AutoInitHelper(ctx, sourceDir) if err != nil { fmt.Fprintf(os.Stderr, "cannot run Terraform provider tests: %s\n", err) os.Exit(1) @@ -49,13 +50,13 @@ type Helper struct { // way to get the standard init behavior based on environment variables, and // callers should use this unless they have an unusual requirement that calls // for constructing a config in a different way. -func AutoInitHelper(sourceDir string) (*Helper, error) { - config, err := DiscoverConfig(sourceDir) +func AutoInitHelper(ctx context.Context, sourceDir string) (*Helper, error) { + config, err := DiscoverConfig(ctx, sourceDir) if err != nil { return nil, err } - return InitHelper(config) + return InitHelper(ctx, config) } // InitHelper prepares a testing helper with the given configuration. @@ -67,8 +68,8 @@ func AutoInitHelper(sourceDir string) (*Helper, error) { // If this function returns an error then it may have left some temporary files // behind in the system's temporary directory. There is currently no way to // automatically clean those up. -func InitHelper(config *Config) (*Helper, error) { - tempDir := os.Getenv("TF_ACC_TEMP_DIR") +func InitHelper(ctx context.Context, config *Config) (*Helper, error) { + tempDir := os.Getenv(EnvTfAccTempDir) baseDir, err := ioutil.TempDir(tempDir, "plugintest") if err != nil { return nil, fmt.Errorf("failed to create temporary directory for test helper: %s", err) @@ -103,24 +104,155 @@ func (h *Helper) Close() error { // If the working directory object is not itself closed by the time the test // program exits, the Close method on the helper itself will attempt to // delete it. -func (h *Helper) NewWorkingDir() (*WorkingDir, error) { +func (h *Helper) NewWorkingDir(ctx context.Context, t TestControl) (*WorkingDir, error) { dir, err := ioutil.TempDir(h.baseDir, "work") if err != nil { return nil, err } + ctx = logging.TestWorkingDirectoryContext(ctx, dir) + // symlink the provider source files into the config directory // e.g. testdata + logging.HelperResourceTrace(ctx, "Symlinking source directories to work directory") err = symlinkDirectoriesOnly(h.sourceDir, dir) if err != nil { return nil, err } tf, err := tfexec.NewTerraform(dir, h.terraformExec) + if err != nil { + return nil, fmt.Errorf("unable to create terraform-exec instance: %w", err) + } + + err = tf.SetDisablePluginTLS(true) + + if err != nil { + return nil, fmt.Errorf("unable to disable terraform-exec plugin TLS: %w", err) + } + + err = tf.SetSkipProviderVerify(true) // Only required for Terraform CLI 0.12.x + + var mismatch *tfexec.ErrVersionMismatch + if err != nil && !errors.As(err, &mismatch) { + return nil, fmt.Errorf("unable to disable terraform-exec provider verification: %w", err) + } + + tfAccLog := os.Getenv(EnvTfAccLog) + tfAccLogPath := os.Getenv(EnvTfAccLogPath) + tfLogCore := os.Getenv(EnvTfLogCore) + tfLogPathMask := os.Getenv(EnvTfLogPathMask) + tfLogProvider := os.Getenv(EnvTfLogProvider) + + if tfAccLog != "" && tfLogCore != "" { + err = fmt.Errorf( + "Invalid environment variable configuration. Cannot set both TF_ACC_LOG and TF_LOG_CORE. " + + "Use TF_LOG_CORE and TF_LOG_PROVIDER to separately control the Terraform CLI logging subsystems. " + + "To control the Go standard library log package for the provider under test, use TF_LOG.", + ) + logging.HelperResourceError(ctx, err.Error()) return nil, err } + if tfAccLog != "" { + logging.HelperResourceTrace( + ctx, + fmt.Sprintf("Setting terraform-exec log level via %s environment variable, if Terraform CLI is version 0.15 or later", EnvTfAccLog), + map[string]interface{}{logging.KeyTestTerraformLogLevel: tfAccLog}, + ) + + err := tf.SetLog(tfAccLog) + + if err != nil { + if !errors.As(err, new(*tfexec.ErrVersionMismatch)) { + logging.HelperResourceError( + ctx, + "Unable to set terraform-exec log level", + map[string]interface{}{logging.KeyError: err.Error()}, + ) + return nil, fmt.Errorf("unable to set terraform-exec log level (%s): %w", tfAccLog, err) + } + + logging.HelperResourceWarn( + ctx, + fmt.Sprintf("Unable to set terraform-exec log level via %s environment variable, as Terraform CLI is version 0.14 or earlier. It will default to TRACE.", EnvTfAccLog), + map[string]interface{}{logging.KeyTestTerraformLogLevel: "TRACE"}, + ) + } + } + + if tfLogCore != "" { + logging.HelperResourceTrace( + ctx, + fmt.Sprintf("Setting terraform-exec core log level via %s environment variable, if Terraform CLI is version 0.15 or later", EnvTfLogCore), + map[string]interface{}{ + logging.KeyTestTerraformLogCoreLevel: tfLogCore, + }, + ) + + err := tf.SetLogCore(tfLogCore) + + if err != nil { + logging.HelperResourceError( + ctx, + "Unable to set terraform-exec core log level", + map[string]interface{}{logging.KeyError: err.Error()}, + ) + return nil, fmt.Errorf("unable to set terraform-exec core log level (%s): %w", tfLogCore, err) + } + } + + if tfLogProvider != "" { + logging.HelperResourceTrace( + ctx, + fmt.Sprintf("Setting terraform-exec provider log level via %s environment variable, if Terraform CLI is version 0.15 or later", EnvTfLogProvider), + map[string]interface{}{ + logging.KeyTestTerraformLogCoreLevel: tfLogProvider, + }, + ) + + err := tf.SetLogProvider(tfLogProvider) + + if err != nil { + logging.HelperResourceError( + ctx, + "Unable to set terraform-exec provider log level", + map[string]interface{}{logging.KeyError: err.Error()}, + ) + return nil, fmt.Errorf("unable to set terraform-exec provider log level (%s): %w", tfLogProvider, err) + } + } + + var logPath, logPathEnvVar string + + if tfAccLogPath != "" { + logPath = tfAccLogPath + logPathEnvVar = EnvTfAccLogPath + } + + // Similar to helper/logging.LogOutput() and + // terraform-plugin-log/tfsdklog.RegisterTestSink(), the TF_LOG_PATH_MASK + // environment variable should take precedence over TF_ACC_LOG_PATH. + if tfLogPathMask != "" { + // Escape special characters which may appear if we have subtests + testName := strings.Replace(t.Name(), "/", "__", -1) + logPath = fmt.Sprintf(tfLogPathMask, testName) + logPathEnvVar = EnvTfLogPathMask + } + + if logPath != "" { + logging.HelperResourceTrace( + ctx, + fmt.Sprintf("Setting terraform-exec log path via %s environment variable", logPathEnvVar), + map[string]interface{}{logging.KeyTestTerraformLogPath: logPath}, + ) + + if err := tf.SetLogPath(logPath); err != nil { + return nil, fmt.Errorf("unable to set terraform-exec log path (%s): %w", logPath, err) + } + } + return &WorkingDir{ h: h, tf: tf, @@ -132,10 +264,10 @@ func (h *Helper) NewWorkingDir() (*WorkingDir, error) { // RequireNewWorkingDir is a variant of NewWorkingDir that takes a TestControl // object and will immediately fail the running test if the creation of the // working directory fails. -func (h *Helper) RequireNewWorkingDir(t TestControl) *WorkingDir { +func (h *Helper) RequireNewWorkingDir(ctx context.Context, t TestControl) *WorkingDir { t.Helper() - wd, err := h.NewWorkingDir() + wd, err := h.NewWorkingDir(ctx, t) if err != nil { t := testingT{t} t.Fatalf("failed to create new working directory: %s", err) @@ -144,6 +276,11 @@ func (h *Helper) RequireNewWorkingDir(t TestControl) *WorkingDir { return wd } +// WorkingDirectory returns the working directory being used when running tests. +func (h *Helper) WorkingDirectory() string { + return h.baseDir +} + // TerraformExecPath returns the location of the Terraform CLI executable that // should be used when running tests. func (h *Helper) TerraformExecPath() string { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/util.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/util.go index df1cb92fda93..335e217ada13 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/util.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/util.go @@ -1,20 +1,31 @@ package plugintest import ( + "fmt" "os" "path/filepath" ) -func symlinkFile(src string, dest string) (err error) { - err = os.Symlink(src, dest) - if err == nil { - srcInfo, err := os.Stat(src) - if err != nil { - err = os.Chmod(dest, srcInfo.Mode()) - } +func symlinkFile(src string, dest string) error { + err := os.Symlink(src, dest) + + if err != nil { + return fmt.Errorf("unable to symlink %q to %q: %w", src, dest, err) } - return + srcInfo, err := os.Stat(src) + + if err != nil { + return fmt.Errorf("unable to stat %q: %w", src, err) + } + + err = os.Chmod(dest, srcInfo.Mode()) + + if err != nil { + return fmt.Errorf("unable to set %q permissions: %w", dest, err) + } + + return nil } // symlinkDir is a simplistic function for recursively symlinking all files in a directory to a new path. diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/working_dir.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/working_dir.go index 1faeb5c7a714..1c15e6f5c198 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/working_dir.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest/working_dir.go @@ -3,7 +3,7 @@ package plugintest import ( "bytes" "context" - "errors" + "encoding/json" "fmt" "io/ioutil" "os" @@ -11,11 +11,13 @@ import ( "github.com/hashicorp/terraform-exec/tfexec" tfjson "github.com/hashicorp/terraform-json" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging" ) const ( - ConfigFileName = "terraform_plugin_test.tf" - PlanFileName = "tfplan" + ConfigFileName = "terraform_plugin_test.tf" + ConfigFileNameJSON = ConfigFileName + ".json" + PlanFileName = "tfplan" ) // WorkingDir represents a distinct working directory that can be used for @@ -28,6 +30,10 @@ type WorkingDir struct { // baseDir is the root of the working directory tree baseDir string + // configFilename is the full filename where the latest configuration + // was stored; empty until SetConfig is called. + configFilename string + // baseArgs is arguments that should be appended to all commands baseArgs []string @@ -40,8 +46,6 @@ type WorkingDir struct { // reattachInfo stores the gRPC socket info required for Terraform's // plugin reattach functionality reattachInfo tfexec.ReattachInfo - - env map[string]string } // Close deletes the directories and files created to represent the receiving @@ -51,20 +55,8 @@ func (wd *WorkingDir) Close() error { return os.RemoveAll(wd.baseDir) } -// Setenv sets an environment variable on the WorkingDir. -func (wd *WorkingDir) Setenv(envVar, val string) { - if wd.env == nil { - wd.env = map[string]string{} - } - wd.env[envVar] = val -} - -// Unsetenv removes an environment variable from the WorkingDir. -func (wd *WorkingDir) Unsetenv(envVar string) { - delete(wd.env, envVar) -} - -func (wd *WorkingDir) SetReattachInfo(reattachInfo tfexec.ReattachInfo) { +func (wd *WorkingDir) SetReattachInfo(ctx context.Context, reattachInfo tfexec.ReattachInfo) { + logging.HelperResourceTrace(ctx, "Setting Terraform CLI reattach configuration", map[string]interface{}{"tf_reattach_config": reattachInfo}) wd.reattachInfo = reattachInfo } @@ -82,29 +74,24 @@ func (wd *WorkingDir) GetHelper() *Helper { // This must be called at least once before any call to Init, Plan, Apply, or // Destroy to establish the configuration. Any previously-set configuration is // discarded and any saved plan is cleared. -func (wd *WorkingDir) SetConfig(cfg string) error { - configFilename := filepath.Join(wd.baseDir, ConfigFileName) - err := ioutil.WriteFile(configFilename, []byte(cfg), 0700) - if err != nil { - return err +func (wd *WorkingDir) SetConfig(ctx context.Context, cfg string) error { + outFilename := filepath.Join(wd.baseDir, ConfigFileName) + rmFilename := filepath.Join(wd.baseDir, ConfigFileNameJSON) + bCfg := []byte(cfg) + if json.Valid(bCfg) { + outFilename, rmFilename = rmFilename, outFilename } - - var mismatch *tfexec.ErrVersionMismatch - err = wd.tf.SetDisablePluginTLS(true) - if err != nil && !errors.As(err, &mismatch) { - return err + if err := os.Remove(rmFilename); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("unable to remove %q: %w", rmFilename, err) } - err = wd.tf.SetSkipProviderVerify(true) - if err != nil && !errors.As(err, &mismatch) { + err := ioutil.WriteFile(outFilename, bCfg, 0700) + if err != nil { return err } - - if p := os.Getenv("TF_ACC_LOG_PATH"); p != "" { - wd.tf.SetLogPath(p) - } + wd.configFilename = outFilename // Changing configuration invalidates any saved plan. - err = wd.ClearPlan() + err = wd.ClearPlan(ctx) if err != nil { return err } @@ -115,35 +102,66 @@ func (wd *WorkingDir) SetConfig(cfg string) error { // // Any remote objects tracked by the state are not destroyed first, so this // will leave them dangling in the remote system. -func (wd *WorkingDir) ClearState() error { +func (wd *WorkingDir) ClearState(ctx context.Context) error { + logging.HelperResourceTrace(ctx, "Clearing Terraform state") + err := os.Remove(filepath.Join(wd.baseDir, "terraform.tfstate")) + if os.IsNotExist(err) { + logging.HelperResourceTrace(ctx, "No Terraform state to clear") return nil } - return err + + if err != nil { + return err + } + + logging.HelperResourceTrace(ctx, "Cleared Terraform state") + + return nil } // ClearPlan deletes any saved plan present in the working directory. -func (wd *WorkingDir) ClearPlan() error { +func (wd *WorkingDir) ClearPlan(ctx context.Context) error { + logging.HelperResourceTrace(ctx, "Clearing Terraform plan") + err := os.Remove(wd.planFilename()) + if os.IsNotExist(err) { + logging.HelperResourceTrace(ctx, "No Terraform plan to clear") return nil } - return err + + if err != nil { + return err + } + + logging.HelperResourceTrace(ctx, "Cleared Terraform plan") + + return nil } +var errWorkingDirSetConfigNotCalled = fmt.Errorf("must call SetConfig before Init") + // Init runs "terraform init" for the given working directory, forcing Terraform // to use the current version of the plugin under test. -func (wd *WorkingDir) Init() error { - if _, err := os.Stat(wd.configFilename()); err != nil { - return fmt.Errorf("must call SetConfig before Init") +func (wd *WorkingDir) Init(ctx context.Context) error { + if wd.configFilename == "" { + return errWorkingDirSetConfigNotCalled + } + if _, err := os.Stat(wd.configFilename); err != nil { + return errWorkingDirSetConfigNotCalled } - return wd.tf.Init(context.Background(), tfexec.Reattach(wd.reattachInfo)) -} + logging.HelperResourceTrace(ctx, "Calling Terraform CLI init command") + + // -upgrade=true is required for per-TestStep provider version changes + // e.g. TestTest_TestStep_ExternalProviders_DifferentVersions + err := wd.tf.Init(context.Background(), tfexec.Reattach(wd.reattachInfo), tfexec.Upgrade(true)) -func (wd *WorkingDir) configFilename() string { - return filepath.Join(wd.baseDir, ConfigFileName) + logging.HelperResourceTrace(ctx, "Called Terraform CLI init command") + + return err } func (wd *WorkingDir) planFilename() string { @@ -152,15 +170,25 @@ func (wd *WorkingDir) planFilename() string { // CreatePlan runs "terraform plan" to create a saved plan file, which if successful // will then be used for the next call to Apply. -func (wd *WorkingDir) CreatePlan() error { +func (wd *WorkingDir) CreatePlan(ctx context.Context) error { + logging.HelperResourceTrace(ctx, "Calling Terraform CLI plan command") + _, err := wd.tf.Plan(context.Background(), tfexec.Reattach(wd.reattachInfo), tfexec.Refresh(false), tfexec.Out(PlanFileName)) + + logging.HelperResourceTrace(ctx, "Called Terraform CLI plan command") + return err } // CreateDestroyPlan runs "terraform plan -destroy" to create a saved plan // file, which if successful will then be used for the next call to Apply. -func (wd *WorkingDir) CreateDestroyPlan() error { +func (wd *WorkingDir) CreateDestroyPlan(ctx context.Context) error { + logging.HelperResourceTrace(ctx, "Calling Terraform CLI plan -destroy command") + _, err := wd.tf.Plan(context.Background(), tfexec.Reattach(wd.reattachInfo), tfexec.Refresh(false), tfexec.Out(PlanFileName), tfexec.Destroy(true)) + + logging.HelperResourceTrace(ctx, "Called Terraform CLI plan -destroy command") + return err } @@ -168,13 +196,19 @@ func (wd *WorkingDir) CreateDestroyPlan() error { // successfully and the saved plan has not been cleared in the meantime then // this will apply the saved plan. Otherwise, it will implicitly create a new // plan and apply it. -func (wd *WorkingDir) Apply() error { +func (wd *WorkingDir) Apply(ctx context.Context) error { args := []tfexec.ApplyOption{tfexec.Reattach(wd.reattachInfo), tfexec.Refresh(false)} if wd.HasSavedPlan() { args = append(args, tfexec.DirOrPlan(PlanFileName)) } - return wd.tf.Apply(context.Background(), args...) + logging.HelperResourceTrace(ctx, "Calling Terraform CLI apply command") + + err := wd.tf.Apply(context.Background(), args...) + + logging.HelperResourceTrace(ctx, "Called Terraform CLI apply command") + + return err } // Destroy runs "terraform destroy". It does not consider or modify any saved @@ -182,8 +216,14 @@ func (wd *WorkingDir) Apply() error { // // If destroy fails then remote objects might still exist, and continue to // exist after a particular test is concluded. -func (wd *WorkingDir) Destroy() error { - return wd.tf.Destroy(context.Background(), tfexec.Reattach(wd.reattachInfo), tfexec.Refresh(false)) +func (wd *WorkingDir) Destroy(ctx context.Context) error { + logging.HelperResourceTrace(ctx, "Calling Terraform CLI destroy command") + + err := wd.tf.Destroy(context.Background(), tfexec.Reattach(wd.reattachInfo), tfexec.Refresh(false)) + + logging.HelperResourceTrace(ctx, "Called Terraform CLI destroy command") + + return err } // HasSavedPlan returns true if there is a saved plan in the working directory. If @@ -197,19 +237,25 @@ func (wd *WorkingDir) HasSavedPlan() bool { // // If no plan is saved or if the plan file cannot be read, SavedPlan returns // an error. -func (wd *WorkingDir) SavedPlan() (*tfjson.Plan, error) { +func (wd *WorkingDir) SavedPlan(ctx context.Context) (*tfjson.Plan, error) { if !wd.HasSavedPlan() { return nil, fmt.Errorf("there is no current saved plan") } - return wd.tf.ShowPlanFile(context.Background(), wd.planFilename(), tfexec.Reattach(wd.reattachInfo)) + logging.HelperResourceTrace(ctx, "Calling Terraform CLI apply command") + + plan, err := wd.tf.ShowPlanFile(context.Background(), wd.planFilename(), tfexec.Reattach(wd.reattachInfo)) + + logging.HelperResourceTrace(ctx, "Calling Terraform CLI apply command") + + return plan, err } // SavedPlanRawStdout returns a human readable stdout capture of the current saved plan file, if any. // // If no plan is saved or if the plan file cannot be read, SavedPlanRawStdout returns // an error. -func (wd *WorkingDir) SavedPlanRawStdout() (string, error) { +func (wd *WorkingDir) SavedPlanRawStdout(ctx context.Context) (string, error) { if !wd.HasSavedPlan() { return "", fmt.Errorf("there is no current saved plan") } @@ -218,7 +264,13 @@ func (wd *WorkingDir) SavedPlanRawStdout() (string, error) { wd.tf.SetStdout(&ret) defer wd.tf.SetStdout(ioutil.Discard) + + logging.HelperResourceTrace(ctx, "Calling Terraform CLI show command") + _, err := wd.tf.ShowPlanFileRaw(context.Background(), wd.planFilename(), tfexec.Reattach(wd.reattachInfo)) + + logging.HelperResourceTrace(ctx, "Called Terraform CLI show command") + if err != nil { return "", err } @@ -230,23 +282,47 @@ func (wd *WorkingDir) SavedPlanRawStdout() (string, error) { // // If the state cannot be read, State returns an error. -func (wd *WorkingDir) State() (*tfjson.State, error) { - return wd.tf.Show(context.Background(), tfexec.Reattach(wd.reattachInfo)) +func (wd *WorkingDir) State(ctx context.Context) (*tfjson.State, error) { + logging.HelperResourceTrace(ctx, "Calling Terraform CLI show command") + + state, err := wd.tf.Show(context.Background(), tfexec.Reattach(wd.reattachInfo)) + + logging.HelperResourceTrace(ctx, "Called Terraform CLI show command") + + return state, err } // Import runs terraform import -func (wd *WorkingDir) Import(resource, id string) error { - return wd.tf.Import(context.Background(), resource, id, tfexec.Config(wd.baseDir), tfexec.Reattach(wd.reattachInfo)) +func (wd *WorkingDir) Import(ctx context.Context, resource, id string) error { + logging.HelperResourceTrace(ctx, "Calling Terraform CLI import command") + + err := wd.tf.Import(context.Background(), resource, id, tfexec.Config(wd.baseDir), tfexec.Reattach(wd.reattachInfo)) + + logging.HelperResourceTrace(ctx, "Called Terraform CLI import command") + + return err } // Refresh runs terraform refresh -func (wd *WorkingDir) Refresh() error { - return wd.tf.Refresh(context.Background(), tfexec.Reattach(wd.reattachInfo), tfexec.State(filepath.Join(wd.baseDir, "terraform.tfstate"))) +func (wd *WorkingDir) Refresh(ctx context.Context) error { + logging.HelperResourceTrace(ctx, "Calling Terraform CLI refresh command") + + err := wd.tf.Refresh(context.Background(), tfexec.Reattach(wd.reattachInfo)) + + logging.HelperResourceTrace(ctx, "Called Terraform CLI refresh command") + + return err } // Schemas returns an object describing the provider schemas. // // If the schemas cannot be read, Schemas returns an error. -func (wd *WorkingDir) Schemas() (*tfjson.ProviderSchemas, error) { - return wd.tf.ProvidersSchema(context.Background()) +func (wd *WorkingDir) Schemas(ctx context.Context) (*tfjson.ProviderSchemas, error) { + logging.HelperResourceTrace(ctx, "Calling Terraform CLI providers schema command") + + providerSchemas, err := wd.tf.ProvidersSchema(context.Background()) + + logging.HelperResourceTrace(ctx, "Called Terraform CLI providers schema command") + + return providerSchemas, err } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/debug.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/debug.go index 171451ca7f97..e1875e134cba 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/debug.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/debug.go @@ -2,13 +2,7 @@ package plugin import ( "context" - "encoding/json" "errors" - "fmt" - "os" - "os/signal" - "runtime" - "strings" "time" "github.com/hashicorp/go-plugin" @@ -37,6 +31,10 @@ func DebugServe(ctx context.Context, opts *ServeOpts) (ReattachConfig, <-chan st reattachCh := make(chan *plugin.ReattachConfig) closeCh := make(chan struct{}) + if opts == nil { + return ReattachConfig{}, closeCh, errors.New("ServeOpts must be passed in with at least GRPCProviderFunc, GRPCProviderV6Func, or ProviderFunc") + } + opts.TestConfig = &plugin.ServeTestConfig{ Context: ctx, ReattachConfigCh: reattachCh, @@ -71,48 +69,20 @@ func DebugServe(ctx context.Context, opts *ServeOpts) (ReattachConfig, <-chan st // Debug starts a debug server and controls its lifecycle, printing the // information needed for Terraform to connect to the provider to stdout. // os.Interrupt will be captured and used to stop the server. +// +// Deprecated: Use the Serve function with the ServeOpts Debug field instead. func Debug(ctx context.Context, providerAddr string, opts *ServeOpts) error { - ctx, cancel := context.WithCancel(ctx) - // Ctrl-C will stop the server - sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, os.Interrupt) - defer func() { - signal.Stop(sigCh) - cancel() - }() - config, closeCh, err := DebugServe(ctx, opts) - if err != nil { - return fmt.Errorf("Error launching debug server: %w", err) - } - go func() { - select { - case <-sigCh: - cancel() - case <-ctx.Done(): - } - }() - reattachBytes, err := json.Marshal(map[string]ReattachConfig{ - providerAddr: config, - }) - if err != nil { - return fmt.Errorf("Error building reattach string: %w", err) + if opts == nil { + return errors.New("ServeOpts must be passed in with at least GRPCProviderFunc, GRPCProviderV6Func, or ProviderFunc") } - reattachStr := string(reattachBytes) - - fmt.Printf("Provider started, to attach Terraform set the TF_REATTACH_PROVIDERS env var:\n\n") - switch runtime.GOOS { - case "windows": - fmt.Printf("\tCommand Prompt:\tset \"TF_REATTACH_PROVIDERS=%s\"\n", reattachStr) - fmt.Printf("\tPowerShell:\t$env:TF_REATTACH_PROVIDERS='%s'\n", strings.ReplaceAll(reattachStr, `'`, `''`)) - case "linux", "darwin": - fmt.Printf("\tTF_REATTACH_PROVIDERS='%s'\n", strings.ReplaceAll(reattachStr, `'`, `'"'"'`)) - default: - fmt.Println(reattachStr) + opts.Debug = true + + if opts.ProviderAddr == "" { + opts.ProviderAddr = providerAddr } - fmt.Println("") - // wait for the server to be done - <-closeCh + Serve(opts) + return nil } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/serve.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/serve.go index ac126642df1a..88975da2cb61 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/serve.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/serve.go @@ -1,12 +1,12 @@ package plugin import ( + "errors" "log" hclog "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-plugin" testing "github.com/mitchellh/go-testing-interface" - "google.golang.org/grpc" "github.com/hashicorp/terraform-plugin-go/tfprotov5" "github.com/hashicorp/terraform-plugin-go/tfprotov5/tf5server" @@ -18,10 +18,16 @@ import ( const ( // The constants below are the names of the plugins that can be dispensed // from the plugin server. + // + // Deprecated: This is no longer used, but left for backwards compatibility + // since it is exported. It will be removed in the next major version. ProviderPluginName = "provider" ) // Handshake is the HandshakeConfig used to configure clients and servers. +// +// Deprecated: This is no longer used, but left for backwards compatibility +// since it is exported. It will be removed in the next major version. var Handshake = plugin.HandshakeConfig{ // The magic cookie values should NEVER be changed. MagicCookieKey: "TF_PLUGIN_MAGIC_COOKIE", @@ -45,11 +51,20 @@ type ServeOpts struct { // Logger is the logger that go-plugin will use. Logger hclog.Logger + // Debug starts a debug server and controls its lifecycle, printing the + // information needed for Terraform to connect to the provider to stdout. + // os.Interrupt will be captured and used to stop the server. + // + // This option cannot be combined with TestConfig. + Debug bool + // TestConfig should only be set when the provider is being tested; it // will opt out of go-plugin's lifecycle management and other features, // and will use the supplied configuration options to control the // plugin's lifecycle and communicate connection information. See the // go-plugin GoDoc for more information. + // + // This option cannot be combined with Debug. TestConfig *plugin.ServeTestConfig // Set NoLogOutputOverride to not override the log output with an hclog @@ -69,6 +84,11 @@ type ServeOpts struct { // Serve serves a plugin. This function never returns and should be the final // function called in the main function of the plugin. func Serve(opts *ServeOpts) { + if opts.Debug && opts.TestConfig != nil { + log.Printf("[ERROR] Error starting provider: cannot set both Debug and TestConfig") + return + } + if !opts.NoLogOutputOverride { // In order to allow go-plugin to correctly pass log-levels through to // terraform, we need to use an hclog.Logger with JSON output. We can @@ -84,65 +104,125 @@ func Serve(opts *ServeOpts) { log.SetOutput(logger.StandardWriter(&hclog.StandardLoggerOptions{InferLevels: true})) } - // since the plugins may not yet be aware of the new protocol, we - // automatically wrap the plugins in the grpc shims. - if opts.GRPCProviderFunc == nil && opts.ProviderFunc != nil { + if opts.ProviderAddr == "" { + opts.ProviderAddr = "provider" + } + + var err error + + switch { + case opts.ProviderFunc != nil && opts.GRPCProviderFunc == nil: opts.GRPCProviderFunc = func() tfprotov5.ProviderServer { return schema.NewGRPCProviderServer(opts.ProviderFunc()) } + err = tf5serverServe(opts) + case opts.GRPCProviderFunc != nil: + err = tf5serverServe(opts) + case opts.GRPCProviderV6Func != nil: + err = tf6serverServe(opts) + default: + err = errors.New("no provider server defined in ServeOpts") } - serveConfig := plugin.ServeConfig{ - HandshakeConfig: Handshake, - GRPCServer: func(opts []grpc.ServerOption) *grpc.Server { - return grpc.NewServer(opts...) - }, - Logger: opts.Logger, - Test: opts.TestConfig, + if err != nil { + log.Printf("[ERROR] Error starting provider: %s", err) } +} - // assume we have either a v5 or a v6 provider - if opts.GRPCProviderFunc != nil { - provider := opts.GRPCProviderFunc() - addr := opts.ProviderAddr - if addr == "" { - addr = "provider" - } - serveConfig.VersionedPlugins = map[int]plugin.PluginSet{ - 5: { - ProviderPluginName: &tf5server.GRPCProviderPlugin{ - GRPCProvider: func() tfprotov5.ProviderServer { - return provider - }, - Name: addr, - }, - }, - } - if opts.UseTFLogSink != nil { - serveConfig.VersionedPlugins[5][ProviderPluginName].(*tf5server.GRPCProviderPlugin).Opts = append(serveConfig.VersionedPlugins[5][ProviderPluginName].(*tf5server.GRPCProviderPlugin).Opts, tf5server.WithLoggingSink(opts.UseTFLogSink)) - } +func tf5serverServe(opts *ServeOpts) error { + var tf5serveOpts []tf5server.ServeOpt - } else if opts.GRPCProviderV6Func != nil { - provider := opts.GRPCProviderV6Func() - addr := opts.ProviderAddr - if addr == "" { - addr = "provider" - } - serveConfig.VersionedPlugins = map[int]plugin.PluginSet{ - 6: { - ProviderPluginName: &tf6server.GRPCProviderPlugin{ - GRPCProvider: func() tfprotov6.ProviderServer { - return provider - }, - Name: addr, - }, - }, - } - if opts.UseTFLogSink != nil { - serveConfig.VersionedPlugins[6][ProviderPluginName].(*tf6server.GRPCProviderPlugin).Opts = append(serveConfig.VersionedPlugins[6][ProviderPluginName].(*tf6server.GRPCProviderPlugin).Opts, tf6server.WithLoggingSink(opts.UseTFLogSink)) - } + if opts.Debug { + tf5serveOpts = append(tf5serveOpts, tf5server.WithManagedDebug()) + } + + if opts.Logger != nil { + tf5serveOpts = append(tf5serveOpts, tf5server.WithGoPluginLogger(opts.Logger)) + } + + if opts.TestConfig != nil { + // Convert send-only channels to bi-directional channels to appease + // the compiler. WithDebug is errantly defined to require + // bi-directional when send-only is actually needed, which may be + // fixed in the future so the opts.TestConfig channels can be passed + // through directly. + closeCh := make(chan struct{}) + reattachConfigCh := make(chan *plugin.ReattachConfig) + + go func() { + // Always forward close channel receive, since its signaling that + // the channel is closed. + val := <-closeCh + opts.TestConfig.CloseCh <- val + }() + + go func() { + val, ok := <-reattachConfigCh + + if ok { + opts.TestConfig.ReattachConfigCh <- val + } + }() + + tf5serveOpts = append(tf5serveOpts, tf5server.WithDebug( + opts.TestConfig.Context, + reattachConfigCh, + closeCh), + ) + } + + if opts.UseTFLogSink != nil { + tf5serveOpts = append(tf5serveOpts, tf5server.WithLoggingSink(opts.UseTFLogSink)) + } + + return tf5server.Serve(opts.ProviderAddr, opts.GRPCProviderFunc, tf5serveOpts...) +} + +func tf6serverServe(opts *ServeOpts) error { + var tf6serveOpts []tf6server.ServeOpt + + if opts.Debug { + tf6serveOpts = append(tf6serveOpts, tf6server.WithManagedDebug()) + } + + if opts.Logger != nil { + tf6serveOpts = append(tf6serveOpts, tf6server.WithGoPluginLogger(opts.Logger)) + } + + if opts.TestConfig != nil { + // Convert send-only channels to bi-directional channels to appease + // the compiler. WithDebug is errantly defined to require + // bi-directional when send-only is actually needed, which may be + // fixed in the future so the opts.TestConfig channels can be passed + // through directly. + closeCh := make(chan struct{}) + reattachConfigCh := make(chan *plugin.ReattachConfig) + + go func() { + // Always forward close channel receive, since its signaling that + // the channel is closed. + val := <-closeCh + opts.TestConfig.CloseCh <- val + }() + + go func() { + val, ok := <-reattachConfigCh + + if ok { + opts.TestConfig.ReattachConfigCh <- val + } + }() + + tf6serveOpts = append(tf6serveOpts, tf6server.WithDebug( + opts.TestConfig.Context, + reattachConfigCh, + closeCh), + ) + } + if opts.UseTFLogSink != nil { + tf6serveOpts = append(tf6serveOpts, tf6server.WithLoggingSink(opts.UseTFLogSink)) } - plugin.Serve(&serveConfig) + return tf6server.Serve(opts.ProviderAddr, opts.GRPCProviderV6Func, tf6serveOpts...) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/diff.go index 0511a1fc5e8a..8a2940f31e22 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/diff.go @@ -20,7 +20,7 @@ import ( type diffChangeType byte const ( - diffInvalid diffChangeType = iota + diffInvalid diffChangeType = iota //nolint:deadcode,varcheck diffNone diffCreate diffUpdate diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource.go index 11b63de8a299..703547745e83 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource.go @@ -154,13 +154,13 @@ func (c *ResourceConfig) DeepCopy() *ResourceConfig { } // Copy, this will copy all the exported attributes - copy, err := copystructure.Config{Lock: true}.Copy(c) + copiedConfig, err := copystructure.Config{Lock: true}.Copy(c) if err != nil { panic(err) } // Force the type - result := copy.(*ResourceConfig) + result := copiedConfig.(*ResourceConfig) return result } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state.go index 7f8655ee7d89..170e20cd0adb 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state.go @@ -366,11 +366,11 @@ func (s *State) Remove(addr ...string) error { switch v := r.Value.(type) { case *ModuleState: - s.removeModule(path, v) + s.removeModule(v) case *ResourceState: s.removeResource(path, v) case *InstanceState: - s.removeInstance(path, r.Parent.Value.(*ResourceState), v) + s.removeInstance(r.Parent.Value.(*ResourceState), v) default: return fmt.Errorf("unknown type to delete: %T", r.Value) } @@ -384,7 +384,7 @@ func (s *State) Remove(addr ...string) error { return nil } -func (s *State) removeModule(path []string, v *ModuleState) { +func (s *State) removeModule(v *ModuleState) { for i, m := range s.Modules { if m == v { s.Modules, s.Modules[len(s.Modules)-1] = append(s.Modules[:i], s.Modules[i+1:]...), nil @@ -412,7 +412,7 @@ func (s *State) removeResource(path []string, v *ResourceState) { } } -func (s *State) removeInstance(path []string, r *ResourceState, v *InstanceState) { +func (s *State) removeInstance(r *ResourceState, v *InstanceState) { // Go through the resource and find the instance that matches this // (if any) and remove it. @@ -421,20 +421,6 @@ func (s *State) removeInstance(path []string, r *ResourceState, v *InstanceState r.Primary = nil return } - - // Check lists - lists := [][]*InstanceState{r.Deposed} - for _, is := range lists { - for i, instance := range is { - if instance == v { - // Found it, remove it - is, is[len(is)-1] = append(is[:i], is[i+1:]...), nil - - // Done - return - } - } - } } // RootModule returns the ModuleState for the root module @@ -562,12 +548,12 @@ func (s *State) DeepCopy() *State { return nil } - copy, err := copystructure.Config{Lock: true}.Copy(s) + copiedState, err := copystructure.Config{Lock: true}.Copy(s) if err != nil { panic(err) } - return copy.(*State) + return copiedState.(*State) } func (s *State) Init() { @@ -1023,7 +1009,7 @@ func (m *ModuleState) String() string { } if len(rs.Dependencies) > 0 { - buf.WriteString(fmt.Sprintf("\n Dependencies:\n")) + buf.WriteString("\n Dependencies:\n") for _, dep := range rs.Dependencies { buf.WriteString(fmt.Sprintf(" %s\n", dep)) } @@ -1237,11 +1223,7 @@ func (s *ResourceState) Equal(other *ResourceState) bool { } // States must be equal - if !s.Primary.Equal(other.Primary) { - return false - } - - return true + return s.Primary.Equal(other.Primary) } // Taint marks a resource as tainted. @@ -1430,12 +1412,12 @@ func (s *InstanceState) Set(from *InstanceState) { } func (s *InstanceState) DeepCopy() *InstanceState { - copy, err := copystructure.Config{Lock: true}.Copy(s) + copiedState, err := copystructure.Config{Lock: true}.Copy(s) if err != nil { panic(err) } - return copy.(*InstanceState) + return copiedState.(*InstanceState) } func (s *InstanceState) Empty() bool { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state_filter.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state_filter.go index 01d039272e36..d2229f8ce763 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state_filter.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state_filter.go @@ -24,7 +24,15 @@ type stateFilter struct { // parseResourceAddress. func (f *stateFilter) filter(fs ...string) ([]*stateFilterResult, error) { // Parse all the addresses - as := make([]*resourceAddress, len(fs)) + var as []*resourceAddress + + if len(fs) == 0 { + // If we weren't given any filters, then we list all + as = []*resourceAddress{{Index: -1}} + } else { + as = make([]*resourceAddress, len(fs)) + } + for i, v := range fs { a, err := parseResourceAddress(v) if err != nil { @@ -34,11 +42,6 @@ func (f *stateFilter) filter(fs ...string) ([]*stateFilterResult, error) { as[i] = a } - // If we weren't given any filters, then we list all - if len(fs) == 0 { - as = append(as, &resourceAddress{Index: -1}) - } - // Filter each of the address. We keep track of this in a map to // strip duplicates. resultSet := make(map[string]*stateFilterResult) diff --git a/vendor/github.com/hashicorp/terraform-registry-address/.go-version b/vendor/github.com/hashicorp/terraform-registry-address/.go-version index 42cf0675c566..adc97d8e2213 100644 --- a/vendor/github.com/hashicorp/terraform-registry-address/.go-version +++ b/vendor/github.com/hashicorp/terraform-registry-address/.go-version @@ -1 +1 @@ -1.15.2 +1.18 diff --git a/vendor/github.com/hashicorp/terraform-registry-address/README.md b/vendor/github.com/hashicorp/terraform-registry-address/README.md index 2ed8398da704..27db81f7c1c1 100644 --- a/vendor/github.com/hashicorp/terraform-registry-address/README.md +++ b/vendor/github.com/hashicorp/terraform-registry-address/README.md @@ -1,46 +1,149 @@ # terraform-registry-address -This package helps with representation, comparison and parsing of -Terraform Registry addresses, such as -`registry.terraform.io/grafana/grafana` or `hashicorp/aws`. +This module enables parsing, comparison and canonical representation of +[Terraform Registry](https://registry.terraform.io/) **provider** addresses +(such as `registry.terraform.io/grafana/grafana` or `hashicorp/aws`) +and **module** addresses (such as `hashicorp/subnets/cidr`). -The most common source of these addresses outside of Terraform Core -is JSON representation of state, plan, or schemas as obtained -via [`hashicorp/terraform-exec`](https://github.com/hashicorp/terraform-exec). +**Provider** addresses can be found in -## Example + - [`terraform show -json `](https://www.terraform.io/internals/json-format#configuration-representation) (`full_name`) + - [`terraform version -json`](https://www.terraform.io/cli/commands/version#example) (`provider_selections`) + - [`terraform providers schema -json`](https://www.terraform.io/cli/commands/providers/schema#providers-schema-representation) (keys of `provider_schemas`) + - within `required_providers` block in Terraform configuration (`*.tf`) + - Terraform [CLI configuration file](https://www.terraform.io/cli/config/config-file#provider-installation) + - Plugin [reattach configurations](https://www.terraform.io/plugin/debugging#running-terraform-with-a-provider-in-debug-mode) + +**Module** addresses can be found within `source` argument +of `module` block in Terraform configuration (`*.tf`) +and parts of the address (namespace and name) in the Registry API. + +## Compatibility + +The module assumes compatibility with Terraform v0.12 and later, +which have the mentioned JSON output produced by corresponding CLI flags. + +We recommend carefully reading the [ambigouous provider addresses](#Ambiguous-Provider-Addresses) +section below which may impact versions `0.12` and `0.13`. + +## Related Libraries + +Other libraries which may help with consuming most of the above Terraform +outputs in automation: + + - [`hashicorp/terraform-exec`](https://github.com/hashicorp/terraform-exec) + - [`hashicorp/terraform-json`](https://github.com/hashicorp/terraform-json) + +## Usage + +### Provider ```go -p, err := ParseRawProviderSourceString("hashicorp/aws") +pAddr, err := ParseProviderSource("hashicorp/aws") if err != nil { // deal with error } -// p == Provider{ +// pAddr == Provider{ // Type: "aws", // Namespace: "hashicorp", -// Hostname: svchost.Hostname("registry.terraform.io"), +// Hostname: DefaultProviderRegistryHost, // } ``` -## Legacy address +### Module + +```go +mAddr, err := ParseModuleSource("hashicorp/consul/aws//modules/consul-cluster") +if err != nil { + // deal with error +} + +// mAddr == Module{ +// Package: ModulePackage{ +// Host: DefaultProviderRegistryHost, +// Namespace: "hashicorp", +// Name: "consul", +// TargetSystem: "aws", +// }, +// Subdir: "modules/consul-cluster", +// }, +``` + +## Other Module Address Formats + +Modules can also be sourced from [other sources](https://www.terraform.io/language/modules/sources) +and these other sources (outside of Terraform Registry) +have different address formats, such as `./local` or +`github.com/hashicorp/example`. + +This library does _not_ recognize such other address formats +and it will return error upon parsing these. + +## Ambiguous Provider Addresses + +Qualified addresses with namespace (such as `hashicorp/aws`) +are used exclusively in all recent versions (`0.14+`) of Terraform. +If you only work with Terraform `v0.14.0+` configuration/output, you may +safely ignore the rest of this section and related part of the API. + +There are a few types of ambiguous addresses you may comes accross: + + - Terraform `v0.12` uses "namespace-less address", such as `aws`. + - Terraform `v0.13` may use `-` as a placeholder for the unknown namespace, + resulting in address such as `-/aws`. + - Terraform `v0.14+` _configuration_ still allows ambiguous providers + through `provider "" {}` block _without_ corresponding + entry inside `required_providers`, but these providers are always + resolved as `hashicorp/` and all JSON outputs only use that + resolved address. + +Both ambiguous address formats are accepted by `ParseProviderSource()` -A legacy address is by itself (without more context) ambiguous. -For example `aws` may represent either the official `hashicorp/aws` -or just any custom-built provider called `aws`. +```go +pAddr, err := ParseProviderSource("aws") +if err != nil { + // deal with error +} + +// pAddr == Provider{ +// Type: "aws", +// Namespace: UnknownProviderNamespace, // "?" +// Hostname: DefaultProviderRegistryHost, // "registry.terraform.io" +// } +pAddr.HasKnownNamespace() // == false +pAddr.IsLegacy() // == false +``` +```go +pAddr, err := ParseProviderSource("-/aws") +if err != nil { + // deal with error +} -Such ambiguous address can be produced by Terraform `<=0.12`. You can -just use `ImpliedProviderForUnqualifiedType` if you know for sure -the address was produced by an affected version. +// pAddr == Provider{ +// Type: "aws", +// Namespace: LegacyProviderNamespace, // "-" +// Hostname: DefaultProviderRegistryHost, // "registry.terraform.io" +// } +pAddr.HasKnownNamespace() // == true +pAddr.IsLegacy() // == true +``` -If you do not have that context you should parse the string via -`ParseRawProviderSourceString` and then check `addr.IsLegacy()`. +However `NewProvider()` will panic if you pass an empty namespace +or any placeholder indicating unknown namespace. + +```go +NewProvider(DefaultProviderRegistryHost, "", "aws") // panic +NewProvider(DefaultProviderRegistryHost, "-", "aws") // panic +NewProvider(DefaultProviderRegistryHost, "?", "aws") // panic +``` -### What to do with a legacy address? +If you come across an ambiguous address, you should resolve +it to a fully qualified one and use that one instead. -Ask the Registry API whether and where the provider was moved to +### Resolving Ambiguous Address -(`-` represents the legacy, basically unknown namespace) +The Registry API provides the safest way of resolving an ambiguous address. ```sh # grafana (redirected to its own namespace) @@ -54,28 +157,15 @@ $ curl -s https://registry.terraform.io/v1/providers/-/aws/versions | jq '(.id, null ``` -Then: +When you cache results, ensure you have invalidation +mechanism in place as target (migrated) namespace may change. - - Reparse the _new_ address (`moved_to`) of any _moved_ provider (e.g. `grafana/grafana`) via `ParseRawProviderSourceString` - - Reparse the full address (`id`) of any other provider (e.g. `hashicorp/aws`) - -Depending on context (legacy) `terraform` may need to be parsed separately. -Read more about this provider below. - -If for some reason you cannot ask the Registry API you may also use -`ParseAndInferProviderSourceString` which assumes that any legacy address -(including `terraform`) belongs to the `hashicorp` namespace. - -If you cache results (which you should), ensure you have invalidation -mechanism in place because target (migrated) namespace may change. -Hard-coding migrations anywhere in code is strongly discouraged. - -### `terraform` provider +#### `terraform` provider Like any other legacy address `terraform` is also ambiguous. Such address may (most unlikely) represent a custom-built provider called `terraform`, or the now archived [`hashicorp/terraform` provider in the registry](https://registry.terraform.io/providers/hashicorp/terraform/latest), -or (most likely) the `terraform` provider built into 0.12+, which is +or (most likely) the `terraform` provider built into 0.11+, which is represented via a dedicated FQN of `terraform.io/builtin/terraform` in 0.13+. You may be able to differentiate between these different providers if you @@ -85,4 +175,7 @@ Alternatively you may just treat the address as the builtin provider, i.e. assume all of its logic including schema is contained within Terraform Core. -In such case you should just use `NewBuiltInProvider("terraform")`. +In such case you should construct the address in the following way +```go +pAddr := NewProvider(BuiltInProviderHost, BuiltInProviderNamespace, "terraform") +``` diff --git a/vendor/github.com/hashicorp/terraform-registry-address/module.go b/vendor/github.com/hashicorp/terraform-registry-address/module.go new file mode 100644 index 000000000000..6af0c5976b54 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-registry-address/module.go @@ -0,0 +1,251 @@ +package tfaddr + +import ( + "fmt" + "path" + "regexp" + "strings" + + svchost "github.com/hashicorp/terraform-svchost" +) + +// Module is representing a module listed in a Terraform module +// registry. +type Module struct { + // Package is the registry package that the target module belongs to. + // The module installer must translate this into a ModuleSourceRemote + // using the registry API and then take that underlying address's + // Package in order to find the actual package location. + Package ModulePackage + + // If Subdir is non-empty then it represents a sub-directory within the + // remote package that the registry address eventually resolves to. + // This will ultimately become the suffix of the Subdir of the + // ModuleSourceRemote that the registry address translates to. + // + // Subdir uses a normalized forward-slash-based path syntax within the + // virtual filesystem represented by the final package. It will never + // include `../` or `./` sequences. + Subdir string +} + +// DefaultModuleRegistryHost is the hostname used for registry-based module +// source addresses that do not have an explicit hostname. +const DefaultModuleRegistryHost = svchost.Hostname("registry.terraform.io") + +var moduleRegistryNamePattern = regexp.MustCompile("^[0-9A-Za-z](?:[0-9A-Za-z-_]{0,62}[0-9A-Za-z])?$") +var moduleRegistryTargetSystemPattern = regexp.MustCompile("^[0-9a-z]{1,64}$") + +// ParseModuleSource only accepts module registry addresses, and +// will reject any other address type. +func ParseModuleSource(raw string) (Module, error) { + var err error + + var subDir string + raw, subDir = splitPackageSubdir(raw) + if strings.HasPrefix(subDir, "../") { + return Module{}, fmt.Errorf("subdirectory path %q leads outside of the module package", subDir) + } + + parts := strings.Split(raw, "/") + // A valid registry address has either three or four parts, because the + // leading hostname part is optional. + if len(parts) != 3 && len(parts) != 4 { + return Module{}, fmt.Errorf("a module registry source address must have either three or four slash-separated components") + } + + host := DefaultModuleRegistryHost + if len(parts) == 4 { + host, err = svchost.ForComparison(parts[0]) + if err != nil { + // The svchost library doesn't produce very good error messages to + // return to an end-user, so we'll use some custom ones here. + switch { + case strings.Contains(parts[0], "--"): + // Looks like possibly punycode, which we don't allow here + // to ensure that source addresses are written readably. + return Module{}, fmt.Errorf("invalid module registry hostname %q; internationalized domain names must be given as direct unicode characters, not in punycode", parts[0]) + default: + return Module{}, fmt.Errorf("invalid module registry hostname %q", parts[0]) + } + } + if !strings.Contains(host.String(), ".") { + return Module{}, fmt.Errorf("invalid module registry hostname: must contain at least one dot") + } + // Discard the hostname prefix now that we've processed it + parts = parts[1:] + } + + ret := Module{ + Package: ModulePackage{ + Host: host, + }, + + Subdir: subDir, + } + + if host == svchost.Hostname("github.com") || host == svchost.Hostname("bitbucket.org") { + return ret, fmt.Errorf("can't use %q as a module registry host, because it's reserved for installing directly from version control repositories", host) + } + + if ret.Package.Namespace, err = parseModuleRegistryName(parts[0]); err != nil { + if strings.Contains(parts[0], ".") { + // Seems like the user omitted one of the latter components in + // an address with an explicit hostname. + return ret, fmt.Errorf("source address must have three more components after the hostname: the namespace, the name, and the target system") + } + return ret, fmt.Errorf("invalid namespace %q: %s", parts[0], err) + } + if ret.Package.Name, err = parseModuleRegistryName(parts[1]); err != nil { + return ret, fmt.Errorf("invalid module name %q: %s", parts[1], err) + } + if ret.Package.TargetSystem, err = parseModuleRegistryTargetSystem(parts[2]); err != nil { + if strings.Contains(parts[2], "?") { + // The user was trying to include a query string, probably? + return ret, fmt.Errorf("module registry addresses may not include a query string portion") + } + return ret, fmt.Errorf("invalid target system %q: %s", parts[2], err) + } + + return ret, nil +} + +// MustParseModuleSource is a wrapper around ParseModuleSource that panics if +// it returns an error. +func MustParseModuleSource(raw string) (Module) { + mod, err := ParseModuleSource(raw) + if err != nil { + panic(err) + } + return mod +} + +// parseModuleRegistryName validates and normalizes a string in either the +// "namespace" or "name" position of a module registry source address. +func parseModuleRegistryName(given string) (string, error) { + // Similar to the names in provider source addresses, we defined these + // to be compatible with what filesystems and typical remote systems + // like GitHub allow in names. Unfortunately we didn't end up defining + // these exactly equivalently: provider names can only use dashes as + // punctuation, whereas module names can use underscores. So here we're + // using some regular expressions from the original module source + // implementation, rather than using the IDNA rules as we do in + // ParseProviderPart. + + if !moduleRegistryNamePattern.MatchString(given) { + return "", fmt.Errorf("must be between one and 64 characters, including ASCII letters, digits, dashes, and underscores, where dashes and underscores may not be the prefix or suffix") + } + + // We also skip normalizing the name to lowercase, because we historically + // didn't do that and so existing module registries might be doing + // case-sensitive matching. + return given, nil +} + +// parseModuleRegistryTargetSystem validates and normalizes a string in the +// "target system" position of a module registry source address. This is +// what we historically called "provider" but never actually enforced as +// being a provider address, and now _cannot_ be a provider address because +// provider addresses have three slash-separated components of their own. +func parseModuleRegistryTargetSystem(given string) (string, error) { + // Similar to the names in provider source addresses, we defined these + // to be compatible with what filesystems and typical remote systems + // like GitHub allow in names. Unfortunately we didn't end up defining + // these exactly equivalently: provider names can't use dashes or + // underscores. So here we're using some regular expressions from the + // original module source implementation, rather than using the IDNA rules + // as we do in ParseProviderPart. + + if !moduleRegistryTargetSystemPattern.MatchString(given) { + return "", fmt.Errorf("must be between one and 64 ASCII letters or digits") + } + + // We also skip normalizing the name to lowercase, because we historically + // didn't do that and so existing module registries might be doing + // case-sensitive matching. + return given, nil +} + +// String returns a full representation of the address, including any +// additional components that are typically implied by omission in +// user-written addresses. +// +// We typically use this longer representation in error message, in case +// the inclusion of normally-omitted components is helpful in debugging +// unexpected behavior. +func (s Module) String() string { + if s.Subdir != "" { + return s.Package.String() + "//" + s.Subdir + } + return s.Package.String() +} + +// ForDisplay is similar to String but instead returns a representation of +// the idiomatic way to write the address in configuration, omitting +// components that are commonly just implied in addresses written by +// users. +// +// We typically use this shorter representation in informational messages, +// such as the note that we're about to start downloading a package. +func (s Module) ForDisplay() string { + if s.Subdir != "" { + return s.Package.ForDisplay() + "//" + s.Subdir + } + return s.Package.ForDisplay() +} + +// splitPackageSubdir detects whether the given address string has a +// subdirectory portion, and if so returns a non-empty subDir string +// along with the trimmed package address. +// +// If the given string doesn't have a subdirectory portion then it'll +// just be returned verbatim in packageAddr, with an empty subDir value. +func splitPackageSubdir(given string) (packageAddr, subDir string) { + packageAddr, subDir = sourceDirSubdir(given) + if subDir != "" { + subDir = path.Clean(subDir) + } + return packageAddr, subDir +} + +// sourceDirSubdir takes a source URL and returns a tuple of the URL without +// the subdir and the subdir. +// +// ex: +// dom.com/path/?q=p => dom.com/path/?q=p, "" +// proto://dom.com/path//*?q=p => proto://dom.com/path?q=p, "*" +// proto://dom.com/path//path2?q=p => proto://dom.com/path?q=p, "path2" +func sourceDirSubdir(src string) (string, string) { + // URL might contains another url in query parameters + stop := len(src) + if idx := strings.Index(src, "?"); idx > -1 { + stop = idx + } + + // Calculate an offset to avoid accidentally marking the scheme + // as the dir. + var offset int + if idx := strings.Index(src[:stop], "://"); idx > -1 { + offset = idx + 3 + } + + // First see if we even have an explicit subdir + idx := strings.Index(src[offset:stop], "//") + if idx == -1 { + return src, "" + } + + idx += offset + subdir := src[idx+2:] + src = src[:idx] + + // Next, check if we have query parameters and push them onto the + // URL. + if idx = strings.Index(subdir, "?"); idx > -1 { + query := subdir[idx:] + subdir = subdir[:idx] + src += query + } + + return src, subdir +} diff --git a/vendor/github.com/hashicorp/terraform-registry-address/module_package.go b/vendor/github.com/hashicorp/terraform-registry-address/module_package.go new file mode 100644 index 000000000000..d8ad2534a096 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-registry-address/module_package.go @@ -0,0 +1,58 @@ +package tfaddr + +import ( + "strings" + + svchost "github.com/hashicorp/terraform-svchost" +) + +// A ModulePackage is an extra indirection over a ModulePackage where +// we use a module registry to translate a more symbolic address (and +// associated version constraint given out of band) into a physical source +// location. +// +// ModulePackage is distinct from ModulePackage because they have +// disjoint use-cases: registry package addresses are only used to query a +// registry in order to find a real module package address. These being +// distinct is intended to help future maintainers more easily follow the +// series of steps in the module installer, with the help of the type checker. +type ModulePackage struct { + Host svchost.Hostname + Namespace string + Name string + TargetSystem string +} + +func (s ModulePackage) String() string { + // Note: we're using the "display" form of the hostname here because + // for our service hostnames "for display" means something different: + // it means to render non-ASCII characters directly as Unicode + // characters, rather than using the "punycode" representation we + // use for internal processing, and so the "display" representation + // is actually what users would write in their configurations. + return s.Host.ForDisplay() + "/" + s.ForRegistryProtocol() +} + +func (s ModulePackage) ForDisplay() string { + if s.Host == DefaultModuleRegistryHost { + return s.ForRegistryProtocol() + } + return s.Host.ForDisplay() + "/" + s.ForRegistryProtocol() +} + +// ForRegistryProtocol returns a string representation of just the namespace, +// name, and target system portions of the address, always omitting the +// registry hostname and the subdirectory portion, if any. +// +// This is primarily intended for generating addresses to send to the +// registry in question via the registry protocol, since the protocol +// skips sending the registry its own hostname as part of identifiers. +func (s ModulePackage) ForRegistryProtocol() string { + var buf strings.Builder + buf.WriteString(s.Namespace) + buf.WriteByte('/') + buf.WriteString(s.Name) + buf.WriteByte('/') + buf.WriteString(s.TargetSystem) + return buf.String() +} diff --git a/vendor/github.com/hashicorp/terraform-registry-address/provider.go b/vendor/github.com/hashicorp/terraform-registry-address/provider.go index 4dd0a5b78132..23e1e221f2f7 100644 --- a/vendor/github.com/hashicorp/terraform-registry-address/provider.go +++ b/vendor/github.com/hashicorp/terraform-registry-address/provider.go @@ -16,9 +16,9 @@ type Provider struct { Hostname svchost.Hostname } -// DefaultRegistryHost is the hostname used for provider addresses that do +// DefaultProviderRegistryHost is the hostname used for provider addresses that do // not have an explicit hostname. -const DefaultRegistryHost = svchost.Hostname("registry.terraform.io") +const DefaultProviderRegistryHost = svchost.Hostname("registry.terraform.io") // BuiltInProviderHost is the pseudo-hostname used for the "built-in" provider // namespace. Built-in provider addresses must also have their namespace set @@ -34,11 +34,18 @@ const BuiltInProviderHost = svchost.Hostname("terraform.io") // special, even if they haven't encountered the concept formally yet. const BuiltInProviderNamespace = "builtin" +// UnknownProviderNamespace is the special string used to indicate +// unknown namespace, e.g. in "aws". This is equivalent to +// LegacyProviderNamespace for <0.12 style address. This namespace +// would never be produced by Terraform itself explicitly, it is +// only an internal placeholder. +const UnknownProviderNamespace = "?" + // LegacyProviderNamespace is the special string used in the Namespace field // of type Provider to mark a legacy provider address. This special namespace // value would normally be invalid, and can be used only when the hostname is -// DefaultRegistryHost because that host owns the mapping from legacy name to -// FQN. +// DefaultProviderRegistryHost because that host owns the mapping from legacy name to +// FQN. This may be produced by Terraform 0.13. const LegacyProviderNamespace = "-" // String returns an FQN string, indended for use in machine-readable output. @@ -56,7 +63,7 @@ func (pt Provider) ForDisplay() string { panic("called ForDisplay on zero-value addrs.Provider") } - if pt.Hostname == DefaultRegistryHost { + if pt.Hostname == DefaultProviderRegistryHost { return pt.Namespace + "/" + pt.Type } return pt.Hostname.ForDisplay() + "/" + pt.Namespace + "/" + pt.Type @@ -75,10 +82,18 @@ func (pt Provider) ForDisplay() string { // ParseProviderPart first to check that the given value is valid. func NewProvider(hostname svchost.Hostname, namespace, typeName string) Provider { if namespace == LegacyProviderNamespace { - // Legacy provider addresses must always be created via - // NewLegacyProvider so that we can use static analysis to find - // codepaths still working with those. - panic("attempt to create legacy provider address using NewProvider; use NewLegacyProvider instead") + // Legacy provider addresses must always be created via struct + panic("attempt to create legacy provider address using NewProvider; use Provider{} instead") + } + if namespace == UnknownProviderNamespace { + // Provider addresses with unknown namespace must always + // be created via struct + panic("attempt to create provider address with unknown namespace using NewProvider; use Provider{} instead") + } + if namespace == "" { + // This case is already handled by MustParseProviderPart() below, + // but we catch it early to provide more helpful message. + panic("attempt to create provider address with empty namespace") } return Provider{ @@ -88,63 +103,6 @@ func NewProvider(hostname svchost.Hostname, namespace, typeName string) Provider } } -// ImpliedProviderForUnqualifiedType represents the rules for inferring what -// provider FQN a user intended when only a naked type name is available. -// -// For all except the type name "terraform" this returns a so-called "default" -// provider, which is under the registry.terraform.io/hashicorp/ namespace. -// -// As a special case, the string "terraform" maps to -// "terraform.io/builtin/terraform" because that is the more likely user -// intent than the now-unmaintained "registry.terraform.io/hashicorp/terraform" -// which remains only for compatibility with older Terraform versions. -func ImpliedProviderForUnqualifiedType(typeName string) Provider { - switch typeName { - case "terraform": - // Note for future maintainers: any additional strings we add here - // as implied to be builtin must never also be use as provider names - // in the registry.terraform.io/hashicorp/... namespace, because - // otherwise older versions of Terraform could implicitly select - // the registry name instead of the internal one. - return NewBuiltInProvider(typeName) - default: - return NewDefaultProvider(typeName) - } -} - -// NewDefaultProvider returns the default address of a HashiCorp-maintained, -// Registry-hosted provider. -func NewDefaultProvider(name string) Provider { - return Provider{ - Type: MustParseProviderPart(name), - Namespace: "hashicorp", - Hostname: DefaultRegistryHost, - } -} - -// NewBuiltInProvider returns the address of a "built-in" provider. See -// the docs for Provider.IsBuiltIn for more information. -func NewBuiltInProvider(name string) Provider { - return Provider{ - Type: MustParseProviderPart(name), - Namespace: BuiltInProviderNamespace, - Hostname: BuiltInProviderHost, - } -} - -// NewLegacyProvider returns a mock address for a provider. -// This will be removed when ProviderType is fully integrated. -func NewLegacyProvider(name string) Provider { - return Provider{ - // We intentionally don't normalize and validate the legacy names, - // because existing code expects legacy provider names to pass through - // verbatim, even if not compliant with our new naming rules. - Type: name, - Namespace: LegacyProviderNamespace, - Hostname: DefaultRegistryHost, - } -} - // LegacyString returns the provider type, which is frequently used // interchangeably with provider name. This function can and should be removed // when provider type is fully integrated. As a safeguard for future @@ -167,6 +125,12 @@ func (pt Provider) IsZero() bool { return pt == Provider{} } +// HasKnownNamespace returns true if the provider namespace is known +// (also if it is legacy namespace) +func (pt Provider) HasKnownNamespace() bool { + return pt.Namespace != UnknownProviderNamespace +} + // IsBuiltIn returns true if the receiver is the address of a "built-in" // provider. That is, a provider under terraform.io/builtin/ which is // included as part of the Terraform binary itself rather than one to be @@ -201,25 +165,16 @@ func (pt Provider) IsLegacy() bool { panic("called IsLegacy() on zero-value addrs.Provider") } - return pt.Hostname == DefaultRegistryHost && pt.Namespace == LegacyProviderNamespace + return pt.Hostname == DefaultProviderRegistryHost && pt.Namespace == LegacyProviderNamespace } -// IsDefault returns true if the provider is a default hashicorp provider -func (pt Provider) IsDefault() bool { - if pt.IsZero() { - panic("called IsDefault() on zero-value addrs.Provider") - } - - return pt.Hostname == DefaultRegistryHost && pt.Namespace == "hashicorp" -} - // Equals returns true if the receiver and other provider have the same attributes. func (pt Provider) Equals(other Provider) bool { return pt == other } -// ParseRawProviderSourceString parses the source attribute and returns a provider. +// ParseProviderSource parses the source attribute and returns a provider. // This is intended primarily to parse the FQN-like strings returned by // terraform-config-inspect. // @@ -230,7 +185,7 @@ func (pt Provider) Equals(other Provider) bool { // // "name"-only format is parsed as -/name (i.e. legacy namespace) // requiring further identification of the namespace via Registry API -func ParseRawProviderSourceString(str string) (Provider, error) { +func ParseProviderSource(str string) (Provider, error) { var ret Provider parts, err := parseSourceStringParts(str) if err != nil { @@ -239,10 +194,14 @@ func ParseRawProviderSourceString(str string) (Provider, error) { name := parts[len(parts)-1] ret.Type = name - ret.Hostname = DefaultRegistryHost + ret.Hostname = DefaultProviderRegistryHost if len(parts) == 1 { - return NewLegacyProvider(name), nil + return Provider{ + Hostname: DefaultProviderRegistryHost, + Namespace: UnknownProviderNamespace, + Type: name, + }, nil } if len(parts) >= 2 { @@ -278,13 +237,13 @@ func ParseRawProviderSourceString(str string) (Provider, error) { ret.Hostname = hn } - if ret.Namespace == LegacyProviderNamespace && ret.Hostname != DefaultRegistryHost { + if ret.Namespace == LegacyProviderNamespace && ret.Hostname != DefaultProviderRegistryHost { // Legacy provider addresses must always be on the default registry // host, because the default registry host decides what actual FQN // each one maps to. return Provider{}, &ParserError{ Summary: "Invalid provider namespace", - Detail: "The legacy provider namespace \"-\" can be used only with hostname " + DefaultRegistryHost.ForDisplay() + ".", + Detail: "The legacy provider namespace \"-\" can be used only with hostname " + DefaultProviderRegistryHost.ForDisplay() + ".", } } @@ -332,28 +291,52 @@ func ParseRawProviderSourceString(str string) (Provider, error) { return ret, nil } -// ParseAndInferProviderSourceString parses the source attribute and returns a provider. -// This is intended primarily to parse the FQN-like strings returned by -// terraform-config-inspect. -// -// The following are valid source string formats: -// name -// namespace/name -// hostname/namespace/name -// -// "name" format is assumed to be hashicorp/name -func ParseAndInferProviderSourceString(str string) (Provider, error) { - var ret Provider - parts, err := parseSourceStringParts(str) +// MustParseProviderSource is a wrapper around ParseProviderSource that panics if +// it returns an error. +func MustParseProviderSource(raw string) (Provider) { + p, err := ParseProviderSource(raw) if err != nil { - return ret, err + panic(err) } + return p +} - if len(parts) == 1 { - return NewDefaultProvider(parts[0]), nil +// ValidateProviderAddress returns error if the given address is not FQN, +// that is if it is missing any of the three components from +// hostname/namespace/name. +func ValidateProviderAddress(raw string) error { + parts, err := parseSourceStringParts(raw) + if err != nil { + return err + } + + if len(parts) != 3 { + return &ParserError{ + Summary: "Invalid provider address format", + Detail: `Expected FQN in the format "hostname/namespace/name"`, + } + } + + p, err := ParseProviderSource(raw) + if err != nil { + return err + } + + if !p.HasKnownNamespace() { + return &ParserError{ + Summary: "Unknown provider namespace", + Detail: `Expected FQN in the format "hostname/namespace/name"`, + } + } + + if !p.IsLegacy() { + return &ParserError{ + Summary: "Invalid legacy provider namespace", + Detail: `Expected FQN in the format "hostname/namespace/name"`, + } } - return ParseRawProviderSourceString(str) + return nil } func parseSourceStringParts(str string) ([]string, error) { @@ -390,16 +373,6 @@ func parseSourceStringParts(str string) ([]string, error) { return parts, nil } -// MustParseRawProviderSourceString is a wrapper around ParseRawProviderSourceString that panics if -// it returns an error. -func MustParseRawProviderSourceString(str string) Provider { - result, err := ParseRawProviderSourceString(str) - if err != nil { - panic(err) - } - return result -} - // ParseProviderPart processes an addrs.Provider namespace or type string // provided by an end-user, producing a normalized version if possible or // an error if the string contains invalid characters. @@ -468,15 +441,3 @@ func MustParseProviderPart(given string) string { } return result } - -// IsProviderPartNormalized compares a given string to the result of ParseProviderPart(string) -func IsProviderPartNormalized(str string) (bool, error) { - normalized, err := ParseProviderPart(str) - if err != nil { - return false, err - } - if str == normalized { - return true, nil - } - return false, nil -} diff --git a/vendor/github.com/mattn/go-colorable/README.md b/vendor/github.com/mattn/go-colorable/README.md index e055952b667c..ca0483711c93 100644 --- a/vendor/github.com/mattn/go-colorable/README.md +++ b/vendor/github.com/mattn/go-colorable/README.md @@ -1,6 +1,6 @@ # go-colorable -[![Build Status](https://travis-ci.org/mattn/go-colorable.svg?branch=master)](https://travis-ci.org/mattn/go-colorable) +[![Build Status](https://github.com/mattn/go-colorable/workflows/test/badge.svg)](https://github.com/mattn/go-colorable/actions?query=workflow%3Atest) [![Codecov](https://codecov.io/gh/mattn/go-colorable/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-colorable) [![GoDoc](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) [![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable) diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go index 1f7806fe16bb..416d1bbbf836 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go +++ b/vendor/github.com/mattn/go-colorable/colorable_appengine.go @@ -1,3 +1,4 @@ +//go:build appengine // +build appengine package colorable diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go index 08cbd1e0fa25..766d94603ac1 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_others.go +++ b/vendor/github.com/mattn/go-colorable/colorable_others.go @@ -1,5 +1,5 @@ -// +build !windows -// +build !appengine +//go:build !windows && !appengine +// +build !windows,!appengine package colorable diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go index 41215d7fc4ff..1846ad5ab41c 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -1,5 +1,5 @@ -// +build windows -// +build !appengine +//go:build windows && !appengine +// +build windows,!appengine package colorable @@ -452,18 +452,22 @@ func (w *Writer) Write(data []byte) (n int, err error) { } else { er = bytes.NewReader(data) } - var bw [1]byte + var plaintext bytes.Buffer loop: for { c1, err := er.ReadByte() if err != nil { + plaintext.WriteTo(w.out) break loop } if c1 != 0x1b { - bw[0] = c1 - w.out.Write(bw[:]) + plaintext.WriteByte(c1) continue } + _, err = plaintext.WriteTo(w.out) + if err != nil { + break loop + } c2, err := er.ReadByte() if err != nil { break loop diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go index 95f2c6be2576..05d6f74bf6bb 100644 --- a/vendor/github.com/mattn/go-colorable/noncolorable.go +++ b/vendor/github.com/mattn/go-colorable/noncolorable.go @@ -18,18 +18,22 @@ func NewNonColorable(w io.Writer) io.Writer { // Write writes data on console func (w *NonColorable) Write(data []byte) (n int, err error) { er := bytes.NewReader(data) - var bw [1]byte + var plaintext bytes.Buffer loop: for { c1, err := er.ReadByte() if err != nil { + plaintext.WriteTo(w.out) break loop } if c1 != 0x1b { - bw[0] = c1 - w.out.Write(bw[:]) + plaintext.WriteByte(c1) continue } + _, err = plaintext.WriteTo(w.out) + if err != nil { + break loop + } c2, err := er.ReadByte() if err != nil { break loop @@ -38,7 +42,6 @@ loop: continue } - var buf bytes.Buffer for { c, err := er.ReadByte() if err != nil { @@ -47,7 +50,6 @@ loop: if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { break } - buf.Write([]byte(string(c))) } } diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go index 711f288085ac..39bbcf00f0c6 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ b/vendor/github.com/mattn/go-isatty/isatty_bsd.go @@ -1,3 +1,4 @@ +//go:build (darwin || freebsd || openbsd || netbsd || dragonfly) && !appengine // +build darwin freebsd openbsd netbsd dragonfly // +build !appengine diff --git a/vendor/github.com/mattn/go-isatty/isatty_others.go b/vendor/github.com/mattn/go-isatty/isatty_others.go index 3eba4cb34a24..31503226f6c8 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_others.go +++ b/vendor/github.com/mattn/go-isatty/isatty_others.go @@ -1,3 +1,4 @@ +//go:build appengine || js || nacl || wasm // +build appengine js nacl wasm package isatty diff --git a/vendor/github.com/mattn/go-isatty/isatty_plan9.go b/vendor/github.com/mattn/go-isatty/isatty_plan9.go index c5b6e0c084ad..bae7f9bb3dc5 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_plan9.go +++ b/vendor/github.com/mattn/go-isatty/isatty_plan9.go @@ -1,3 +1,4 @@ +//go:build plan9 // +build plan9 package isatty diff --git a/vendor/github.com/mattn/go-isatty/isatty_solaris.go b/vendor/github.com/mattn/go-isatty/isatty_solaris.go index 301067078341..0c3acf2dc288 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_solaris.go +++ b/vendor/github.com/mattn/go-isatty/isatty_solaris.go @@ -1,5 +1,5 @@ -// +build solaris -// +build !appengine +//go:build solaris && !appengine +// +build solaris,!appengine package isatty diff --git a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go index 4e7b850ecfb3..67787657fb2b 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go +++ b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go @@ -1,3 +1,4 @@ +//go:build (linux || aix || zos) && !appengine // +build linux aix zos // +build !appengine diff --git a/vendor/github.com/mattn/go-isatty/isatty_windows.go b/vendor/github.com/mattn/go-isatty/isatty_windows.go index 1fa869154059..8e3c99171bff 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_windows.go +++ b/vendor/github.com/mattn/go-isatty/isatty_windows.go @@ -1,5 +1,5 @@ -// +build windows -// +build !appengine +//go:build windows && !appengine +// +build windows,!appengine package isatty @@ -76,7 +76,7 @@ func isCygwinPipeName(name string) bool { } // getFileNameByHandle use the undocomented ntdll NtQueryObject to get file full name from file handler -// since GetFileInformationByHandleEx is not avilable under windows Vista and still some old fashion +// since GetFileInformationByHandleEx is not available under windows Vista and still some old fashion // guys are using Windows XP, this is a workaround for those guys, it will also work on system from // Windows vista to 10 // see https://stackoverflow.com/a/18792477 for details diff --git a/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md b/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md index 1955f2878c81..c758234904ec 100644 --- a/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md +++ b/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md @@ -1,6 +1,29 @@ -## unreleased +## 1.5.0 -* Fix regression where `*time.Time` value would be set to empty and not be sent +* New option `IgnoreUntaggedFields` to ignore decoding to any fields + without `mapstructure` (or the configured tag name) set [GH-277] +* New option `ErrorUnset` which makes it an error if any fields + in a target struct are not set by the decoding process. [GH-225] +* New function `OrComposeDecodeHookFunc` to help compose decode hooks. [GH-240] +* Decoding to slice from array no longer crashes [GH-265] +* Decode nested struct pointers to map [GH-271] +* Fix issue where `,squash` was ignored if `Squash` option was set. [GH-280] +* Fix issue where fields with `,omitempty` would sometimes decode + into a map with an empty string key [GH-281] + +## 1.4.3 + +* Fix cases where `json.Number` didn't decode properly [GH-261] + +## 1.4.2 + +* Custom name matchers to support any sort of casing, formatting, etc. for + field names. [GH-250] +* Fix possible panic in ComposeDecodeHookFunc [GH-251] + +## 1.4.1 + +* Fix regression where `*time.Time` value would be set to empty and not be sent to decode hooks properly [GH-232] ## 1.4.0 diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go index 92e6f76fff43..3a754ca72484 100644 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go @@ -62,7 +62,8 @@ func DecodeHookExec( func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { return func(f reflect.Value, t reflect.Value) (interface{}, error) { var err error - var data interface{} + data := f.Interface() + newFrom := f for _, f1 := range fs { data, err = DecodeHookExec(f1, newFrom, t) @@ -76,6 +77,28 @@ func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { } } +// OrComposeDecodeHookFunc executes all input hook functions until one of them returns no error. In that case its value is returned. +// If all hooks return an error, OrComposeDecodeHookFunc returns an error concatenating all error messages. +func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc { + return func(a, b reflect.Value) (interface{}, error) { + var allErrs string + var out interface{} + var err error + + for _, f := range ff { + out, err = DecodeHookExec(f, a, b) + if err != nil { + allErrs += err.Error() + "\n" + continue + } + + return out, nil + } + + return nil, errors.New(allErrs) + } +} + // StringToSliceHookFunc returns a DecodeHookFunc that converts // string to []string by splitting on the given sep. func StringToSliceHookFunc(sep string) DecodeHookFunc { diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index 3643901f55f1..1efb22ac3610 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -122,7 +122,7 @@ // field value is zero and a numeric type, the field is empty, and it won't // be encoded into the destination type. // -// type Source { +// type Source struct { // Age int `mapstructure:",omitempty"` // } // @@ -192,7 +192,7 @@ type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface // source and target types. type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) -// DecodeHookFuncRaw is a DecodeHookFunc which has complete access to both the source and target +// DecodeHookFuncValue is a DecodeHookFunc which has complete access to both the source and target // values. type DecodeHookFuncValue func(from reflect.Value, to reflect.Value) (interface{}, error) @@ -215,6 +215,12 @@ type DecoderConfig struct { // (extra keys). ErrorUnused bool + // If ErrorUnset is true, then it is an error for there to exist + // fields in the result that were not set in the decoding process + // (extra fields). This only applies to decoding to a struct. This + // will affect all nested structs as well. + ErrorUnset bool + // ZeroFields, if set to true, will zero fields before writing them. // For example, a map will be emptied before decoded values are put in // it. If this is false, a map will be merged. @@ -258,6 +264,15 @@ type DecoderConfig struct { // The tag name that mapstructure reads for field names. This // defaults to "mapstructure" TagName string + + // IgnoreUntaggedFields ignores all struct fields without explicit + // TagName, comparable to `mapstructure:"-"` as default behaviour. + IgnoreUntaggedFields bool + + // MatchName is the function used to match the map key to the struct + // field name or tag. Defaults to `strings.EqualFold`. This can be used + // to implement case-sensitive tag values, support snake casing, etc. + MatchName func(mapKey, fieldName string) bool } // A Decoder takes a raw interface value and turns it into structured @@ -279,6 +294,11 @@ type Metadata struct { // Unused is a slice of keys that were found in the raw value but // weren't decoded since there was no matching field in the result interface Unused []string + + // Unset is a slice of field names that were found in the result interface + // but weren't set in the decoding process since there was no matching value + // in the input + Unset []string } // Decode takes an input structure and uses reflection to translate it to @@ -370,12 +390,20 @@ func NewDecoder(config *DecoderConfig) (*Decoder, error) { if config.Metadata.Unused == nil { config.Metadata.Unused = make([]string, 0) } + + if config.Metadata.Unset == nil { + config.Metadata.Unset = make([]string, 0) + } } if config.TagName == "" { config.TagName = "mapstructure" } + if config.MatchName == nil { + config.MatchName = strings.EqualFold + } + result := &Decoder{ config: config, } @@ -675,16 +703,12 @@ func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) e } case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": jn := data.(json.Number) - i, err := jn.Int64() + i, err := strconv.ParseUint(string(jn), 0, 64) if err != nil { return fmt.Errorf( "error decoding json.Number into %s: %s", name, err) } - if i < 0 && !d.config.WeaklyTypedInput { - return fmt.Errorf("cannot parse '%s', %d overflows uint", - name, i) - } - val.SetUint(uint64(i)) + val.SetUint(i) default: return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", @@ -901,9 +925,15 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re tagValue := f.Tag.Get(d.config.TagName) keyName := f.Name + if tagValue == "" && d.config.IgnoreUntaggedFields { + continue + } + // If Squash is set in the config, we squash the field down. squash := d.config.Squash && v.Kind() == reflect.Struct && f.Anonymous + v = dereferencePtrToStructIfNeeded(v, d.config.TagName) + // Determine the name of the key in the map if index := strings.Index(tagValue, ","); index != -1 { if tagValue[:index] == "-" { @@ -915,7 +945,7 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re } // If "squash" is specified in the tag, we squash the field down. - squash = !squash && strings.Index(tagValue[index+1:], "squash") != -1 + squash = squash || strings.Index(tagValue[index+1:], "squash") != -1 if squash { // When squashing, the embedded type can be a pointer to a struct. if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct { @@ -927,7 +957,9 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re return fmt.Errorf("cannot squash non-struct type '%s'", v.Type()) } } - keyName = tagValue[:index] + if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" { + keyName = keyNameTagValue + } } else if len(tagValue) > 0 { if tagValue == "-" { continue @@ -1083,7 +1115,7 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) } // If the input value is nil, then don't allocate since empty != nil - if dataVal.IsNil() { + if dataValKind != reflect.Array && dataVal.IsNil() { return nil } @@ -1245,6 +1277,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e dataValKeysUnused[dataValKey.Interface()] = struct{}{} } + targetValKeysUnused := make(map[interface{}]struct{}) errors := make([]string, 0) // This slice will keep track of all the structs we'll be decoding. @@ -1340,7 +1373,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e continue } - if strings.EqualFold(mK, fieldName) { + if d.config.MatchName(mK, fieldName) { rawMapKey = dataValKey rawMapVal = dataVal.MapIndex(dataValKey) break @@ -1349,7 +1382,8 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e if !rawMapVal.IsValid() { // There was no matching key in the map for the value in - // the struct. Just ignore. + // the struct. Remember it for potential errors and metadata. + targetValKeysUnused[fieldName] = struct{}{} continue } } @@ -1409,6 +1443,17 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e errors = appendErrors(errors, err) } + if d.config.ErrorUnset && len(targetValKeysUnused) > 0 { + keys := make([]string, 0, len(targetValKeysUnused)) + for rawKey := range targetValKeysUnused { + keys = append(keys, rawKey.(string)) + } + sort.Strings(keys) + + err := fmt.Errorf("'%s' has unset fields: %s", name, strings.Join(keys, ", ")) + errors = appendErrors(errors, err) + } + if len(errors) > 0 { return &Error{errors} } @@ -1423,6 +1468,14 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e d.config.Metadata.Unused = append(d.config.Metadata.Unused, key) } + for rawKey := range targetValKeysUnused { + key := rawKey.(string) + if name != "" { + key = name + "." + key + } + + d.config.Metadata.Unset = append(d.config.Metadata.Unset, key) + } } return nil @@ -1460,3 +1513,28 @@ func getKind(val reflect.Value) reflect.Kind { return kind } } + +func isStructTypeConvertibleToMap(typ reflect.Type, checkMapstructureTags bool, tagName string) bool { + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if f.PkgPath == "" && !checkMapstructureTags { // check for unexported fields + return true + } + if checkMapstructureTags && f.Tag.Get(tagName) != "" { // check for mapstructure tags inside + return true + } + } + return false +} + +func dereferencePtrToStructIfNeeded(v reflect.Value, tagName string) reflect.Value { + if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { + return v + } + deref := v.Elem() + derefT := deref.Type() + if isStructTypeConvertibleToMap(derefT, true, tagName) { + return deref + } + return v +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/.golangci.yml b/vendor/github.com/vmihailenco/msgpack/v4/.golangci.yml new file mode 100644 index 000000000000..98d6cb7797f2 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/.golangci.yml @@ -0,0 +1,12 @@ +run: + concurrency: 8 + deadline: 5m + tests: false +linters: + enable-all: true + disable: + - gochecknoglobals + - gocognit + - godox + - wsl + - funlen diff --git a/vendor/github.com/vmihailenco/msgpack/v4/.travis.yml b/vendor/github.com/vmihailenco/msgpack/v4/.travis.yml new file mode 100644 index 000000000000..b35bf5484e7c --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/.travis.yml @@ -0,0 +1,21 @@ +sudo: false +language: go + +go: + - 1.11.x + - 1.12.x + - 1.13.x + - 1.14.x + - tip + +matrix: + allow_failures: + - go: tip + +env: + - GO111MODULE=on + +go_import_path: github.com/vmihailenco/msgpack + +before_install: + - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.21.0 diff --git a/vendor/github.com/vmihailenco/msgpack/v4/CHANGELOG.md b/vendor/github.com/vmihailenco/msgpack/v4/CHANGELOG.md new file mode 100644 index 000000000000..fac97090e456 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/CHANGELOG.md @@ -0,0 +1,24 @@ +## v4 + +- Encode, Decode, Marshal, and Unmarshal are changed to accept single argument. EncodeMulti and DecodeMulti are added as replacement. +- Added EncodeInt8/16/32/64 and EncodeUint8/16/32/64. +- Encoder changed to preserve type of numbers instead of chosing most compact encoding. The old behavior can be achieved with Encoder.UseCompactEncoding. + +## v3.3 + +- `msgpack:",inline"` tag is restored to force inlining structs. + +## v3.2 + +- Decoding extension types returns pointer to the value instead of the value. Fixes #153 + +## v3 + +- gopkg.in is not supported any more. Update import path to github.com/vmihailenco/msgpack. +- Msgpack maps are decoded into map[string]interface{} by default. +- EncodeSliceLen is removed in favor of EncodeArrayLen. DecodeSliceLen is removed in favor of DecodeArrayLen. +- Embedded structs are automatically inlined where possible. +- Time is encoded using extension as described in https://github.com/msgpack/msgpack/pull/209. Old format is supported as well. +- EncodeInt8/16/32/64 is replaced with EncodeInt. EncodeUint8/16/32/64 is replaced with EncodeUint. There should be no performance differences. +- DecodeInterface can now return int8/16/32 and uint8/16/32. +- PeekCode returns codes.Code instead of byte. diff --git a/vendor/github.com/vmihailenco/msgpack/v4/LICENSE b/vendor/github.com/vmihailenco/msgpack/v4/LICENSE new file mode 100644 index 000000000000..b749d070797c --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2013 The github.com/vmihailenco/msgpack Authors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/vmihailenco/msgpack/v4/Makefile b/vendor/github.com/vmihailenco/msgpack/v4/Makefile new file mode 100644 index 000000000000..57914e333a85 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/Makefile @@ -0,0 +1,6 @@ +all: + go test ./... + go test ./... -short -race + go test ./... -run=NONE -bench=. -benchmem + env GOOS=linux GOARCH=386 go test ./... + golangci-lint run diff --git a/vendor/github.com/vmihailenco/msgpack/v4/README.md b/vendor/github.com/vmihailenco/msgpack/v4/README.md new file mode 100644 index 000000000000..a5b1004e08c1 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/README.md @@ -0,0 +1,72 @@ +# MessagePack encoding for Golang + +[![Build Status](https://travis-ci.org/vmihailenco/msgpack.svg?branch=v2)](https://travis-ci.org/vmihailenco/msgpack) +[![GoDoc](https://godoc.org/github.com/vmihailenco/msgpack?status.svg)](https://godoc.org/github.com/vmihailenco/msgpack) + +Supports: +- Primitives, arrays, maps, structs, time.Time and interface{}. +- Appengine *datastore.Key and datastore.Cursor. +- [CustomEncoder](https://godoc.org/github.com/vmihailenco/msgpack#example-CustomEncoder)/CustomDecoder interfaces for custom encoding. +- [Extensions](https://godoc.org/github.com/vmihailenco/msgpack#example-RegisterExt) to encode type information. +- Renaming fields via `msgpack:"my_field_name"` and alias via `msgpack:"alias:another_name"`. +- Omitting individual empty fields via `msgpack:",omitempty"` tag or all [empty fields in a struct](https://godoc.org/github.com/vmihailenco/msgpack#example-Marshal--OmitEmpty). +- [Map keys sorting](https://godoc.org/github.com/vmihailenco/msgpack#Encoder.SortMapKeys). +- Encoding/decoding all [structs as arrays](https://godoc.org/github.com/vmihailenco/msgpack#Encoder.UseArrayForStructs) or [individual structs](https://godoc.org/github.com/vmihailenco/msgpack#example-Marshal--AsArray). +- [Encoder.UseJSONTag](https://godoc.org/github.com/vmihailenco/msgpack#Encoder.UseJSONTag) with [Decoder.UseJSONTag](https://godoc.org/github.com/vmihailenco/msgpack#Decoder.UseJSONTag) can turn msgpack into drop-in replacement for JSON. +- Simple but very fast and efficient [queries](https://godoc.org/github.com/vmihailenco/msgpack#example-Decoder-Query). + +API docs: https://godoc.org/github.com/vmihailenco/msgpack. +Examples: https://godoc.org/github.com/vmihailenco/msgpack#pkg-examples. + +## Installation + +This project uses [Go Modules](https://github.com/golang/go/wiki/Modules) and semantic import versioning since v4: + +``` shell +go mod init github.com/my/repo +go get github.com/vmihailenco/msgpack/v4 +``` + +## Quickstart + +``` go +import "github.com/vmihailenco/msgpack/v4" + +func ExampleMarshal() { + type Item struct { + Foo string + } + + b, err := msgpack.Marshal(&Item{Foo: "bar"}) + if err != nil { + panic(err) + } + + var item Item + err = msgpack.Unmarshal(b, &item) + if err != nil { + panic(err) + } + fmt.Println(item.Foo) + // Output: bar +} +``` + +## Benchmark + +``` +BenchmarkStructVmihailencoMsgpack-4 200000 12814 ns/op 2128 B/op 26 allocs/op +BenchmarkStructUgorjiGoMsgpack-4 100000 17678 ns/op 3616 B/op 70 allocs/op +BenchmarkStructUgorjiGoCodec-4 100000 19053 ns/op 7346 B/op 23 allocs/op +BenchmarkStructJSON-4 20000 69438 ns/op 7864 B/op 26 allocs/op +BenchmarkStructGOB-4 10000 104331 ns/op 14664 B/op 278 allocs/op +``` + +## Howto + +Please go through [examples](https://godoc.org/github.com/vmihailenco/msgpack#pkg-examples) to get an idea how to use this package. + +## See also + +- [Golang PostgreSQL ORM](https://github.com/go-pg/pg) +- [Golang message task queue](https://github.com/vmihailenco/taskq) diff --git a/vendor/github.com/vmihailenco/msgpack/v4/appengine.go b/vendor/github.com/vmihailenco/msgpack/v4/appengine.go new file mode 100644 index 000000000000..e8e91e53f35d --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/appengine.go @@ -0,0 +1,64 @@ +// +build appengine + +package msgpack + +import ( + "reflect" + + ds "google.golang.org/appengine/datastore" +) + +func init() { + Register((*ds.Key)(nil), encodeDatastoreKeyValue, decodeDatastoreKeyValue) + Register((*ds.Cursor)(nil), encodeDatastoreCursorValue, decodeDatastoreCursorValue) +} + +func EncodeDatastoreKey(e *Encoder, key *ds.Key) error { + if key == nil { + return e.EncodeNil() + } + return e.EncodeString(key.Encode()) +} + +func encodeDatastoreKeyValue(e *Encoder, v reflect.Value) error { + key := v.Interface().(*ds.Key) + return EncodeDatastoreKey(e, key) +} + +func DecodeDatastoreKey(d *Decoder) (*ds.Key, error) { + v, err := d.DecodeString() + if err != nil { + return nil, err + } + if v == "" { + return nil, nil + } + return ds.DecodeKey(v) +} + +func decodeDatastoreKeyValue(d *Decoder, v reflect.Value) error { + key, err := DecodeDatastoreKey(d) + if err != nil { + return err + } + v.Set(reflect.ValueOf(key)) + return nil +} + +func encodeDatastoreCursorValue(e *Encoder, v reflect.Value) error { + cursor := v.Interface().(ds.Cursor) + return e.Encode(cursor.String()) +} + +func decodeDatastoreCursorValue(d *Decoder, v reflect.Value) error { + s, err := d.DecodeString() + if err != nil { + return err + } + cursor, err := ds.DecodeCursor(s) + if err != nil { + return err + } + v.Set(reflect.ValueOf(cursor)) + return nil +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/codes/codes.go b/vendor/github.com/vmihailenco/msgpack/v4/codes/codes.go new file mode 100644 index 000000000000..28e0a5a88b4d --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/codes/codes.go @@ -0,0 +1,90 @@ +package codes + +type Code byte + +var ( + PosFixedNumHigh Code = 0x7f + NegFixedNumLow Code = 0xe0 + + Nil Code = 0xc0 + + False Code = 0xc2 + True Code = 0xc3 + + Float Code = 0xca + Double Code = 0xcb + + Uint8 Code = 0xcc + Uint16 Code = 0xcd + Uint32 Code = 0xce + Uint64 Code = 0xcf + + Int8 Code = 0xd0 + Int16 Code = 0xd1 + Int32 Code = 0xd2 + Int64 Code = 0xd3 + + FixedStrLow Code = 0xa0 + FixedStrHigh Code = 0xbf + FixedStrMask Code = 0x1f + Str8 Code = 0xd9 + Str16 Code = 0xda + Str32 Code = 0xdb + + Bin8 Code = 0xc4 + Bin16 Code = 0xc5 + Bin32 Code = 0xc6 + + FixedArrayLow Code = 0x90 + FixedArrayHigh Code = 0x9f + FixedArrayMask Code = 0xf + Array16 Code = 0xdc + Array32 Code = 0xdd + + FixedMapLow Code = 0x80 + FixedMapHigh Code = 0x8f + FixedMapMask Code = 0xf + Map16 Code = 0xde + Map32 Code = 0xdf + + FixExt1 Code = 0xd4 + FixExt2 Code = 0xd5 + FixExt4 Code = 0xd6 + FixExt8 Code = 0xd7 + FixExt16 Code = 0xd8 + Ext8 Code = 0xc7 + Ext16 Code = 0xc8 + Ext32 Code = 0xc9 +) + +func IsFixedNum(c Code) bool { + return c <= PosFixedNumHigh || c >= NegFixedNumLow +} + +func IsFixedMap(c Code) bool { + return c >= FixedMapLow && c <= FixedMapHigh +} + +func IsFixedArray(c Code) bool { + return c >= FixedArrayLow && c <= FixedArrayHigh +} + +func IsFixedString(c Code) bool { + return c >= FixedStrLow && c <= FixedStrHigh +} + +func IsString(c Code) bool { + return IsFixedString(c) || c == Str8 || c == Str16 || c == Str32 +} + +func IsBin(c Code) bool { + return c == Bin8 || c == Bin16 || c == Bin32 +} + +func IsFixedExt(c Code) bool { + return c >= FixExt1 && c <= FixExt16 +} + +func IsExt(c Code) bool { + return IsFixedExt(c) || c == Ext8 || c == Ext16 || c == Ext32 +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/decode.go b/vendor/github.com/vmihailenco/msgpack/v4/decode.go new file mode 100644 index 000000000000..1711675e9a1e --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/decode.go @@ -0,0 +1,617 @@ +package msgpack + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "reflect" + "sync" + "time" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +const ( + looseIfaceFlag uint32 = 1 << iota + decodeUsingJSONFlag + disallowUnknownFieldsFlag +) + +const ( + bytesAllocLimit = 1e6 // 1mb + sliceAllocLimit = 1e4 + maxMapSize = 1e6 +) + +type bufReader interface { + io.Reader + io.ByteScanner +} + +//------------------------------------------------------------------------------ + +var decPool = sync.Pool{ + New: func() interface{} { + return NewDecoder(nil) + }, +} + +// Unmarshal decodes the MessagePack-encoded data and stores the result +// in the value pointed to by v. +func Unmarshal(data []byte, v interface{}) error { + dec := decPool.Get().(*Decoder) + + if r, ok := dec.r.(*bytes.Reader); ok { + r.Reset(data) + } else { + dec.Reset(bytes.NewReader(data)) + } + err := dec.Decode(v) + + decPool.Put(dec) + + return err +} + +// A Decoder reads and decodes MessagePack values from an input stream. +type Decoder struct { + r io.Reader + s io.ByteScanner + buf []byte + + extLen int + rec []byte // accumulates read data if not nil + + intern []string + flags uint32 + decodeMapFunc func(*Decoder) (interface{}, error) +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may read data from r +// beyond the MessagePack values requested. Buffering can be disabled +// by passing a reader that implements io.ByteScanner interface. +func NewDecoder(r io.Reader) *Decoder { + d := new(Decoder) + d.Reset(r) + return d +} + +// Reset discards any buffered data, resets all state, and switches the buffered +// reader to read from r. +func (d *Decoder) Reset(r io.Reader) { + if br, ok := r.(bufReader); ok { + d.r = br + d.s = br + } else if br, ok := d.r.(*bufio.Reader); ok { + br.Reset(r) + } else { + br := bufio.NewReader(r) + d.r = br + d.s = br + } + + if d.intern != nil { + d.intern = d.intern[:0] + } + + //TODO: + //d.useLoose = false + //d.useJSONTag = false + //d.disallowUnknownFields = false + //d.decodeMapFunc = nil +} + +func (d *Decoder) SetDecodeMapFunc(fn func(*Decoder) (interface{}, error)) { + d.decodeMapFunc = fn +} + +// UseDecodeInterfaceLoose causes decoder to use DecodeInterfaceLoose +// to decode msgpack value into Go interface{}. +func (d *Decoder) UseDecodeInterfaceLoose(on bool) *Decoder { + if on { + d.flags |= looseIfaceFlag + } else { + d.flags &= ^looseIfaceFlag + } + return d +} + +// UseJSONTag causes the Decoder to use json struct tag as fallback option +// if there is no msgpack tag. +func (d *Decoder) UseJSONTag(on bool) *Decoder { + if on { + d.flags |= decodeUsingJSONFlag + } else { + d.flags &= ^decodeUsingJSONFlag + } + return d +} + +// DisallowUnknownFields causes the Decoder to return an error when the destination +// is a struct and the input contains object keys which do not match any +// non-ignored, exported fields in the destination. +func (d *Decoder) DisallowUnknownFields() { + if true { + d.flags |= disallowUnknownFieldsFlag + } else { + d.flags &= ^disallowUnknownFieldsFlag + } +} + +// Buffered returns a reader of the data remaining in the Decoder's buffer. +// The reader is valid until the next call to Decode. +func (d *Decoder) Buffered() io.Reader { + return d.r +} + +//nolint:gocyclo +func (d *Decoder) Decode(v interface{}) error { + var err error + switch v := v.(type) { + case *string: + if v != nil { + *v, err = d.DecodeString() + return err + } + case *[]byte: + if v != nil { + return d.decodeBytesPtr(v) + } + case *int: + if v != nil { + *v, err = d.DecodeInt() + return err + } + case *int8: + if v != nil { + *v, err = d.DecodeInt8() + return err + } + case *int16: + if v != nil { + *v, err = d.DecodeInt16() + return err + } + case *int32: + if v != nil { + *v, err = d.DecodeInt32() + return err + } + case *int64: + if v != nil { + *v, err = d.DecodeInt64() + return err + } + case *uint: + if v != nil { + *v, err = d.DecodeUint() + return err + } + case *uint8: + if v != nil { + *v, err = d.DecodeUint8() + return err + } + case *uint16: + if v != nil { + *v, err = d.DecodeUint16() + return err + } + case *uint32: + if v != nil { + *v, err = d.DecodeUint32() + return err + } + case *uint64: + if v != nil { + *v, err = d.DecodeUint64() + return err + } + case *bool: + if v != nil { + *v, err = d.DecodeBool() + return err + } + case *float32: + if v != nil { + *v, err = d.DecodeFloat32() + return err + } + case *float64: + if v != nil { + *v, err = d.DecodeFloat64() + return err + } + case *[]string: + return d.decodeStringSlicePtr(v) + case *map[string]string: + return d.decodeMapStringStringPtr(v) + case *map[string]interface{}: + return d.decodeMapStringInterfacePtr(v) + case *time.Duration: + if v != nil { + vv, err := d.DecodeInt64() + *v = time.Duration(vv) + return err + } + case *time.Time: + if v != nil { + *v, err = d.DecodeTime() + return err + } + } + + vv := reflect.ValueOf(v) + if !vv.IsValid() { + return errors.New("msgpack: Decode(nil)") + } + if vv.Kind() != reflect.Ptr { + return fmt.Errorf("msgpack: Decode(nonsettable %T)", v) + } + vv = vv.Elem() + if !vv.IsValid() { + return fmt.Errorf("msgpack: Decode(nonsettable %T)", v) + } + return d.DecodeValue(vv) +} + +func (d *Decoder) DecodeMulti(v ...interface{}) error { + for _, vv := range v { + if err := d.Decode(vv); err != nil { + return err + } + } + return nil +} + +func (d *Decoder) decodeInterfaceCond() (interface{}, error) { + if d.flags&looseIfaceFlag != 0 { + return d.DecodeInterfaceLoose() + } + return d.DecodeInterface() +} + +func (d *Decoder) DecodeValue(v reflect.Value) error { + decode := getDecoder(v.Type()) + return decode(d, v) +} + +func (d *Decoder) DecodeNil() error { + c, err := d.readCode() + if err != nil { + return err + } + if c != codes.Nil { + return fmt.Errorf("msgpack: invalid code=%x decoding nil", c) + } + return nil +} + +func (d *Decoder) decodeNilValue(v reflect.Value) error { + err := d.DecodeNil() + if v.IsNil() { + return err + } + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + v.Set(reflect.Zero(v.Type())) + return err +} + +func (d *Decoder) DecodeBool() (bool, error) { + c, err := d.readCode() + if err != nil { + return false, err + } + return d.bool(c) +} + +func (d *Decoder) bool(c codes.Code) (bool, error) { + if c == codes.False { + return false, nil + } + if c == codes.True { + return true, nil + } + return false, fmt.Errorf("msgpack: invalid code=%x decoding bool", c) +} + +func (d *Decoder) DecodeDuration() (time.Duration, error) { + n, err := d.DecodeInt64() + if err != nil { + return 0, err + } + return time.Duration(n), nil +} + +// DecodeInterface decodes value into interface. It returns following types: +// - nil, +// - bool, +// - int8, int16, int32, int64, +// - uint8, uint16, uint32, uint64, +// - float32 and float64, +// - string, +// - []byte, +// - slices of any of the above, +// - maps of any of the above. +// +// DecodeInterface should be used only when you don't know the type of value +// you are decoding. For example, if you are decoding number it is better to use +// DecodeInt64 for negative numbers and DecodeUint64 for positive numbers. +func (d *Decoder) DecodeInterface() (interface{}, error) { + c, err := d.readCode() + if err != nil { + return nil, err + } + + if codes.IsFixedNum(c) { + return int8(c), nil + } + if codes.IsFixedMap(c) { + err = d.s.UnreadByte() + if err != nil { + return nil, err + } + return d.DecodeMap() + } + if codes.IsFixedArray(c) { + return d.decodeSlice(c) + } + if codes.IsFixedString(c) { + return d.string(c) + } + + switch c { + case codes.Nil: + return nil, nil + case codes.False, codes.True: + return d.bool(c) + case codes.Float: + return d.float32(c) + case codes.Double: + return d.float64(c) + case codes.Uint8: + return d.uint8() + case codes.Uint16: + return d.uint16() + case codes.Uint32: + return d.uint32() + case codes.Uint64: + return d.uint64() + case codes.Int8: + return d.int8() + case codes.Int16: + return d.int16() + case codes.Int32: + return d.int32() + case codes.Int64: + return d.int64() + case codes.Bin8, codes.Bin16, codes.Bin32: + return d.bytes(c, nil) + case codes.Str8, codes.Str16, codes.Str32: + return d.string(c) + case codes.Array16, codes.Array32: + return d.decodeSlice(c) + case codes.Map16, codes.Map32: + err = d.s.UnreadByte() + if err != nil { + return nil, err + } + return d.DecodeMap() + case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16, + codes.Ext8, codes.Ext16, codes.Ext32: + return d.extInterface(c) + } + + return 0, fmt.Errorf("msgpack: unknown code %x decoding interface{}", c) +} + +// DecodeInterfaceLoose is like DecodeInterface except that: +// - int8, int16, and int32 are converted to int64, +// - uint8, uint16, and uint32 are converted to uint64, +// - float32 is converted to float64. +func (d *Decoder) DecodeInterfaceLoose() (interface{}, error) { + c, err := d.readCode() + if err != nil { + return nil, err + } + + if codes.IsFixedNum(c) { + return int64(int8(c)), nil + } + if codes.IsFixedMap(c) { + err = d.s.UnreadByte() + if err != nil { + return nil, err + } + return d.DecodeMap() + } + if codes.IsFixedArray(c) { + return d.decodeSlice(c) + } + if codes.IsFixedString(c) { + return d.string(c) + } + + switch c { + case codes.Nil: + return nil, nil + case codes.False, codes.True: + return d.bool(c) + case codes.Float, codes.Double: + return d.float64(c) + case codes.Uint8, codes.Uint16, codes.Uint32, codes.Uint64: + return d.uint(c) + case codes.Int8, codes.Int16, codes.Int32, codes.Int64: + return d.int(c) + case codes.Bin8, codes.Bin16, codes.Bin32: + return d.bytes(c, nil) + case codes.Str8, codes.Str16, codes.Str32: + return d.string(c) + case codes.Array16, codes.Array32: + return d.decodeSlice(c) + case codes.Map16, codes.Map32: + err = d.s.UnreadByte() + if err != nil { + return nil, err + } + return d.DecodeMap() + case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16, + codes.Ext8, codes.Ext16, codes.Ext32: + return d.extInterface(c) + } + + return 0, fmt.Errorf("msgpack: unknown code %x decoding interface{}", c) +} + +// Skip skips next value. +func (d *Decoder) Skip() error { + c, err := d.readCode() + if err != nil { + return err + } + + if codes.IsFixedNum(c) { + return nil + } + if codes.IsFixedMap(c) { + return d.skipMap(c) + } + if codes.IsFixedArray(c) { + return d.skipSlice(c) + } + if codes.IsFixedString(c) { + return d.skipBytes(c) + } + + switch c { + case codes.Nil, codes.False, codes.True: + return nil + case codes.Uint8, codes.Int8: + return d.skipN(1) + case codes.Uint16, codes.Int16: + return d.skipN(2) + case codes.Uint32, codes.Int32, codes.Float: + return d.skipN(4) + case codes.Uint64, codes.Int64, codes.Double: + return d.skipN(8) + case codes.Bin8, codes.Bin16, codes.Bin32: + return d.skipBytes(c) + case codes.Str8, codes.Str16, codes.Str32: + return d.skipBytes(c) + case codes.Array16, codes.Array32: + return d.skipSlice(c) + case codes.Map16, codes.Map32: + return d.skipMap(c) + case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16, + codes.Ext8, codes.Ext16, codes.Ext32: + return d.skipExt(c) + } + + return fmt.Errorf("msgpack: unknown code %x", c) +} + +// PeekCode returns the next MessagePack code without advancing the reader. +// Subpackage msgpack/codes contains list of available codes. +func (d *Decoder) PeekCode() (codes.Code, error) { + c, err := d.s.ReadByte() + if err != nil { + return 0, err + } + return codes.Code(c), d.s.UnreadByte() +} + +func (d *Decoder) hasNilCode() bool { + code, err := d.PeekCode() + return err == nil && code == codes.Nil +} + +func (d *Decoder) readCode() (codes.Code, error) { + d.extLen = 0 + c, err := d.s.ReadByte() + if err != nil { + return 0, err + } + if d.rec != nil { + d.rec = append(d.rec, c) + } + return codes.Code(c), nil +} + +func (d *Decoder) readFull(b []byte) error { + _, err := io.ReadFull(d.r, b) + if err != nil { + return err + } + if d.rec != nil { + //TODO: read directly into d.rec? + d.rec = append(d.rec, b...) + } + return nil +} + +func (d *Decoder) readN(n int) ([]byte, error) { + var err error + d.buf, err = readN(d.r, d.buf, n) + if err != nil { + return nil, err + } + if d.rec != nil { + //TODO: read directly into d.rec? + d.rec = append(d.rec, d.buf...) + } + return d.buf, nil +} + +func readN(r io.Reader, b []byte, n int) ([]byte, error) { + if b == nil { + if n == 0 { + return make([]byte, 0), nil + } + switch { + case n < 64: + b = make([]byte, 0, 64) + case n <= bytesAllocLimit: + b = make([]byte, 0, n) + default: + b = make([]byte, 0, bytesAllocLimit) + } + } + + if n <= cap(b) { + b = b[:n] + _, err := io.ReadFull(r, b) + return b, err + } + b = b[:cap(b)] + + var pos int + for { + alloc := min(n-len(b), bytesAllocLimit) + b = append(b, make([]byte, alloc)...) + + _, err := io.ReadFull(r, b[pos:]) + if err != nil { + return b, err + } + + if len(b) == n { + break + } + pos = len(b) + } + + return b, nil +} + +func min(a, b int) int { //nolint:unparam + if a <= b { + return a + } + return b +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/decode_map.go b/vendor/github.com/vmihailenco/msgpack/v4/decode_map.go new file mode 100644 index 000000000000..16c40fe77e18 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/decode_map.go @@ -0,0 +1,350 @@ +package msgpack + +import ( + "errors" + "fmt" + "reflect" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +var ( + mapStringStringPtrType = reflect.TypeOf((*map[string]string)(nil)) + mapStringStringType = mapStringStringPtrType.Elem() +) + +var ( + mapStringInterfacePtrType = reflect.TypeOf((*map[string]interface{})(nil)) + mapStringInterfaceType = mapStringInterfacePtrType.Elem() +) + +func decodeMapValue(d *Decoder, v reflect.Value) error { + size, err := d.DecodeMapLen() + if err != nil { + return err + } + + typ := v.Type() + if size == -1 { + v.Set(reflect.Zero(typ)) + return nil + } + + if v.IsNil() { + v.Set(reflect.MakeMap(typ)) + } + if size == 0 { + return nil + } + + return decodeMapValueSize(d, v, size) +} + +func decodeMapValueSize(d *Decoder, v reflect.Value, size int) error { + typ := v.Type() + keyType := typ.Key() + valueType := typ.Elem() + + for i := 0; i < size; i++ { + mk := reflect.New(keyType).Elem() + if err := d.DecodeValue(mk); err != nil { + return err + } + + mv := reflect.New(valueType).Elem() + if err := d.DecodeValue(mv); err != nil { + return err + } + + v.SetMapIndex(mk, mv) + } + + return nil +} + +// DecodeMapLen decodes map length. Length is -1 when map is nil. +func (d *Decoder) DecodeMapLen() (int, error) { + c, err := d.readCode() + if err != nil { + return 0, err + } + + if codes.IsExt(c) { + if err = d.skipExtHeader(c); err != nil { + return 0, err + } + + c, err = d.readCode() + if err != nil { + return 0, err + } + } + return d.mapLen(c) +} + +func (d *Decoder) mapLen(c codes.Code) (int, error) { + size, err := d._mapLen(c) + err = expandInvalidCodeMapLenError(c, err) + return size, err +} + +func (d *Decoder) _mapLen(c codes.Code) (int, error) { + if c == codes.Nil { + return -1, nil + } + if c >= codes.FixedMapLow && c <= codes.FixedMapHigh { + return int(c & codes.FixedMapMask), nil + } + if c == codes.Map16 { + size, err := d.uint16() + return int(size), err + } + if c == codes.Map32 { + size, err := d.uint32() + return int(size), err + } + return 0, errInvalidCode +} + +var errInvalidCode = errors.New("invalid code") + +func expandInvalidCodeMapLenError(c codes.Code, err error) error { + if err == errInvalidCode { + return fmt.Errorf("msgpack: invalid code=%x decoding map length", c) + } + return err +} + +func decodeMapStringStringValue(d *Decoder, v reflect.Value) error { + mptr := v.Addr().Convert(mapStringStringPtrType).Interface().(*map[string]string) + return d.decodeMapStringStringPtr(mptr) +} + +func (d *Decoder) decodeMapStringStringPtr(ptr *map[string]string) error { + size, err := d.DecodeMapLen() + if err != nil { + return err + } + if size == -1 { + *ptr = nil + return nil + } + + m := *ptr + if m == nil { + *ptr = make(map[string]string, min(size, maxMapSize)) + m = *ptr + } + + for i := 0; i < size; i++ { + mk, err := d.DecodeString() + if err != nil { + return err + } + mv, err := d.DecodeString() + if err != nil { + return err + } + m[mk] = mv + } + + return nil +} + +func decodeMapStringInterfaceValue(d *Decoder, v reflect.Value) error { + ptr := v.Addr().Convert(mapStringInterfacePtrType).Interface().(*map[string]interface{}) + return d.decodeMapStringInterfacePtr(ptr) +} + +func (d *Decoder) decodeMapStringInterfacePtr(ptr *map[string]interface{}) error { + n, err := d.DecodeMapLen() + if err != nil { + return err + } + if n == -1 { + *ptr = nil + return nil + } + + m := *ptr + if m == nil { + *ptr = make(map[string]interface{}, min(n, maxMapSize)) + m = *ptr + } + + for i := 0; i < n; i++ { + mk, err := d.DecodeString() + if err != nil { + return err + } + mv, err := d.decodeInterfaceCond() + if err != nil { + return err + } + m[mk] = mv + } + + return nil +} + +var errUnsupportedMapKey = errors.New("msgpack: unsupported map key") + +func (d *Decoder) DecodeMap() (interface{}, error) { + if d.decodeMapFunc != nil { + return d.decodeMapFunc(d) + } + + size, err := d.DecodeMapLen() + if err != nil { + return nil, err + } + if size == -1 { + return nil, nil + } + if size == 0 { + return make(map[string]interface{}), nil + } + + code, err := d.PeekCode() + if err != nil { + return nil, err + } + + if codes.IsString(code) || codes.IsBin(code) { + return d.decodeMapStringInterfaceSize(size) + } + + key, err := d.decodeInterfaceCond() + if err != nil { + return nil, err + } + + value, err := d.decodeInterfaceCond() + if err != nil { + return nil, err + } + + keyType := reflect.TypeOf(key) + valueType := reflect.TypeOf(value) + + if !keyType.Comparable() { + return nil, errUnsupportedMapKey + } + + mapType := reflect.MapOf(keyType, valueType) + mapValue := reflect.MakeMap(mapType) + + mapValue.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value)) + size-- + + err = decodeMapValueSize(d, mapValue, size) + if err != nil { + return nil, err + } + + return mapValue.Interface(), nil +} + +func (d *Decoder) decodeMapStringInterfaceSize(size int) (map[string]interface{}, error) { + m := make(map[string]interface{}, min(size, maxMapSize)) + for i := 0; i < size; i++ { + mk, err := d.DecodeString() + if err != nil { + return nil, err + } + mv, err := d.decodeInterfaceCond() + if err != nil { + return nil, err + } + m[mk] = mv + } + return m, nil +} + +func (d *Decoder) skipMap(c codes.Code) error { + n, err := d.mapLen(c) + if err != nil { + return err + } + for i := 0; i < n; i++ { + if err := d.Skip(); err != nil { + return err + } + if err := d.Skip(); err != nil { + return err + } + } + return nil +} + +func decodeStructValue(d *Decoder, v reflect.Value) error { + c, err := d.readCode() + if err != nil { + return err + } + + var isArray bool + + n, err := d._mapLen(c) + if err != nil { + var err2 error + n, err2 = d.arrayLen(c) + if err2 != nil { + return expandInvalidCodeMapLenError(c, err) + } + isArray = true + } + if n == -1 { + if err = mustSet(v); err != nil { + return err + } + v.Set(reflect.Zero(v.Type())) + return nil + } + + var fields *fields + if d.flags&decodeUsingJSONFlag != 0 { + fields = jsonStructs.Fields(v.Type()) + } else { + fields = structs.Fields(v.Type()) + } + + if isArray { + for i, f := range fields.List { + if i >= n { + break + } + if err := f.DecodeValue(d, v); err != nil { + return err + } + } + + // Skip extra values. + for i := len(fields.List); i < n; i++ { + if err := d.Skip(); err != nil { + return err + } + } + + return nil + } + + for i := 0; i < n; i++ { + name, err := d.DecodeString() + if err != nil { + return err + } + + if f := fields.Map[name]; f != nil { + if err := f.DecodeValue(d, v); err != nil { + return err + } + } else if d.flags&disallowUnknownFieldsFlag != 0 { + return fmt.Errorf("msgpack: unknown field %q", name) + } else if err := d.Skip(); err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/decode_number.go b/vendor/github.com/vmihailenco/msgpack/v4/decode_number.go new file mode 100644 index 000000000000..f6b9151f01e7 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/decode_number.go @@ -0,0 +1,307 @@ +package msgpack + +import ( + "fmt" + "math" + "reflect" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +func (d *Decoder) skipN(n int) error { + _, err := d.readN(n) + return err +} + +func (d *Decoder) uint8() (uint8, error) { + c, err := d.readCode() + if err != nil { + return 0, err + } + return uint8(c), nil +} + +func (d *Decoder) int8() (int8, error) { + n, err := d.uint8() + return int8(n), err +} + +func (d *Decoder) uint16() (uint16, error) { + b, err := d.readN(2) + if err != nil { + return 0, err + } + return (uint16(b[0]) << 8) | uint16(b[1]), nil +} + +func (d *Decoder) int16() (int16, error) { + n, err := d.uint16() + return int16(n), err +} + +func (d *Decoder) uint32() (uint32, error) { + b, err := d.readN(4) + if err != nil { + return 0, err + } + n := (uint32(b[0]) << 24) | + (uint32(b[1]) << 16) | + (uint32(b[2]) << 8) | + uint32(b[3]) + return n, nil +} + +func (d *Decoder) int32() (int32, error) { + n, err := d.uint32() + return int32(n), err +} + +func (d *Decoder) uint64() (uint64, error) { + b, err := d.readN(8) + if err != nil { + return 0, err + } + n := (uint64(b[0]) << 56) | + (uint64(b[1]) << 48) | + (uint64(b[2]) << 40) | + (uint64(b[3]) << 32) | + (uint64(b[4]) << 24) | + (uint64(b[5]) << 16) | + (uint64(b[6]) << 8) | + uint64(b[7]) + return n, nil +} + +func (d *Decoder) int64() (int64, error) { + n, err := d.uint64() + return int64(n), err +} + +// DecodeUint64 decodes msgpack int8/16/32/64 and uint8/16/32/64 +// into Go uint64. +func (d *Decoder) DecodeUint64() (uint64, error) { + c, err := d.readCode() + if err != nil { + return 0, err + } + return d.uint(c) +} + +func (d *Decoder) uint(c codes.Code) (uint64, error) { + if c == codes.Nil { + return 0, nil + } + if codes.IsFixedNum(c) { + return uint64(int8(c)), nil + } + switch c { + case codes.Uint8: + n, err := d.uint8() + return uint64(n), err + case codes.Int8: + n, err := d.int8() + return uint64(n), err + case codes.Uint16: + n, err := d.uint16() + return uint64(n), err + case codes.Int16: + n, err := d.int16() + return uint64(n), err + case codes.Uint32: + n, err := d.uint32() + return uint64(n), err + case codes.Int32: + n, err := d.int32() + return uint64(n), err + case codes.Uint64, codes.Int64: + return d.uint64() + } + return 0, fmt.Errorf("msgpack: invalid code=%x decoding uint64", c) +} + +// DecodeInt64 decodes msgpack int8/16/32/64 and uint8/16/32/64 +// into Go int64. +func (d *Decoder) DecodeInt64() (int64, error) { + c, err := d.readCode() + if err != nil { + return 0, err + } + return d.int(c) +} + +func (d *Decoder) int(c codes.Code) (int64, error) { + if c == codes.Nil { + return 0, nil + } + if codes.IsFixedNum(c) { + return int64(int8(c)), nil + } + switch c { + case codes.Uint8: + n, err := d.uint8() + return int64(n), err + case codes.Int8: + n, err := d.uint8() + return int64(int8(n)), err + case codes.Uint16: + n, err := d.uint16() + return int64(n), err + case codes.Int16: + n, err := d.uint16() + return int64(int16(n)), err + case codes.Uint32: + n, err := d.uint32() + return int64(n), err + case codes.Int32: + n, err := d.uint32() + return int64(int32(n)), err + case codes.Uint64, codes.Int64: + n, err := d.uint64() + return int64(n), err + } + return 0, fmt.Errorf("msgpack: invalid code=%x decoding int64", c) +} + +func (d *Decoder) DecodeFloat32() (float32, error) { + c, err := d.readCode() + if err != nil { + return 0, err + } + return d.float32(c) +} + +func (d *Decoder) float32(c codes.Code) (float32, error) { + if c == codes.Float { + n, err := d.uint32() + if err != nil { + return 0, err + } + return math.Float32frombits(n), nil + } + + n, err := d.int(c) + if err != nil { + return 0, fmt.Errorf("msgpack: invalid code=%x decoding float32", c) + } + return float32(n), nil +} + +// DecodeFloat64 decodes msgpack float32/64 into Go float64. +func (d *Decoder) DecodeFloat64() (float64, error) { + c, err := d.readCode() + if err != nil { + return 0, err + } + return d.float64(c) +} + +func (d *Decoder) float64(c codes.Code) (float64, error) { + switch c { + case codes.Float: + n, err := d.float32(c) + if err != nil { + return 0, err + } + return float64(n), nil + case codes.Double: + n, err := d.uint64() + if err != nil { + return 0, err + } + return math.Float64frombits(n), nil + } + + n, err := d.int(c) + if err != nil { + return 0, fmt.Errorf("msgpack: invalid code=%x decoding float32", c) + } + return float64(n), nil +} + +func (d *Decoder) DecodeUint() (uint, error) { + n, err := d.DecodeUint64() + return uint(n), err +} + +func (d *Decoder) DecodeUint8() (uint8, error) { + n, err := d.DecodeUint64() + return uint8(n), err +} + +func (d *Decoder) DecodeUint16() (uint16, error) { + n, err := d.DecodeUint64() + return uint16(n), err +} + +func (d *Decoder) DecodeUint32() (uint32, error) { + n, err := d.DecodeUint64() + return uint32(n), err +} + +func (d *Decoder) DecodeInt() (int, error) { + n, err := d.DecodeInt64() + return int(n), err +} + +func (d *Decoder) DecodeInt8() (int8, error) { + n, err := d.DecodeInt64() + return int8(n), err +} + +func (d *Decoder) DecodeInt16() (int16, error) { + n, err := d.DecodeInt64() + return int16(n), err +} + +func (d *Decoder) DecodeInt32() (int32, error) { + n, err := d.DecodeInt64() + return int32(n), err +} + +func decodeFloat32Value(d *Decoder, v reflect.Value) error { + f, err := d.DecodeFloat32() + if err != nil { + return err + } + if err = mustSet(v); err != nil { + return err + } + v.SetFloat(float64(f)) + return nil +} + +func decodeFloat64Value(d *Decoder, v reflect.Value) error { + f, err := d.DecodeFloat64() + if err != nil { + return err + } + if err = mustSet(v); err != nil { + return err + } + v.SetFloat(f) + return nil +} + +func decodeInt64Value(d *Decoder, v reflect.Value) error { + n, err := d.DecodeInt64() + if err != nil { + return err + } + if err = mustSet(v); err != nil { + return err + } + v.SetInt(n) + return nil +} + +func decodeUint64Value(d *Decoder, v reflect.Value) error { + n, err := d.DecodeUint64() + if err != nil { + return err + } + if err = mustSet(v); err != nil { + return err + } + v.SetUint(n) + return nil +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/decode_query.go b/vendor/github.com/vmihailenco/msgpack/v4/decode_query.go new file mode 100644 index 000000000000..80cd80e78521 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/decode_query.go @@ -0,0 +1,158 @@ +package msgpack + +import ( + "fmt" + "strconv" + "strings" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +type queryResult struct { + query string + key string + hasAsterisk bool + + values []interface{} +} + +func (q *queryResult) nextKey() { + ind := strings.IndexByte(q.query, '.') + if ind == -1 { + q.key = q.query + q.query = "" + return + } + q.key = q.query[:ind] + q.query = q.query[ind+1:] +} + +// Query extracts data specified by the query from the msgpack stream skipping +// any other data. Query consists of map keys and array indexes separated with dot, +// e.g. key1.0.key2. +func (d *Decoder) Query(query string) ([]interface{}, error) { + res := queryResult{ + query: query, + } + if err := d.query(&res); err != nil { + return nil, err + } + return res.values, nil +} + +func (d *Decoder) query(q *queryResult) error { + q.nextKey() + if q.key == "" { + v, err := d.decodeInterfaceCond() + if err != nil { + return err + } + q.values = append(q.values, v) + return nil + } + + code, err := d.PeekCode() + if err != nil { + return err + } + + switch { + case code == codes.Map16 || code == codes.Map32 || codes.IsFixedMap(code): + err = d.queryMapKey(q) + case code == codes.Array16 || code == codes.Array32 || codes.IsFixedArray(code): + err = d.queryArrayIndex(q) + default: + err = fmt.Errorf("msgpack: unsupported code=%x decoding key=%q", code, q.key) + } + return err +} + +func (d *Decoder) queryMapKey(q *queryResult) error { + n, err := d.DecodeMapLen() + if err != nil { + return err + } + if n == -1 { + return nil + } + + for i := 0; i < n; i++ { + k, err := d.bytesNoCopy() + if err != nil { + return err + } + + if string(k) == q.key { + if err := d.query(q); err != nil { + return err + } + if q.hasAsterisk { + return d.skipNext((n - i - 1) * 2) + } + return nil + } + + if err := d.Skip(); err != nil { + return err + } + } + + return nil +} + +func (d *Decoder) queryArrayIndex(q *queryResult) error { + n, err := d.DecodeArrayLen() + if err != nil { + return err + } + if n == -1 { + return nil + } + + if q.key == "*" { + q.hasAsterisk = true + + query := q.query + for i := 0; i < n; i++ { + q.query = query + if err := d.query(q); err != nil { + return err + } + } + + q.hasAsterisk = false + return nil + } + + ind, err := strconv.Atoi(q.key) + if err != nil { + return err + } + + for i := 0; i < n; i++ { + if i == ind { + if err := d.query(q); err != nil { + return err + } + if q.hasAsterisk { + return d.skipNext(n - i - 1) + } + return nil + } + + if err := d.Skip(); err != nil { + return err + } + } + + return nil +} + +func (d *Decoder) skipNext(n int) error { + for i := 0; i < n; i++ { + if err := d.Skip(); err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/decode_slice.go b/vendor/github.com/vmihailenco/msgpack/v4/decode_slice.go new file mode 100644 index 000000000000..adf17ae5cfb7 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/decode_slice.go @@ -0,0 +1,191 @@ +package msgpack + +import ( + "fmt" + "reflect" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +var sliceStringPtrType = reflect.TypeOf((*[]string)(nil)) + +// DecodeArrayLen decodes array length. Length is -1 when array is nil. +func (d *Decoder) DecodeArrayLen() (int, error) { + c, err := d.readCode() + if err != nil { + return 0, err + } + return d.arrayLen(c) +} + +func (d *Decoder) arrayLen(c codes.Code) (int, error) { + if c == codes.Nil { + return -1, nil + } else if c >= codes.FixedArrayLow && c <= codes.FixedArrayHigh { + return int(c & codes.FixedArrayMask), nil + } + switch c { + case codes.Array16: + n, err := d.uint16() + return int(n), err + case codes.Array32: + n, err := d.uint32() + return int(n), err + } + return 0, fmt.Errorf("msgpack: invalid code=%x decoding array length", c) +} + +func decodeStringSliceValue(d *Decoder, v reflect.Value) error { + ptr := v.Addr().Convert(sliceStringPtrType).Interface().(*[]string) + return d.decodeStringSlicePtr(ptr) +} + +func (d *Decoder) decodeStringSlicePtr(ptr *[]string) error { + n, err := d.DecodeArrayLen() + if err != nil { + return err + } + if n == -1 { + return nil + } + + ss := makeStrings(*ptr, n) + for i := 0; i < n; i++ { + s, err := d.DecodeString() + if err != nil { + return err + } + ss = append(ss, s) + } + *ptr = ss + + return nil +} + +func makeStrings(s []string, n int) []string { + if n > sliceAllocLimit { + n = sliceAllocLimit + } + + if s == nil { + return make([]string, 0, n) + } + + if cap(s) >= n { + return s[:0] + } + + s = s[:cap(s)] + s = append(s, make([]string, n-len(s))...) + return s[:0] +} + +func decodeSliceValue(d *Decoder, v reflect.Value) error { + n, err := d.DecodeArrayLen() + if err != nil { + return err + } + + if n == -1 { + v.Set(reflect.Zero(v.Type())) + return nil + } + if n == 0 && v.IsNil() { + v.Set(reflect.MakeSlice(v.Type(), 0, 0)) + return nil + } + + if v.Cap() >= n { + v.Set(v.Slice(0, n)) + } else if v.Len() < v.Cap() { + v.Set(v.Slice(0, v.Cap())) + } + + for i := 0; i < n; i++ { + if i >= v.Len() { + v.Set(growSliceValue(v, n)) + } + elem := v.Index(i) + if err := d.DecodeValue(elem); err != nil { + return err + } + } + + return nil +} + +func growSliceValue(v reflect.Value, n int) reflect.Value { + diff := n - v.Len() + if diff > sliceAllocLimit { + diff = sliceAllocLimit + } + v = reflect.AppendSlice(v, reflect.MakeSlice(v.Type(), diff, diff)) + return v +} + +func decodeArrayValue(d *Decoder, v reflect.Value) error { + n, err := d.DecodeArrayLen() + if err != nil { + return err + } + + if n == -1 { + return nil + } + if n > v.Len() { + return fmt.Errorf("%s len is %d, but msgpack has %d elements", v.Type(), v.Len(), n) + } + + for i := 0; i < n; i++ { + sv := v.Index(i) + if err := d.DecodeValue(sv); err != nil { + return err + } + } + + return nil +} + +func (d *Decoder) DecodeSlice() ([]interface{}, error) { + c, err := d.readCode() + if err != nil { + return nil, err + } + return d.decodeSlice(c) +} + +func (d *Decoder) decodeSlice(c codes.Code) ([]interface{}, error) { + n, err := d.arrayLen(c) + if err != nil { + return nil, err + } + if n == -1 { + return nil, nil + } + + s := make([]interface{}, 0, min(n, sliceAllocLimit)) + for i := 0; i < n; i++ { + v, err := d.decodeInterfaceCond() + if err != nil { + return nil, err + } + s = append(s, v) + } + + return s, nil +} + +func (d *Decoder) skipSlice(c codes.Code) error { + n, err := d.arrayLen(c) + if err != nil { + return err + } + + for i := 0; i < n; i++ { + if err := d.Skip(); err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/decode_string.go b/vendor/github.com/vmihailenco/msgpack/v4/decode_string.go new file mode 100644 index 000000000000..c5adf3865cb9 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/decode_string.go @@ -0,0 +1,186 @@ +package msgpack + +import ( + "fmt" + "reflect" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +func (d *Decoder) bytesLen(c codes.Code) (int, error) { + if c == codes.Nil { + return -1, nil + } + + if codes.IsFixedString(c) { + return int(c & codes.FixedStrMask), nil + } + + switch c { + case codes.Str8, codes.Bin8: + n, err := d.uint8() + return int(n), err + case codes.Str16, codes.Bin16: + n, err := d.uint16() + return int(n), err + case codes.Str32, codes.Bin32: + n, err := d.uint32() + return int(n), err + } + + return 0, fmt.Errorf("msgpack: invalid code=%x decoding bytes length", c) +} + +func (d *Decoder) DecodeString() (string, error) { + c, err := d.readCode() + if err != nil { + return "", err + } + return d.string(c) +} + +func (d *Decoder) string(c codes.Code) (string, error) { + n, err := d.bytesLen(c) + if err != nil { + return "", err + } + return d.stringWithLen(n) +} + +func (d *Decoder) stringWithLen(n int) (string, error) { + if n <= 0 { + return "", nil + } + b, err := d.readN(n) + return string(b), err +} + +func decodeStringValue(d *Decoder, v reflect.Value) error { + if err := mustSet(v); err != nil { + return err + } + + s, err := d.DecodeString() + if err != nil { + return err + } + + v.SetString(s) + return nil +} + +func (d *Decoder) DecodeBytesLen() (int, error) { + c, err := d.readCode() + if err != nil { + return 0, err + } + return d.bytesLen(c) +} + +func (d *Decoder) DecodeBytes() ([]byte, error) { + c, err := d.readCode() + if err != nil { + return nil, err + } + return d.bytes(c, nil) +} + +func (d *Decoder) bytes(c codes.Code, b []byte) ([]byte, error) { + n, err := d.bytesLen(c) + if err != nil { + return nil, err + } + if n == -1 { + return nil, nil + } + return readN(d.r, b, n) +} + +func (d *Decoder) bytesNoCopy() ([]byte, error) { + c, err := d.readCode() + if err != nil { + return nil, err + } + n, err := d.bytesLen(c) + if err != nil { + return nil, err + } + if n == -1 { + return nil, nil + } + return d.readN(n) +} + +func (d *Decoder) decodeBytesPtr(ptr *[]byte) error { + c, err := d.readCode() + if err != nil { + return err + } + return d.bytesPtr(c, ptr) +} + +func (d *Decoder) bytesPtr(c codes.Code, ptr *[]byte) error { + n, err := d.bytesLen(c) + if err != nil { + return err + } + if n == -1 { + *ptr = nil + return nil + } + + *ptr, err = readN(d.r, *ptr, n) + return err +} + +func (d *Decoder) skipBytes(c codes.Code) error { + n, err := d.bytesLen(c) + if err != nil { + return err + } + if n <= 0 { + return nil + } + return d.skipN(n) +} + +func decodeBytesValue(d *Decoder, v reflect.Value) error { + if err := mustSet(v); err != nil { + return err + } + + c, err := d.readCode() + if err != nil { + return err + } + + b, err := d.bytes(c, v.Bytes()) + if err != nil { + return err + } + + v.SetBytes(b) + + return nil +} + +func decodeByteArrayValue(d *Decoder, v reflect.Value) error { + c, err := d.readCode() + if err != nil { + return err + } + + n, err := d.bytesLen(c) + if err != nil { + return err + } + if n == -1 { + return nil + } + if n > v.Len() { + return fmt.Errorf("%s len is %d, but msgpack has %d elements", v.Type(), v.Len(), n) + } + + b := v.Slice(0, n).Bytes() + return d.readFull(b) +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/decode_value.go b/vendor/github.com/vmihailenco/msgpack/v4/decode_value.go new file mode 100644 index 000000000000..810d3be8f92c --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/decode_value.go @@ -0,0 +1,276 @@ +package msgpack + +import ( + "encoding" + "errors" + "fmt" + "reflect" +) + +var interfaceType = reflect.TypeOf((*interface{})(nil)).Elem() +var stringType = reflect.TypeOf((*string)(nil)).Elem() + +var valueDecoders []decoderFunc + +//nolint:gochecknoinits +func init() { + valueDecoders = []decoderFunc{ + reflect.Bool: decodeBoolValue, + reflect.Int: decodeInt64Value, + reflect.Int8: decodeInt64Value, + reflect.Int16: decodeInt64Value, + reflect.Int32: decodeInt64Value, + reflect.Int64: decodeInt64Value, + reflect.Uint: decodeUint64Value, + reflect.Uint8: decodeUint64Value, + reflect.Uint16: decodeUint64Value, + reflect.Uint32: decodeUint64Value, + reflect.Uint64: decodeUint64Value, + reflect.Float32: decodeFloat32Value, + reflect.Float64: decodeFloat64Value, + reflect.Complex64: decodeUnsupportedValue, + reflect.Complex128: decodeUnsupportedValue, + reflect.Array: decodeArrayValue, + reflect.Chan: decodeUnsupportedValue, + reflect.Func: decodeUnsupportedValue, + reflect.Interface: decodeInterfaceValue, + reflect.Map: decodeMapValue, + reflect.Ptr: decodeUnsupportedValue, + reflect.Slice: decodeSliceValue, + reflect.String: decodeStringValue, + reflect.Struct: decodeStructValue, + reflect.UnsafePointer: decodeUnsupportedValue, + } +} + +func mustSet(v reflect.Value) error { + if !v.CanSet() { + return fmt.Errorf("msgpack: Decode(nonsettable %s)", v.Type()) + } + return nil +} + +func getDecoder(typ reflect.Type) decoderFunc { + if v, ok := typeDecMap.Load(typ); ok { + return v.(decoderFunc) + } + fn := _getDecoder(typ) + typeDecMap.Store(typ, fn) + return fn +} + +func _getDecoder(typ reflect.Type) decoderFunc { + kind := typ.Kind() + + if typ.Implements(customDecoderType) { + return decodeCustomValue + } + if typ.Implements(unmarshalerType) { + return unmarshalValue + } + if typ.Implements(binaryUnmarshalerType) { + return unmarshalBinaryValue + } + + // Addressable struct field value. + if kind != reflect.Ptr { + ptr := reflect.PtrTo(typ) + if ptr.Implements(customDecoderType) { + return decodeCustomValueAddr + } + if ptr.Implements(unmarshalerType) { + return unmarshalValueAddr + } + if ptr.Implements(binaryUnmarshalerType) { + return unmarshalBinaryValueAddr + } + } + + switch kind { + case reflect.Ptr: + return ptrDecoderFunc(typ) + case reflect.Slice: + elem := typ.Elem() + if elem.Kind() == reflect.Uint8 { + return decodeBytesValue + } + if elem == stringType { + return decodeStringSliceValue + } + case reflect.Array: + if typ.Elem().Kind() == reflect.Uint8 { + return decodeByteArrayValue + } + case reflect.Map: + if typ.Key() == stringType { + switch typ.Elem() { + case stringType: + return decodeMapStringStringValue + case interfaceType: + return decodeMapStringInterfaceValue + } + } + } + + return valueDecoders[kind] +} + +func ptrDecoderFunc(typ reflect.Type) decoderFunc { + decoder := getDecoder(typ.Elem()) + return func(d *Decoder, v reflect.Value) error { + if d.hasNilCode() { + if err := mustSet(v); err != nil { + return err + } + if !v.IsNil() { + v.Set(reflect.Zero(v.Type())) + } + return d.DecodeNil() + } + if v.IsNil() { + if err := mustSet(v); err != nil { + return err + } + v.Set(reflect.New(v.Type().Elem())) + } + return decoder(d, v.Elem()) + } +} + +func decodeCustomValueAddr(d *Decoder, v reflect.Value) error { + if !v.CanAddr() { + return fmt.Errorf("msgpack: Decode(nonaddressable %T)", v.Interface()) + } + return decodeCustomValue(d, v.Addr()) +} + +func decodeCustomValue(d *Decoder, v reflect.Value) error { + if d.hasNilCode() { + return d.decodeNilValue(v) + } + + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + + decoder := v.Interface().(CustomDecoder) + return decoder.DecodeMsgpack(d) +} + +func unmarshalValueAddr(d *Decoder, v reflect.Value) error { + if !v.CanAddr() { + return fmt.Errorf("msgpack: Decode(nonaddressable %T)", v.Interface()) + } + return unmarshalValue(d, v.Addr()) +} + +func unmarshalValue(d *Decoder, v reflect.Value) error { + if d.extLen == 0 || d.extLen == 1 { + if d.hasNilCode() { + return d.decodeNilValue(v) + } + } + + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + + var b []byte + + if d.extLen != 0 { + var err error + b, err = d.readN(d.extLen) + if err != nil { + return err + } + } else { + d.rec = make([]byte, 0, 64) + if err := d.Skip(); err != nil { + return err + } + b = d.rec + d.rec = nil + } + + unmarshaler := v.Interface().(Unmarshaler) + return unmarshaler.UnmarshalMsgpack(b) +} + +func decodeBoolValue(d *Decoder, v reflect.Value) error { + flag, err := d.DecodeBool() + if err != nil { + return err + } + if err = mustSet(v); err != nil { + return err + } + v.SetBool(flag) + return nil +} + +func decodeInterfaceValue(d *Decoder, v reflect.Value) error { + if v.IsNil() { + return d.interfaceValue(v) + } + + elem := v.Elem() + if !elem.CanAddr() { + if d.hasNilCode() { + v.Set(reflect.Zero(v.Type())) + return d.DecodeNil() + } + } + + return d.DecodeValue(elem) +} + +func (d *Decoder) interfaceValue(v reflect.Value) error { + vv, err := d.decodeInterfaceCond() + if err != nil { + return err + } + + if vv != nil { + if v.Type() == errorType { + if vv, ok := vv.(string); ok { + v.Set(reflect.ValueOf(errors.New(vv))) + return nil + } + } + + v.Set(reflect.ValueOf(vv)) + } + + return nil +} + +func decodeUnsupportedValue(d *Decoder, v reflect.Value) error { + return fmt.Errorf("msgpack: Decode(unsupported %s)", v.Type()) +} + +//------------------------------------------------------------------------------ + +func unmarshalBinaryValueAddr(d *Decoder, v reflect.Value) error { + if !v.CanAddr() { + return fmt.Errorf("msgpack: Decode(nonaddressable %T)", v.Interface()) + } + return unmarshalBinaryValue(d, v.Addr()) +} + +func unmarshalBinaryValue(d *Decoder, v reflect.Value) error { + if d.hasNilCode() { + return d.decodeNilValue(v) + } + + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + + data, err := d.DecodeBytes() + if err != nil { + return err + } + + unmarshaler := v.Interface().(encoding.BinaryUnmarshaler) + return unmarshaler.UnmarshalBinary(data) +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/encode.go b/vendor/github.com/vmihailenco/msgpack/v4/encode.go new file mode 100644 index 000000000000..37f098701ea0 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/encode.go @@ -0,0 +1,241 @@ +package msgpack + +import ( + "bytes" + "io" + "reflect" + "sync" + "time" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +const ( + sortMapKeysFlag uint32 = 1 << iota + structAsArrayFlag + encodeUsingJSONFlag + useCompactIntsFlag + useCompactFloatsFlag +) + +type writer interface { + io.Writer + WriteByte(byte) error +} + +type byteWriter struct { + io.Writer + + buf [1]byte +} + +func newByteWriter(w io.Writer) *byteWriter { + bw := new(byteWriter) + bw.Reset(w) + return bw +} + +func (bw *byteWriter) Reset(w io.Writer) { + bw.Writer = w +} + +func (bw *byteWriter) WriteByte(c byte) error { + bw.buf[0] = c + _, err := bw.Write(bw.buf[:]) + return err +} + +//------------------------------------------------------------------------------ + +var encPool = sync.Pool{ + New: func() interface{} { + return NewEncoder(nil) + }, +} + +// Marshal returns the MessagePack encoding of v. +func Marshal(v interface{}) ([]byte, error) { + enc := encPool.Get().(*Encoder) + + var buf bytes.Buffer + enc.Reset(&buf) + + err := enc.Encode(v) + b := buf.Bytes() + + encPool.Put(enc) + + if err != nil { + return nil, err + } + return b, err +} + +type Encoder struct { + w writer + + buf []byte + timeBuf []byte + bootstrap [9 + 12]byte + + intern map[string]int + + flags uint32 +} + +// NewEncoder returns a new encoder that writes to w. +func NewEncoder(w io.Writer) *Encoder { + e := new(Encoder) + e.buf = e.bootstrap[:9] + e.timeBuf = e.bootstrap[9 : 9+12] + e.Reset(w) + return e +} + +func (e *Encoder) Reset(w io.Writer) { + if bw, ok := w.(writer); ok { + e.w = bw + } else if bw, ok := e.w.(*byteWriter); ok { + bw.Reset(w) + } else { + e.w = newByteWriter(w) + } + + for k := range e.intern { + delete(e.intern, k) + } + + //TODO: + //e.sortMapKeys = false + //e.structAsArray = false + //e.useJSONTag = false + //e.useCompact = false +} + +// SortMapKeys causes the Encoder to encode map keys in increasing order. +// Supported map types are: +// - map[string]string +// - map[string]interface{} +func (e *Encoder) SortMapKeys(on bool) *Encoder { + if on { + e.flags |= sortMapKeysFlag + } else { + e.flags &= ^sortMapKeysFlag + } + return e +} + +// StructAsArray causes the Encoder to encode Go structs as msgpack arrays. +func (e *Encoder) StructAsArray(on bool) *Encoder { + if on { + e.flags |= structAsArrayFlag + } else { + e.flags &= ^structAsArrayFlag + } + return e +} + +// UseJSONTag causes the Encoder to use json struct tag as fallback option +// if there is no msgpack tag. +func (e *Encoder) UseJSONTag(on bool) *Encoder { + if on { + e.flags |= encodeUsingJSONFlag + } else { + e.flags &= ^encodeUsingJSONFlag + } + return e +} + +// UseCompactEncoding causes the Encoder to chose the most compact encoding. +// For example, it allows to encode small Go int64 as msgpack int8 saving 7 bytes. +func (e *Encoder) UseCompactEncoding(on bool) *Encoder { + if on { + e.flags |= useCompactIntsFlag + } else { + e.flags &= ^useCompactIntsFlag + } + return e +} + +// UseCompactFloats causes the Encoder to chose a compact integer encoding +// for floats that can be represented as integers. +func (e *Encoder) UseCompactFloats(on bool) { + if on { + e.flags |= useCompactFloatsFlag + } else { + e.flags &= ^useCompactFloatsFlag + } +} + +func (e *Encoder) Encode(v interface{}) error { + switch v := v.(type) { + case nil: + return e.EncodeNil() + case string: + return e.EncodeString(v) + case []byte: + return e.EncodeBytes(v) + case int: + return e.encodeInt64Cond(int64(v)) + case int64: + return e.encodeInt64Cond(v) + case uint: + return e.encodeUint64Cond(uint64(v)) + case uint64: + return e.encodeUint64Cond(v) + case bool: + return e.EncodeBool(v) + case float32: + return e.EncodeFloat32(v) + case float64: + return e.EncodeFloat64(v) + case time.Duration: + return e.encodeInt64Cond(int64(v)) + case time.Time: + return e.EncodeTime(v) + } + return e.EncodeValue(reflect.ValueOf(v)) +} + +func (e *Encoder) EncodeMulti(v ...interface{}) error { + for _, vv := range v { + if err := e.Encode(vv); err != nil { + return err + } + } + return nil +} + +func (e *Encoder) EncodeValue(v reflect.Value) error { + fn := getEncoder(v.Type()) + return fn(e, v) +} + +func (e *Encoder) EncodeNil() error { + return e.writeCode(codes.Nil) +} + +func (e *Encoder) EncodeBool(value bool) error { + if value { + return e.writeCode(codes.True) + } + return e.writeCode(codes.False) +} + +func (e *Encoder) EncodeDuration(d time.Duration) error { + return e.EncodeInt(int64(d)) +} + +func (e *Encoder) writeCode(c codes.Code) error { + return e.w.WriteByte(byte(c)) +} + +func (e *Encoder) write(b []byte) error { + _, err := e.w.Write(b) + return err +} + +func (e *Encoder) writeString(s string) error { + _, err := e.w.Write(stringToBytes(s)) + return err +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/encode_map.go b/vendor/github.com/vmihailenco/msgpack/v4/encode_map.go new file mode 100644 index 000000000000..d9b954d8667a --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/encode_map.go @@ -0,0 +1,172 @@ +package msgpack + +import ( + "reflect" + "sort" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +func encodeMapValue(e *Encoder, v reflect.Value) error { + if v.IsNil() { + return e.EncodeNil() + } + + if err := e.EncodeMapLen(v.Len()); err != nil { + return err + } + + for _, key := range v.MapKeys() { + if err := e.EncodeValue(key); err != nil { + return err + } + if err := e.EncodeValue(v.MapIndex(key)); err != nil { + return err + } + } + + return nil +} + +func encodeMapStringStringValue(e *Encoder, v reflect.Value) error { + if v.IsNil() { + return e.EncodeNil() + } + + if err := e.EncodeMapLen(v.Len()); err != nil { + return err + } + + m := v.Convert(mapStringStringType).Interface().(map[string]string) + if e.flags&sortMapKeysFlag != 0 { + return e.encodeSortedMapStringString(m) + } + + for mk, mv := range m { + if err := e.EncodeString(mk); err != nil { + return err + } + if err := e.EncodeString(mv); err != nil { + return err + } + } + + return nil +} + +func encodeMapStringInterfaceValue(e *Encoder, v reflect.Value) error { + if v.IsNil() { + return e.EncodeNil() + } + + if err := e.EncodeMapLen(v.Len()); err != nil { + return err + } + + m := v.Convert(mapStringInterfaceType).Interface().(map[string]interface{}) + if e.flags&sortMapKeysFlag != 0 { + return e.encodeSortedMapStringInterface(m) + } + + for mk, mv := range m { + if err := e.EncodeString(mk); err != nil { + return err + } + if err := e.Encode(mv); err != nil { + return err + } + } + + return nil +} + +func (e *Encoder) encodeSortedMapStringString(m map[string]string) error { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + + for _, k := range keys { + err := e.EncodeString(k) + if err != nil { + return err + } + if err = e.EncodeString(m[k]); err != nil { + return err + } + } + + return nil +} + +func (e *Encoder) encodeSortedMapStringInterface(m map[string]interface{}) error { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + + for _, k := range keys { + err := e.EncodeString(k) + if err != nil { + return err + } + if err = e.Encode(m[k]); err != nil { + return err + } + } + + return nil +} + +func (e *Encoder) EncodeMapLen(l int) error { + if l < 16 { + return e.writeCode(codes.FixedMapLow | codes.Code(l)) + } + if l < 65536 { + return e.write2(codes.Map16, uint16(l)) + } + return e.write4(codes.Map32, uint32(l)) +} + +func encodeStructValue(e *Encoder, strct reflect.Value) error { + var structFields *fields + if e.flags&encodeUsingJSONFlag != 0 { + structFields = jsonStructs.Fields(strct.Type()) + } else { + structFields = structs.Fields(strct.Type()) + } + + if e.flags&structAsArrayFlag != 0 || structFields.AsArray { + return encodeStructValueAsArray(e, strct, structFields.List) + } + fields := structFields.OmitEmpty(strct) + + if err := e.EncodeMapLen(len(fields)); err != nil { + return err + } + + for _, f := range fields { + if err := e.EncodeString(f.name); err != nil { + return err + } + if err := f.EncodeValue(e, strct); err != nil { + return err + } + } + + return nil +} + +func encodeStructValueAsArray(e *Encoder, strct reflect.Value, fields []*field) error { + if err := e.EncodeArrayLen(len(fields)); err != nil { + return err + } + for _, f := range fields { + if err := f.EncodeValue(e, strct); err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/encode_number.go b/vendor/github.com/vmihailenco/msgpack/v4/encode_number.go new file mode 100644 index 000000000000..bf3c2f851ae8 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/encode_number.go @@ -0,0 +1,244 @@ +package msgpack + +import ( + "math" + "reflect" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +// EncodeUint8 encodes an uint8 in 2 bytes preserving type of the number. +func (e *Encoder) EncodeUint8(n uint8) error { + return e.write1(codes.Uint8, n) +} + +func (e *Encoder) encodeUint8Cond(n uint8) error { + if e.flags&useCompactIntsFlag != 0 { + return e.EncodeUint(uint64(n)) + } + return e.EncodeUint8(n) +} + +// EncodeUint16 encodes an uint16 in 3 bytes preserving type of the number. +func (e *Encoder) EncodeUint16(n uint16) error { + return e.write2(codes.Uint16, n) +} + +func (e *Encoder) encodeUint16Cond(n uint16) error { + if e.flags&useCompactIntsFlag != 0 { + return e.EncodeUint(uint64(n)) + } + return e.EncodeUint16(n) +} + +// EncodeUint32 encodes an uint16 in 5 bytes preserving type of the number. +func (e *Encoder) EncodeUint32(n uint32) error { + return e.write4(codes.Uint32, n) +} + +func (e *Encoder) encodeUint32Cond(n uint32) error { + if e.flags&useCompactIntsFlag != 0 { + return e.EncodeUint(uint64(n)) + } + return e.EncodeUint32(n) +} + +// EncodeUint64 encodes an uint16 in 9 bytes preserving type of the number. +func (e *Encoder) EncodeUint64(n uint64) error { + return e.write8(codes.Uint64, n) +} + +func (e *Encoder) encodeUint64Cond(n uint64) error { + if e.flags&useCompactIntsFlag != 0 { + return e.EncodeUint(n) + } + return e.EncodeUint64(n) +} + +// EncodeInt8 encodes an int8 in 2 bytes preserving type of the number. +func (e *Encoder) EncodeInt8(n int8) error { + return e.write1(codes.Int8, uint8(n)) +} + +func (e *Encoder) encodeInt8Cond(n int8) error { + if e.flags&useCompactIntsFlag != 0 { + return e.EncodeInt(int64(n)) + } + return e.EncodeInt8(n) +} + +// EncodeInt16 encodes an int16 in 3 bytes preserving type of the number. +func (e *Encoder) EncodeInt16(n int16) error { + return e.write2(codes.Int16, uint16(n)) +} + +func (e *Encoder) encodeInt16Cond(n int16) error { + if e.flags&useCompactIntsFlag != 0 { + return e.EncodeInt(int64(n)) + } + return e.EncodeInt16(n) +} + +// EncodeInt32 encodes an int32 in 5 bytes preserving type of the number. +func (e *Encoder) EncodeInt32(n int32) error { + return e.write4(codes.Int32, uint32(n)) +} + +func (e *Encoder) encodeInt32Cond(n int32) error { + if e.flags&useCompactIntsFlag != 0 { + return e.EncodeInt(int64(n)) + } + return e.EncodeInt32(n) +} + +// EncodeInt64 encodes an int64 in 9 bytes preserving type of the number. +func (e *Encoder) EncodeInt64(n int64) error { + return e.write8(codes.Int64, uint64(n)) +} + +func (e *Encoder) encodeInt64Cond(n int64) error { + if e.flags&useCompactIntsFlag != 0 { + return e.EncodeInt(n) + } + return e.EncodeInt64(n) +} + +// EncodeUnsignedNumber encodes an uint64 in 1, 2, 3, 5, or 9 bytes. +// Type of the number is lost during encoding. +func (e *Encoder) EncodeUint(n uint64) error { + if n <= math.MaxInt8 { + return e.w.WriteByte(byte(n)) + } + if n <= math.MaxUint8 { + return e.EncodeUint8(uint8(n)) + } + if n <= math.MaxUint16 { + return e.EncodeUint16(uint16(n)) + } + if n <= math.MaxUint32 { + return e.EncodeUint32(uint32(n)) + } + return e.EncodeUint64(n) +} + +// EncodeNumber encodes an int64 in 1, 2, 3, 5, or 9 bytes. +// Type of the number is lost during encoding. +func (e *Encoder) EncodeInt(n int64) error { + if n >= 0 { + return e.EncodeUint(uint64(n)) + } + if n >= int64(int8(codes.NegFixedNumLow)) { + return e.w.WriteByte(byte(n)) + } + if n >= math.MinInt8 { + return e.EncodeInt8(int8(n)) + } + if n >= math.MinInt16 { + return e.EncodeInt16(int16(n)) + } + if n >= math.MinInt32 { + return e.EncodeInt32(int32(n)) + } + return e.EncodeInt64(n) +} + +func (e *Encoder) EncodeFloat32(n float32) error { + if e.flags&useCompactFloatsFlag != 0 { + if float32(int64(n)) == n { + return e.EncodeInt(int64(n)) + } + } + return e.write4(codes.Float, math.Float32bits(n)) +} + +func (e *Encoder) EncodeFloat64(n float64) error { + if e.flags&useCompactFloatsFlag != 0 { + // Both NaN and Inf convert to int64(-0x8000000000000000) + // If n is NaN then it never compares true with any other value + // If n is Inf then it doesn't convert from int64 back to +/-Inf + // In both cases the comparison works. + if float64(int64(n)) == n { + return e.EncodeInt(int64(n)) + } + } + return e.write8(codes.Double, math.Float64bits(n)) +} + +func (e *Encoder) write1(code codes.Code, n uint8) error { + e.buf = e.buf[:2] + e.buf[0] = byte(code) + e.buf[1] = n + return e.write(e.buf) +} + +func (e *Encoder) write2(code codes.Code, n uint16) error { + e.buf = e.buf[:3] + e.buf[0] = byte(code) + e.buf[1] = byte(n >> 8) + e.buf[2] = byte(n) + return e.write(e.buf) +} + +func (e *Encoder) write4(code codes.Code, n uint32) error { + e.buf = e.buf[:5] + e.buf[0] = byte(code) + e.buf[1] = byte(n >> 24) + e.buf[2] = byte(n >> 16) + e.buf[3] = byte(n >> 8) + e.buf[4] = byte(n) + return e.write(e.buf) +} + +func (e *Encoder) write8(code codes.Code, n uint64) error { + e.buf = e.buf[:9] + e.buf[0] = byte(code) + e.buf[1] = byte(n >> 56) + e.buf[2] = byte(n >> 48) + e.buf[3] = byte(n >> 40) + e.buf[4] = byte(n >> 32) + e.buf[5] = byte(n >> 24) + e.buf[6] = byte(n >> 16) + e.buf[7] = byte(n >> 8) + e.buf[8] = byte(n) + return e.write(e.buf) +} + +func encodeUint8CondValue(e *Encoder, v reflect.Value) error { + return e.encodeUint8Cond(uint8(v.Uint())) +} + +func encodeUint16CondValue(e *Encoder, v reflect.Value) error { + return e.encodeUint16Cond(uint16(v.Uint())) +} + +func encodeUint32CondValue(e *Encoder, v reflect.Value) error { + return e.encodeUint32Cond(uint32(v.Uint())) +} + +func encodeUint64CondValue(e *Encoder, v reflect.Value) error { + return e.encodeUint64Cond(v.Uint()) +} + +func encodeInt8CondValue(e *Encoder, v reflect.Value) error { + return e.encodeInt8Cond(int8(v.Int())) +} + +func encodeInt16CondValue(e *Encoder, v reflect.Value) error { + return e.encodeInt16Cond(int16(v.Int())) +} + +func encodeInt32CondValue(e *Encoder, v reflect.Value) error { + return e.encodeInt32Cond(int32(v.Int())) +} + +func encodeInt64CondValue(e *Encoder, v reflect.Value) error { + return e.encodeInt64Cond(v.Int()) +} + +func encodeFloat32Value(e *Encoder, v reflect.Value) error { + return e.EncodeFloat32(float32(v.Float())) +} + +func encodeFloat64Value(e *Encoder, v reflect.Value) error { + return e.EncodeFloat64(v.Float()) +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/encode_slice.go b/vendor/github.com/vmihailenco/msgpack/v4/encode_slice.go new file mode 100644 index 000000000000..69a9618e0645 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/encode_slice.go @@ -0,0 +1,131 @@ +package msgpack + +import ( + "reflect" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +var sliceStringType = reflect.TypeOf(([]string)(nil)) + +func encodeStringValue(e *Encoder, v reflect.Value) error { + return e.EncodeString(v.String()) +} + +func encodeByteSliceValue(e *Encoder, v reflect.Value) error { + return e.EncodeBytes(v.Bytes()) +} + +func encodeByteArrayValue(e *Encoder, v reflect.Value) error { + if err := e.EncodeBytesLen(v.Len()); err != nil { + return err + } + + if v.CanAddr() { + b := v.Slice(0, v.Len()).Bytes() + return e.write(b) + } + + e.buf = grow(e.buf, v.Len()) + reflect.Copy(reflect.ValueOf(e.buf), v) + return e.write(e.buf) +} + +func grow(b []byte, n int) []byte { + if cap(b) >= n { + return b[:n] + } + b = b[:cap(b)] + b = append(b, make([]byte, n-len(b))...) + return b +} + +func (e *Encoder) EncodeBytesLen(l int) error { + if l < 256 { + return e.write1(codes.Bin8, uint8(l)) + } + if l < 65536 { + return e.write2(codes.Bin16, uint16(l)) + } + return e.write4(codes.Bin32, uint32(l)) +} + +func (e *Encoder) encodeStrLen(l int) error { + if l < 32 { + return e.writeCode(codes.FixedStrLow | codes.Code(l)) + } + if l < 256 { + return e.write1(codes.Str8, uint8(l)) + } + if l < 65536 { + return e.write2(codes.Str16, uint16(l)) + } + return e.write4(codes.Str32, uint32(l)) +} + +func (e *Encoder) EncodeString(v string) error { + if err := e.encodeStrLen(len(v)); err != nil { + return err + } + return e.writeString(v) +} + +func (e *Encoder) EncodeBytes(v []byte) error { + if v == nil { + return e.EncodeNil() + } + if err := e.EncodeBytesLen(len(v)); err != nil { + return err + } + return e.write(v) +} + +func (e *Encoder) EncodeArrayLen(l int) error { + if l < 16 { + return e.writeCode(codes.FixedArrayLow | codes.Code(l)) + } + if l < 65536 { + return e.write2(codes.Array16, uint16(l)) + } + return e.write4(codes.Array32, uint32(l)) +} + +func encodeStringSliceValue(e *Encoder, v reflect.Value) error { + ss := v.Convert(sliceStringType).Interface().([]string) + return e.encodeStringSlice(ss) +} + +func (e *Encoder) encodeStringSlice(s []string) error { + if s == nil { + return e.EncodeNil() + } + if err := e.EncodeArrayLen(len(s)); err != nil { + return err + } + for _, v := range s { + if err := e.EncodeString(v); err != nil { + return err + } + } + return nil +} + +func encodeSliceValue(e *Encoder, v reflect.Value) error { + if v.IsNil() { + return e.EncodeNil() + } + return encodeArrayValue(e, v) +} + +func encodeArrayValue(e *Encoder, v reflect.Value) error { + l := v.Len() + if err := e.EncodeArrayLen(l); err != nil { + return err + } + for i := 0; i < l; i++ { + if err := e.EncodeValue(v.Index(i)); err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/encode_value.go b/vendor/github.com/vmihailenco/msgpack/v4/encode_value.go new file mode 100644 index 000000000000..335fcdb7ed6c --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/encode_value.go @@ -0,0 +1,216 @@ +package msgpack + +import ( + "encoding" + "fmt" + "reflect" +) + +var valueEncoders []encoderFunc + +//nolint:gochecknoinits +func init() { + valueEncoders = []encoderFunc{ + reflect.Bool: encodeBoolValue, + reflect.Int: encodeInt64CondValue, + reflect.Int8: encodeInt8CondValue, + reflect.Int16: encodeInt16CondValue, + reflect.Int32: encodeInt32CondValue, + reflect.Int64: encodeInt64CondValue, + reflect.Uint: encodeUint64CondValue, + reflect.Uint8: encodeUint8CondValue, + reflect.Uint16: encodeUint16CondValue, + reflect.Uint32: encodeUint32CondValue, + reflect.Uint64: encodeUint64CondValue, + reflect.Float32: encodeFloat32Value, + reflect.Float64: encodeFloat64Value, + reflect.Complex64: encodeUnsupportedValue, + reflect.Complex128: encodeUnsupportedValue, + reflect.Array: encodeArrayValue, + reflect.Chan: encodeUnsupportedValue, + reflect.Func: encodeUnsupportedValue, + reflect.Interface: encodeInterfaceValue, + reflect.Map: encodeMapValue, + reflect.Ptr: encodeUnsupportedValue, + reflect.Slice: encodeSliceValue, + reflect.String: encodeStringValue, + reflect.Struct: encodeStructValue, + reflect.UnsafePointer: encodeUnsupportedValue, + } +} + +func getEncoder(typ reflect.Type) encoderFunc { + if v, ok := typeEncMap.Load(typ); ok { + return v.(encoderFunc) + } + fn := _getEncoder(typ) + typeEncMap.Store(typ, fn) + return fn +} + +func _getEncoder(typ reflect.Type) encoderFunc { + kind := typ.Kind() + + if kind == reflect.Ptr { + if _, ok := typeEncMap.Load(typ.Elem()); ok { + return ptrEncoderFunc(typ) + } + } + + if typ.Implements(customEncoderType) { + return encodeCustomValue + } + if typ.Implements(marshalerType) { + return marshalValue + } + if typ.Implements(binaryMarshalerType) { + return marshalBinaryValue + } + + // Addressable struct field value. + if kind != reflect.Ptr { + ptr := reflect.PtrTo(typ) + if ptr.Implements(customEncoderType) { + return encodeCustomValuePtr + } + if ptr.Implements(marshalerType) { + return marshalValuePtr + } + if ptr.Implements(binaryMarshalerType) { + return marshalBinaryValuePtr + } + } + + if typ == errorType { + return encodeErrorValue + } + + switch kind { + case reflect.Ptr: + return ptrEncoderFunc(typ) + case reflect.Slice: + elem := typ.Elem() + if elem.Kind() == reflect.Uint8 { + return encodeByteSliceValue + } + if elem == stringType { + return encodeStringSliceValue + } + case reflect.Array: + if typ.Elem().Kind() == reflect.Uint8 { + return encodeByteArrayValue + } + case reflect.Map: + if typ.Key() == stringType { + switch typ.Elem() { + case stringType: + return encodeMapStringStringValue + case interfaceType: + return encodeMapStringInterfaceValue + } + } + } + + return valueEncoders[kind] +} + +func ptrEncoderFunc(typ reflect.Type) encoderFunc { + encoder := getEncoder(typ.Elem()) + return func(e *Encoder, v reflect.Value) error { + if v.IsNil() { + return e.EncodeNil() + } + return encoder(e, v.Elem()) + } +} + +func encodeCustomValuePtr(e *Encoder, v reflect.Value) error { + if !v.CanAddr() { + return fmt.Errorf("msgpack: Encode(non-addressable %T)", v.Interface()) + } + encoder := v.Addr().Interface().(CustomEncoder) + return encoder.EncodeMsgpack(e) +} + +func encodeCustomValue(e *Encoder, v reflect.Value) error { + if nilable(v) && v.IsNil() { + return e.EncodeNil() + } + + encoder := v.Interface().(CustomEncoder) + return encoder.EncodeMsgpack(e) +} + +func marshalValuePtr(e *Encoder, v reflect.Value) error { + if !v.CanAddr() { + return fmt.Errorf("msgpack: Encode(non-addressable %T)", v.Interface()) + } + return marshalValue(e, v.Addr()) +} + +func marshalValue(e *Encoder, v reflect.Value) error { + if nilable(v) && v.IsNil() { + return e.EncodeNil() + } + + marshaler := v.Interface().(Marshaler) + b, err := marshaler.MarshalMsgpack() + if err != nil { + return err + } + _, err = e.w.Write(b) + return err +} + +func encodeBoolValue(e *Encoder, v reflect.Value) error { + return e.EncodeBool(v.Bool()) +} + +func encodeInterfaceValue(e *Encoder, v reflect.Value) error { + if v.IsNil() { + return e.EncodeNil() + } + return e.EncodeValue(v.Elem()) +} + +func encodeErrorValue(e *Encoder, v reflect.Value) error { + if v.IsNil() { + return e.EncodeNil() + } + return e.EncodeString(v.Interface().(error).Error()) +} + +func encodeUnsupportedValue(e *Encoder, v reflect.Value) error { + return fmt.Errorf("msgpack: Encode(unsupported %s)", v.Type()) +} + +func nilable(v reflect.Value) bool { + switch v.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return true + } + return false +} + +//------------------------------------------------------------------------------ + +func marshalBinaryValuePtr(e *Encoder, v reflect.Value) error { + if !v.CanAddr() { + return fmt.Errorf("msgpack: Encode(non-addressable %T)", v.Interface()) + } + return marshalBinaryValue(e, v.Addr()) +} + +func marshalBinaryValue(e *Encoder, v reflect.Value) error { + if nilable(v) && v.IsNil() { + return e.EncodeNil() + } + + marshaler := v.Interface().(encoding.BinaryMarshaler) + data, err := marshaler.MarshalBinary() + if err != nil { + return err + } + + return e.EncodeBytes(data) +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/ext.go b/vendor/github.com/vmihailenco/msgpack/v4/ext.go new file mode 100644 index 000000000000..17e709bc8ff6 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/ext.go @@ -0,0 +1,244 @@ +package msgpack + +import ( + "bytes" + "fmt" + "reflect" + "sync" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +type extInfo struct { + Type reflect.Type + Decoder decoderFunc +} + +var extTypes = make(map[int8]*extInfo) + +var bufferPool = &sync.Pool{ + New: func() interface{} { + return new(bytes.Buffer) + }, +} + +// RegisterExt records a type, identified by a value for that type, +// under the provided id. That id will identify the concrete type of a value +// sent or received as an interface variable. Only types that will be +// transferred as implementations of interface values need to be registered. +// Expecting to be used only during initialization, it panics if the mapping +// between types and ids is not a bijection. +func RegisterExt(id int8, value interface{}) { + typ := reflect.TypeOf(value) + if typ.Kind() == reflect.Ptr { + typ = typ.Elem() + } + ptr := reflect.PtrTo(typ) + + if _, ok := extTypes[id]; ok { + panic(fmt.Errorf("msgpack: ext with id=%d is already registered", id)) + } + + registerExt(id, ptr, getEncoder(ptr), getDecoder(ptr)) + registerExt(id, typ, getEncoder(typ), getDecoder(typ)) +} + +func registerExt(id int8, typ reflect.Type, enc encoderFunc, dec decoderFunc) { + if enc != nil { + typeEncMap.Store(typ, makeExtEncoder(id, enc)) + } + if dec != nil { + extTypes[id] = &extInfo{ + Type: typ, + Decoder: dec, + } + typeDecMap.Store(typ, makeExtDecoder(id, dec)) + } +} + +func (e *Encoder) EncodeExtHeader(typeID int8, length int) error { + if err := e.encodeExtLen(length); err != nil { + return err + } + if err := e.w.WriteByte(byte(typeID)); err != nil { + return err + } + return nil +} + +func makeExtEncoder(typeID int8, enc encoderFunc) encoderFunc { + return func(e *Encoder, v reflect.Value) error { + buf := bufferPool.Get().(*bytes.Buffer) + defer bufferPool.Put(buf) + buf.Reset() + + oldw := e.w + e.w = buf + err := enc(e, v) + e.w = oldw + + if err != nil { + return err + } + + err = e.EncodeExtHeader(typeID, buf.Len()) + if err != nil { + return err + } + return e.write(buf.Bytes()) + } +} + +func makeExtDecoder(typeID int8, dec decoderFunc) decoderFunc { + return func(d *Decoder, v reflect.Value) error { + c, err := d.PeekCode() + if err != nil { + return err + } + + if !codes.IsExt(c) { + return dec(d, v) + } + + id, extLen, err := d.DecodeExtHeader() + if err != nil { + return err + } + + if id != typeID { + return fmt.Errorf("msgpack: got ext type=%d, wanted %d", id, typeID) + } + + d.extLen = extLen + return dec(d, v) + } +} + +func (e *Encoder) encodeExtLen(l int) error { + switch l { + case 1: + return e.writeCode(codes.FixExt1) + case 2: + return e.writeCode(codes.FixExt2) + case 4: + return e.writeCode(codes.FixExt4) + case 8: + return e.writeCode(codes.FixExt8) + case 16: + return e.writeCode(codes.FixExt16) + } + if l < 256 { + return e.write1(codes.Ext8, uint8(l)) + } + if l < 65536 { + return e.write2(codes.Ext16, uint16(l)) + } + return e.write4(codes.Ext32, uint32(l)) +} + +func (d *Decoder) parseExtLen(c codes.Code) (int, error) { + switch c { + case codes.FixExt1: + return 1, nil + case codes.FixExt2: + return 2, nil + case codes.FixExt4: + return 4, nil + case codes.FixExt8: + return 8, nil + case codes.FixExt16: + return 16, nil + case codes.Ext8: + n, err := d.uint8() + return int(n), err + case codes.Ext16: + n, err := d.uint16() + return int(n), err + case codes.Ext32: + n, err := d.uint32() + return int(n), err + default: + return 0, fmt.Errorf("msgpack: invalid code=%x decoding ext length", c) + } +} + +func (d *Decoder) extHeader(c codes.Code) (int8, int, error) { + length, err := d.parseExtLen(c) + if err != nil { + return 0, 0, err + } + + typeID, err := d.readCode() + if err != nil { + return 0, 0, err + } + + return int8(typeID), length, nil +} + +func (d *Decoder) DecodeExtHeader() (typeID int8, length int, err error) { + c, err := d.readCode() + if err != nil { + return + } + return d.extHeader(c) +} + +func (d *Decoder) extInterface(c codes.Code) (interface{}, error) { + extID, extLen, err := d.extHeader(c) + if err != nil { + return nil, err + } + + info, ok := extTypes[extID] + if !ok { + return nil, fmt.Errorf("msgpack: unknown ext id=%d", extID) + } + + v := reflect.New(info.Type) + + d.extLen = extLen + err = info.Decoder(d, v.Elem()) + d.extLen = 0 + if err != nil { + return nil, err + } + + return v.Interface(), nil +} + +func (d *Decoder) skipExt(c codes.Code) error { + n, err := d.parseExtLen(c) + if err != nil { + return err + } + return d.skipN(n + 1) +} + +func (d *Decoder) skipExtHeader(c codes.Code) error { + // Read ext type. + _, err := d.readCode() + if err != nil { + return err + } + // Read ext body len. + for i := 0; i < extHeaderLen(c); i++ { + _, err := d.readCode() + if err != nil { + return err + } + } + return nil +} + +func extHeaderLen(c codes.Code) int { + switch c { + case codes.Ext8: + return 1 + case codes.Ext16: + return 2 + case codes.Ext32: + return 4 + } + return 0 +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/intern.go b/vendor/github.com/vmihailenco/msgpack/v4/intern.go new file mode 100644 index 000000000000..6ca5692739ab --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/intern.go @@ -0,0 +1,236 @@ +package msgpack + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + "reflect" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +var internStringExtID int8 = -128 + +var errUnexpectedCode = errors.New("msgpack: unexpected code") + +func encodeInternInterfaceValue(e *Encoder, v reflect.Value) error { + if v.IsNil() { + return e.EncodeNil() + } + + v = v.Elem() + if v.Kind() == reflect.String { + return encodeInternStringValue(e, v) + } + return e.EncodeValue(v) +} + +func encodeInternStringValue(e *Encoder, v reflect.Value) error { + s := v.String() + + if s != "" { + if idx, ok := e.intern[s]; ok { + return e.internStringIndex(idx) + } + + if e.intern == nil { + e.intern = make(map[string]int) + } + + idx := len(e.intern) + e.intern[s] = idx + } + + return e.EncodeString(s) +} + +func (e *Encoder) internStringIndex(idx int) error { + if idx < math.MaxUint8 { + if err := e.writeCode(codes.FixExt1); err != nil { + return err + } + if err := e.w.WriteByte(byte(internStringExtID)); err != nil { + return err + } + return e.w.WriteByte(byte(idx)) + } + + if idx < math.MaxUint16 { + if err := e.writeCode(codes.FixExt2); err != nil { + return err + } + if err := e.w.WriteByte(byte(internStringExtID)); err != nil { + return err + } + if err := e.w.WriteByte(byte(idx >> 8)); err != nil { + return err + } + return e.w.WriteByte(byte(idx)) + } + + if int64(idx) < math.MaxUint32 { + if err := e.writeCode(codes.FixExt4); err != nil { + return err + } + if err := e.w.WriteByte(byte(internStringExtID)); err != nil { + return err + } + if err := e.w.WriteByte(byte(idx >> 24)); err != nil { + return err + } + if err := e.w.WriteByte(byte(idx >> 16)); err != nil { + return err + } + if err := e.w.WriteByte(byte(idx >> 8)); err != nil { + return err + } + return e.w.WriteByte(byte(idx)) + } + + return fmt.Errorf("msgpack: intern string index=%d is too large", idx) +} + +//------------------------------------------------------------------------------ + +func decodeInternInterfaceValue(d *Decoder, v reflect.Value) error { + c, err := d.readCode() + if err != nil { + return err + } + + s, err := d.internString(c) + if err == nil { + v.Set(reflect.ValueOf(s)) + return nil + } + if err != nil && err != errUnexpectedCode { + return err + } + + if err := d.s.UnreadByte(); err != nil { + return err + } + + return decodeInterfaceValue(d, v) +} + +func decodeInternStringValue(d *Decoder, v reflect.Value) error { + if err := mustSet(v); err != nil { + return err + } + + c, err := d.readCode() + if err != nil { + return err + } + + s, err := d.internString(c) + if err != nil { + if err == errUnexpectedCode { + return fmt.Errorf("msgpack: invalid code=%x decoding intern string", c) + } + return err + } + + v.SetString(s) + return nil +} + +func (d *Decoder) internString(c codes.Code) (string, error) { + if codes.IsFixedString(c) { + n := int(c & codes.FixedStrMask) + return d.internStringWithLen(n) + } + + switch c { + case codes.FixExt1, codes.FixExt2, codes.FixExt4: + typeID, length, err := d.extHeader(c) + if err != nil { + return "", err + } + if typeID != internStringExtID { + err := fmt.Errorf("msgpack: got ext type=%d, wanted %d", + typeID, internStringExtID) + return "", err + } + + idx, err := d.internStringIndex(length) + if err != nil { + return "", err + } + + return d.internStringAtIndex(idx) + case codes.Str8, codes.Bin8: + n, err := d.uint8() + if err != nil { + return "", err + } + return d.internStringWithLen(int(n)) + case codes.Str16, codes.Bin16: + n, err := d.uint16() + if err != nil { + return "", err + } + return d.internStringWithLen(int(n)) + case codes.Str32, codes.Bin32: + n, err := d.uint32() + if err != nil { + return "", err + } + return d.internStringWithLen(int(n)) + } + + return "", errUnexpectedCode +} + +func (d *Decoder) internStringIndex(length int) (int, error) { + switch length { + case 1: + c, err := d.s.ReadByte() + if err != nil { + return 0, err + } + return int(c), nil + case 2: + b, err := d.readN(2) + if err != nil { + return 0, err + } + n := binary.BigEndian.Uint16(b) + return int(n), nil + case 4: + b, err := d.readN(4) + if err != nil { + return 0, err + } + n := binary.BigEndian.Uint32(b) + return int(n), nil + } + + err := fmt.Errorf("msgpack: unsupported intern string index length=%d", length) + return 0, err +} + +func (d *Decoder) internStringAtIndex(idx int) (string, error) { + if idx >= len(d.intern) { + err := fmt.Errorf("msgpack: intern string with index=%d does not exist", idx) + return "", err + } + return d.intern[idx], nil +} + +func (d *Decoder) internStringWithLen(n int) (string, error) { + if n <= 0 { + return "", nil + } + + s, err := d.stringWithLen(n) + if err != nil { + return "", err + } + + d.intern = append(d.intern, s) + + return s, nil +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/msgpack.go b/vendor/github.com/vmihailenco/msgpack/v4/msgpack.go new file mode 100644 index 000000000000..220b43c47b31 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/msgpack.go @@ -0,0 +1,17 @@ +package msgpack + +type Marshaler interface { + MarshalMsgpack() ([]byte, error) +} + +type Unmarshaler interface { + UnmarshalMsgpack([]byte) error +} + +type CustomEncoder interface { + EncodeMsgpack(*Encoder) error +} + +type CustomDecoder interface { + DecodeMsgpack(*Decoder) error +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/safe.go b/vendor/github.com/vmihailenco/msgpack/v4/safe.go new file mode 100644 index 000000000000..8352c9dcefcd --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/safe.go @@ -0,0 +1,13 @@ +// +build appengine + +package msgpack + +// bytesToString converts byte slice to string. +func bytesToString(b []byte) string { + return string(b) +} + +// stringToBytes converts string to byte slice. +func stringToBytes(s string) []byte { + return []byte(s) +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/time.go b/vendor/github.com/vmihailenco/msgpack/v4/time.go new file mode 100644 index 000000000000..bf53eb2a36fc --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/time.go @@ -0,0 +1,149 @@ +package msgpack + +import ( + "encoding/binary" + "fmt" + "reflect" + "time" + + "github.com/vmihailenco/msgpack/v4/codes" +) + +var timeExtID int8 = -1 + +var timePtrType = reflect.TypeOf((*time.Time)(nil)) + +//nolint:gochecknoinits +func init() { + registerExt(timeExtID, timePtrType.Elem(), encodeTimeValue, decodeTimeValue) +} + +func (e *Encoder) EncodeTime(tm time.Time) error { + b := e.encodeTime(tm) + if err := e.encodeExtLen(len(b)); err != nil { + return err + } + if err := e.w.WriteByte(byte(timeExtID)); err != nil { + return err + } + return e.write(b) +} + +func (e *Encoder) encodeTime(tm time.Time) []byte { + secs := uint64(tm.Unix()) + if secs>>34 == 0 { + data := uint64(tm.Nanosecond())<<34 | secs + if data&0xffffffff00000000 == 0 { + b := e.timeBuf[:4] + binary.BigEndian.PutUint32(b, uint32(data)) + return b + } + b := e.timeBuf[:8] + binary.BigEndian.PutUint64(b, data) + return b + } + + b := e.timeBuf[:12] + binary.BigEndian.PutUint32(b, uint32(tm.Nanosecond())) + binary.BigEndian.PutUint64(b[4:], secs) + return b +} + +func (d *Decoder) DecodeTime() (time.Time, error) { + tm, err := d.decodeTime() + if err != nil { + return tm, err + } + + if tm.IsZero() { + // Assume that zero time does not have timezone information. + return tm.UTC(), nil + } + return tm, nil +} + +func (d *Decoder) decodeTime() (time.Time, error) { + extLen := d.extLen + d.extLen = 0 + if extLen == 0 { + c, err := d.readCode() + if err != nil { + return time.Time{}, err + } + + // Legacy format. + if c == codes.FixedArrayLow|2 { + sec, err := d.DecodeInt64() + if err != nil { + return time.Time{}, err + } + + nsec, err := d.DecodeInt64() + if err != nil { + return time.Time{}, err + } + + return time.Unix(sec, nsec), nil + } + + if codes.IsString(c) { + s, err := d.string(c) + if err != nil { + return time.Time{}, err + } + return time.Parse(time.RFC3339Nano, s) + } + + extLen, err = d.parseExtLen(c) + if err != nil { + return time.Time{}, err + } + + // Skip ext id. + _, err = d.s.ReadByte() + if err != nil { + return time.Time{}, nil + } + } + + b, err := d.readN(extLen) + if err != nil { + return time.Time{}, err + } + + switch len(b) { + case 4: + sec := binary.BigEndian.Uint32(b) + return time.Unix(int64(sec), 0), nil + case 8: + sec := binary.BigEndian.Uint64(b) + nsec := int64(sec >> 34) + sec &= 0x00000003ffffffff + return time.Unix(int64(sec), nsec), nil + case 12: + nsec := binary.BigEndian.Uint32(b) + sec := binary.BigEndian.Uint64(b[4:]) + return time.Unix(int64(sec), int64(nsec)), nil + default: + err = fmt.Errorf("msgpack: invalid ext len=%d decoding time", extLen) + return time.Time{}, err + } +} + +func encodeTimeValue(e *Encoder, v reflect.Value) error { + tm := v.Interface().(time.Time) + b := e.encodeTime(tm) + return e.write(b) +} + +func decodeTimeValue(d *Decoder, v reflect.Value) error { + tm, err := d.DecodeTime() + if err != nil { + return err + } + + ptr := v.Addr().Interface().(*time.Time) + *ptr = tm + + return nil +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/types.go b/vendor/github.com/vmihailenco/msgpack/v4/types.go new file mode 100644 index 000000000000..08cf099dd2a8 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/types.go @@ -0,0 +1,382 @@ +package msgpack + +import ( + "encoding" + "fmt" + "log" + "reflect" + "sync" + + "github.com/vmihailenco/tagparser" +) + +var errorType = reflect.TypeOf((*error)(nil)).Elem() + +var ( + customEncoderType = reflect.TypeOf((*CustomEncoder)(nil)).Elem() + customDecoderType = reflect.TypeOf((*CustomDecoder)(nil)).Elem() +) + +var ( + marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() + unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() +) + +var ( + binaryMarshalerType = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem() + binaryUnmarshalerType = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem() +) + +type ( + encoderFunc func(*Encoder, reflect.Value) error + decoderFunc func(*Decoder, reflect.Value) error +) + +var ( + typeEncMap sync.Map + typeDecMap sync.Map +) + +// Register registers encoder and decoder functions for a value. +// This is low level API and in most cases you should prefer implementing +// Marshaler/CustomEncoder and Unmarshaler/CustomDecoder interfaces. +func Register(value interface{}, enc encoderFunc, dec decoderFunc) { + typ := reflect.TypeOf(value) + if enc != nil { + typeEncMap.Store(typ, enc) + } + if dec != nil { + typeDecMap.Store(typ, dec) + } +} + +//------------------------------------------------------------------------------ + +var ( + structs = newStructCache(false) + jsonStructs = newStructCache(true) +) + +type structCache struct { + m sync.Map + + useJSONTag bool +} + +func newStructCache(useJSONTag bool) *structCache { + return &structCache{ + useJSONTag: useJSONTag, + } +} + +func (m *structCache) Fields(typ reflect.Type) *fields { + if v, ok := m.m.Load(typ); ok { + return v.(*fields) + } + + fs := getFields(typ, m.useJSONTag) + m.m.Store(typ, fs) + return fs +} + +//------------------------------------------------------------------------------ + +type field struct { + name string + index []int + omitEmpty bool + encoder encoderFunc + decoder decoderFunc +} + +func (f *field) Omit(strct reflect.Value) bool { + v, isNil := fieldByIndex(strct, f.index) + if isNil { + return true + } + return f.omitEmpty && isEmptyValue(v) +} + +func (f *field) EncodeValue(e *Encoder, strct reflect.Value) error { + v, isNil := fieldByIndex(strct, f.index) + if isNil { + return e.EncodeNil() + } + return f.encoder(e, v) +} + +func (f *field) DecodeValue(d *Decoder, strct reflect.Value) error { + v := fieldByIndexAlloc(strct, f.index) + return f.decoder(d, v) +} + +//------------------------------------------------------------------------------ + +type fields struct { + Type reflect.Type + Map map[string]*field + List []*field + AsArray bool + + hasOmitEmpty bool +} + +func newFields(typ reflect.Type) *fields { + return &fields{ + Type: typ, + Map: make(map[string]*field, typ.NumField()), + List: make([]*field, 0, typ.NumField()), + } +} + +func (fs *fields) Add(field *field) { + fs.warnIfFieldExists(field.name) + fs.Map[field.name] = field + fs.List = append(fs.List, field) + if field.omitEmpty { + fs.hasOmitEmpty = true + } +} + +func (fs *fields) warnIfFieldExists(name string) { + if _, ok := fs.Map[name]; ok { + log.Printf("msgpack: %s already has field=%s", fs.Type, name) + } +} + +func (fs *fields) OmitEmpty(strct reflect.Value) []*field { + if !fs.hasOmitEmpty { + return fs.List + } + + fields := make([]*field, 0, len(fs.List)) + + for _, f := range fs.List { + if !f.Omit(strct) { + fields = append(fields, f) + } + } + + return fields +} + +func getFields(typ reflect.Type, useJSONTag bool) *fields { + fs := newFields(typ) + + var omitEmpty bool + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + + tagStr := f.Tag.Get("msgpack") + if useJSONTag && tagStr == "" { + tagStr = f.Tag.Get("json") + } + + tag := tagparser.Parse(tagStr) + if tag.Name == "-" { + continue + } + + if f.Name == "_msgpack" { + if tag.HasOption("asArray") { + fs.AsArray = true + } + if tag.HasOption("omitempty") { + omitEmpty = true + } + } + + if f.PkgPath != "" && !f.Anonymous { + continue + } + + field := &field{ + name: tag.Name, + index: f.Index, + omitEmpty: omitEmpty || tag.HasOption("omitempty"), + } + + if tag.HasOption("intern") { + switch f.Type.Kind() { + case reflect.Interface: + field.encoder = encodeInternInterfaceValue + field.decoder = decodeInternInterfaceValue + case reflect.String: + field.encoder = encodeInternStringValue + field.decoder = decodeInternStringValue + default: + err := fmt.Errorf("msgpack: intern strings are not supported on %s", f.Type) + panic(err) + } + } else { + field.encoder = getEncoder(f.Type) + field.decoder = getDecoder(f.Type) + } + + if field.name == "" { + field.name = f.Name + } + + if f.Anonymous && !tag.HasOption("noinline") { + inline := tag.HasOption("inline") + if inline { + inlineFields(fs, f.Type, field, useJSONTag) + } else { + inline = shouldInline(fs, f.Type, field, useJSONTag) + } + + if inline { + if _, ok := fs.Map[field.name]; ok { + log.Printf("msgpack: %s already has field=%s", fs.Type, field.name) + } + fs.Map[field.name] = field + continue + } + } + + fs.Add(field) + + if alias, ok := tag.Options["alias"]; ok { + fs.warnIfFieldExists(alias) + fs.Map[alias] = field + } + } + return fs +} + +var ( + encodeStructValuePtr uintptr + decodeStructValuePtr uintptr +) + +//nolint:gochecknoinits +func init() { + encodeStructValuePtr = reflect.ValueOf(encodeStructValue).Pointer() + decodeStructValuePtr = reflect.ValueOf(decodeStructValue).Pointer() +} + +func inlineFields(fs *fields, typ reflect.Type, f *field, useJSONTag bool) { + inlinedFields := getFields(typ, useJSONTag).List + for _, field := range inlinedFields { + if _, ok := fs.Map[field.name]; ok { + // Don't inline shadowed fields. + continue + } + field.index = append(f.index, field.index...) + fs.Add(field) + } +} + +func shouldInline(fs *fields, typ reflect.Type, f *field, useJSONTag bool) bool { + var encoder encoderFunc + var decoder decoderFunc + + if typ.Kind() == reflect.Struct { + encoder = f.encoder + decoder = f.decoder + } else { + for typ.Kind() == reflect.Ptr { + typ = typ.Elem() + encoder = getEncoder(typ) + decoder = getDecoder(typ) + } + if typ.Kind() != reflect.Struct { + return false + } + } + + if reflect.ValueOf(encoder).Pointer() != encodeStructValuePtr { + return false + } + if reflect.ValueOf(decoder).Pointer() != decodeStructValuePtr { + return false + } + + inlinedFields := getFields(typ, useJSONTag).List + for _, field := range inlinedFields { + if _, ok := fs.Map[field.name]; ok { + // Don't auto inline if there are shadowed fields. + return false + } + } + + for _, field := range inlinedFields { + field.index = append(f.index, field.index...) + fs.Add(field) + } + return true +} + +func isEmptyValue(v reflect.Value) bool { + switch v.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + return false +} + +func fieldByIndex(v reflect.Value, index []int) (_ reflect.Value, isNil bool) { + if len(index) == 1 { + return v.Field(index[0]), false + } + + for i, idx := range index { + if i > 0 { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + return v, true + } + v = v.Elem() + } + } + v = v.Field(idx) + } + + return v, false +} + +func fieldByIndexAlloc(v reflect.Value, index []int) reflect.Value { + if len(index) == 1 { + return v.Field(index[0]) + } + + for i, idx := range index { + if i > 0 { + var ok bool + v, ok = indirectNew(v) + if !ok { + return v + } + } + v = v.Field(idx) + } + + return v +} + +func indirectNew(v reflect.Value) (reflect.Value, bool) { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + if !v.CanSet() { + return v, false + } + elemType := v.Type().Elem() + if elemType.Kind() != reflect.Struct { + return v, false + } + v.Set(reflect.New(elemType)) + } + v = v.Elem() + } + return v, true +} diff --git a/vendor/github.com/vmihailenco/msgpack/v4/unsafe.go b/vendor/github.com/vmihailenco/msgpack/v4/unsafe.go new file mode 100644 index 000000000000..50c0da8b5be5 --- /dev/null +++ b/vendor/github.com/vmihailenco/msgpack/v4/unsafe.go @@ -0,0 +1,22 @@ +// +build !appengine + +package msgpack + +import ( + "unsafe" +) + +// bytesToString converts byte slice to string. +func bytesToString(b []byte) string { //nolint:deadcode,unused + return *(*string)(unsafe.Pointer(&b)) +} + +// stringToBytes converts string to byte slice. +func stringToBytes(s string) []byte { + return *(*[]byte)(unsafe.Pointer( + &struct { + string + Cap int + }{s, len(s)}, + )) +} diff --git a/vendor/github.com/vmihailenco/tagparser/.travis.yml b/vendor/github.com/vmihailenco/tagparser/.travis.yml new file mode 100644 index 000000000000..ec538452322c --- /dev/null +++ b/vendor/github.com/vmihailenco/tagparser/.travis.yml @@ -0,0 +1,24 @@ +dist: xenial +sudo: false +language: go + +go: + - 1.11.x + - 1.12.x + - tip + +matrix: + allow_failures: + - go: tip + +env: + - GO111MODULE=on + +go_import_path: github.com/vmihailenco/tagparser + +before_install: + - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.17.1 + +script: + - make + - golangci-lint run diff --git a/vendor/github.com/vmihailenco/tagparser/LICENSE b/vendor/github.com/vmihailenco/tagparser/LICENSE new file mode 100644 index 000000000000..3fc93fdff8c5 --- /dev/null +++ b/vendor/github.com/vmihailenco/tagparser/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2019 The github.com/vmihailenco/tagparser Authors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/vmihailenco/tagparser/Makefile b/vendor/github.com/vmihailenco/tagparser/Makefile new file mode 100644 index 000000000000..fe9dc5bdbafd --- /dev/null +++ b/vendor/github.com/vmihailenco/tagparser/Makefile @@ -0,0 +1,8 @@ +all: + go test ./... + go test ./... -short -race + go test ./... -run=NONE -bench=. -benchmem + env GOOS=linux GOARCH=386 go test ./... + go vet ./... + go get github.com/gordonklaus/ineffassign + ineffassign . diff --git a/vendor/github.com/vmihailenco/tagparser/README.md b/vendor/github.com/vmihailenco/tagparser/README.md new file mode 100644 index 000000000000..411aa5444dc5 --- /dev/null +++ b/vendor/github.com/vmihailenco/tagparser/README.md @@ -0,0 +1,24 @@ +# Opinionated Golang tag parser + +[![Build Status](https://travis-ci.org/vmihailenco/tagparser.png?branch=master)](https://travis-ci.org/vmihailenco/tagparser) +[![GoDoc](https://godoc.org/github.com/vmihailenco/tagparser?status.svg)](https://godoc.org/github.com/vmihailenco/tagparser) + +## Installation + +Install: + +```shell +go get -u github.com/vmihailenco/tagparser +``` + +## Quickstart + +```go +func ExampleParse() { + tag := tagparser.Parse("some_name,key:value,key2:'complex value'") + fmt.Println(tag.Name) + fmt.Println(tag.Options) + // Output: some_name + // map[key:value key2:'complex value'] +} +``` diff --git a/vendor/github.com/vmihailenco/tagparser/internal/parser/parser.go b/vendor/github.com/vmihailenco/tagparser/internal/parser/parser.go new file mode 100644 index 000000000000..2de1c6f7bde5 --- /dev/null +++ b/vendor/github.com/vmihailenco/tagparser/internal/parser/parser.go @@ -0,0 +1,82 @@ +package parser + +import ( + "bytes" + + "github.com/vmihailenco/tagparser/internal" +) + +type Parser struct { + b []byte + i int +} + +func New(b []byte) *Parser { + return &Parser{ + b: b, + } +} + +func NewString(s string) *Parser { + return New(internal.StringToBytes(s)) +} + +func (p *Parser) Bytes() []byte { + return p.b[p.i:] +} + +func (p *Parser) Valid() bool { + return p.i < len(p.b) +} + +func (p *Parser) Read() byte { + if p.Valid() { + c := p.b[p.i] + p.Advance() + return c + } + return 0 +} + +func (p *Parser) Peek() byte { + if p.Valid() { + return p.b[p.i] + } + return 0 +} + +func (p *Parser) Advance() { + p.i++ +} + +func (p *Parser) Skip(skip byte) bool { + if p.Peek() == skip { + p.Advance() + return true + } + return false +} + +func (p *Parser) SkipBytes(skip []byte) bool { + if len(skip) > len(p.b[p.i:]) { + return false + } + if !bytes.Equal(p.b[p.i:p.i+len(skip)], skip) { + return false + } + p.i += len(skip) + return true +} + +func (p *Parser) ReadSep(sep byte) ([]byte, bool) { + ind := bytes.IndexByte(p.b[p.i:], sep) + if ind == -1 { + b := p.b[p.i:] + p.i = len(p.b) + return b, false + } + + b := p.b[p.i : p.i+ind] + p.i += ind + 1 + return b, true +} diff --git a/vendor/github.com/vmihailenco/tagparser/internal/safe.go b/vendor/github.com/vmihailenco/tagparser/internal/safe.go new file mode 100644 index 000000000000..870fe541f0d1 --- /dev/null +++ b/vendor/github.com/vmihailenco/tagparser/internal/safe.go @@ -0,0 +1,11 @@ +// +build appengine + +package internal + +func BytesToString(b []byte) string { + return string(b) +} + +func StringToBytes(s string) []byte { + return []byte(s) +} diff --git a/vendor/github.com/vmihailenco/tagparser/internal/unsafe.go b/vendor/github.com/vmihailenco/tagparser/internal/unsafe.go new file mode 100644 index 000000000000..f8bc18d911ad --- /dev/null +++ b/vendor/github.com/vmihailenco/tagparser/internal/unsafe.go @@ -0,0 +1,22 @@ +// +build !appengine + +package internal + +import ( + "unsafe" +) + +// BytesToString converts byte slice to string. +func BytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} + +// StringToBytes converts string to byte slice. +func StringToBytes(s string) []byte { + return *(*[]byte)(unsafe.Pointer( + &struct { + string + Cap int + }{s, len(s)}, + )) +} diff --git a/vendor/github.com/vmihailenco/tagparser/tagparser.go b/vendor/github.com/vmihailenco/tagparser/tagparser.go new file mode 100644 index 000000000000..56b918011b0b --- /dev/null +++ b/vendor/github.com/vmihailenco/tagparser/tagparser.go @@ -0,0 +1,176 @@ +package tagparser + +import ( + "github.com/vmihailenco/tagparser/internal/parser" +) + +type Tag struct { + Name string + Options map[string]string +} + +func (t *Tag) HasOption(name string) bool { + _, ok := t.Options[name] + return ok +} + +func Parse(s string) *Tag { + p := &tagParser{ + Parser: parser.NewString(s), + } + p.parseKey() + return &p.Tag +} + +type tagParser struct { + *parser.Parser + + Tag Tag + hasName bool + key string +} + +func (p *tagParser) setTagOption(key, value string) { + if !p.hasName { + p.hasName = true + if key == "" { + p.Tag.Name = value + return + } + } + if p.Tag.Options == nil { + p.Tag.Options = make(map[string]string) + } + if key == "" { + p.Tag.Options[value] = "" + } else { + p.Tag.Options[key] = value + } +} + +func (p *tagParser) parseKey() { + p.key = "" + + var b []byte + for p.Valid() { + c := p.Read() + switch c { + case ',': + p.Skip(' ') + p.setTagOption("", string(b)) + p.parseKey() + return + case ':': + p.key = string(b) + p.parseValue() + return + case '\'': + p.parseQuotedValue() + return + default: + b = append(b, c) + } + } + + if len(b) > 0 { + p.setTagOption("", string(b)) + } +} + +func (p *tagParser) parseValue() { + const quote = '\'' + + c := p.Peek() + if c == quote { + p.Skip(quote) + p.parseQuotedValue() + return + } + + var b []byte + for p.Valid() { + c = p.Read() + switch c { + case '\\': + b = append(b, p.Read()) + case '(': + b = append(b, c) + b = p.readBrackets(b) + case ',': + p.Skip(' ') + p.setTagOption(p.key, string(b)) + p.parseKey() + return + default: + b = append(b, c) + } + } + p.setTagOption(p.key, string(b)) +} + +func (p *tagParser) readBrackets(b []byte) []byte { + var lvl int +loop: + for p.Valid() { + c := p.Read() + switch c { + case '\\': + b = append(b, p.Read()) + case '(': + b = append(b, c) + lvl++ + case ')': + b = append(b, c) + lvl-- + if lvl < 0 { + break loop + } + default: + b = append(b, c) + } + } + return b +} + +func (p *tagParser) parseQuotedValue() { + const quote = '\'' + + var b []byte + b = append(b, quote) + + for p.Valid() { + bb, ok := p.ReadSep(quote) + if !ok { + b = append(b, bb...) + break + } + + if len(bb) > 0 && bb[len(bb)-1] == '\\' { + b = append(b, bb[:len(bb)-1]...) + b = append(b, quote) + continue + } + + b = append(b, bb...) + b = append(b, quote) + break + } + + p.setTagOption(p.key, string(b)) + if p.Skip(',') { + p.Skip(' ') + } + p.parseKey() +} + +func Unquote(s string) (string, bool) { + const quote = '\'' + + if len(s) < 2 { + return s, false + } + if s[0] == quote && s[len(s)-1] == quote { + return s[1 : len(s)-1], true + } + return s, false +} diff --git a/vendor/github.com/zclconf/go-cty/cty/primitive_type.go b/vendor/github.com/zclconf/go-cty/cty/primitive_type.go index 7b3d1196cd01..603901732b10 100644 --- a/vendor/github.com/zclconf/go-cty/cty/primitive_type.go +++ b/vendor/github.com/zclconf/go-cty/cty/primitive_type.go @@ -52,6 +52,51 @@ func (t primitiveType) GoString() string { } } +// rawNumberEqual is our cty-specific definition of whether two big floats +// underlying cty.Number are "equal" for the purposes of the Value.Equals and +// Value.RawEquals methods. +// +// The built-in equality for big.Float is a direct comparison of the mantissa +// bits and the exponent, but that's too precise a check for cty because we +// routinely send numbers through decimal approximations and back and so +// we only promise to accurately represent the subset of binary floating point +// numbers that can be derived from a decimal string representation. +// +// In respect of the fact that cty only tries to preserve numbers that can +// reasonably be written in JSON documents, we use the string representation of +// a decimal approximation of the number as our comparison, relying on the +// big.Float type's heuristic for discarding extraneous mantissa bits that seem +// likely to only be there as a result of an earlier decimal-to-binary +// approximation during parsing, e.g. in ParseNumberVal. +func rawNumberEqual(a, b *big.Float) bool { + switch { + case (a == nil) != (b == nil): + return false + case a == nil: // b == nil too then, due to previous case + return true + default: + // This format and precision matches that used by cty/json.Marshal, + // and thus achieves our definition of "two numbers are equal if + // we'd use the same JSON serialization for both of them". + const format = 'f' + const prec = -1 + aStr := a.Text(format, prec) + bStr := b.Text(format, prec) + + // The one exception to our rule about equality-by-stringification is + // negative zero, because we want -0 to always be equal to +0. + const posZero = "0" + const negZero = "-0" + if aStr == negZero { + aStr = posZero + } + if bStr == negZero { + bStr = posZero + } + return aStr == bStr + } +} + // Number is the numeric type. Number values are arbitrary-precision // decimal numbers, which can then be converted into Go's various numeric // types only if they are in the appropriate range. diff --git a/vendor/github.com/zclconf/go-cty/cty/value_ops.go b/vendor/github.com/zclconf/go-cty/cty/value_ops.go index 55bebe0365a8..cdcc1506f01f 100644 --- a/vendor/github.com/zclconf/go-cty/cty/value_ops.go +++ b/vendor/github.com/zclconf/go-cty/cty/value_ops.go @@ -191,7 +191,7 @@ func (val Value) Equals(other Value) Value { switch { case ty == Number: - result = val.v.(*big.Float).Cmp(other.v.(*big.Float)) == 0 + result = rawNumberEqual(val.v.(*big.Float), other.v.(*big.Float)) case ty == Bool: result = val.v.(bool) == other.v.(bool) case ty == String: diff --git a/vendor/golang.org/x/crypto/ssh/certs.go b/vendor/golang.org/x/crypto/ssh/certs.go index a69e22491d37..4600c20772a5 100644 --- a/vendor/golang.org/x/crypto/ssh/certs.go +++ b/vendor/golang.org/x/crypto/ssh/certs.go @@ -460,6 +460,8 @@ func (c *Certificate) SignCert(rand io.Reader, authority Signer) error { // certKeyAlgoNames is a mapping from known certificate algorithm names to the // corresponding public key signature algorithm. +// +// This map must be kept in sync with the one in agent/client.go. var certKeyAlgoNames = map[string]string{ CertAlgoRSAv01: KeyAlgoRSA, CertAlgoRSASHA256v01: KeyAlgoRSASHA256, diff --git a/vendor/google.golang.org/grpc/CONTRIBUTING.md b/vendor/google.golang.org/grpc/CONTRIBUTING.md index cd03f8c76888..52338d004ce3 100644 --- a/vendor/google.golang.org/grpc/CONTRIBUTING.md +++ b/vendor/google.golang.org/grpc/CONTRIBUTING.md @@ -53,9 +53,8 @@ How to get your contributions merged smoothly and quickly. - **All tests need to be passing** before your change can be merged. We recommend you **run tests locally** before creating your PR to catch breakages early on. - - `make all` to test everything, OR - - `make vet` to catch vet errors - - `make test` to run the tests - - `make testrace` to run tests in race mode + - `VET_SKIP_PROTO=1 ./vet.sh` to catch vet errors + - `go test -cpu 1,4 -timeout 7m ./...` to run the tests + - `go test -race -cpu 1,4 -timeout 7m ./...` to run tests in race mode - Exceptions to the rules can be made if there's a compelling reason for doing so. diff --git a/vendor/google.golang.org/grpc/MAINTAINERS.md b/vendor/google.golang.org/grpc/MAINTAINERS.md index 093c82b3afe8..c6672c0a3efe 100644 --- a/vendor/google.golang.org/grpc/MAINTAINERS.md +++ b/vendor/google.golang.org/grpc/MAINTAINERS.md @@ -8,17 +8,18 @@ See [CONTRIBUTING.md](https://github.com/grpc/grpc-community/blob/master/CONTRIB for general contribution guidelines. ## Maintainers (in alphabetical order) -- [canguler](https://github.com/canguler), Google LLC + - [cesarghali](https://github.com/cesarghali), Google LLC - [dfawley](https://github.com/dfawley), Google LLC - [easwars](https://github.com/easwars), Google LLC -- [jadekler](https://github.com/jadekler), Google LLC - [menghanl](https://github.com/menghanl), Google LLC - [srini100](https://github.com/srini100), Google LLC ## Emeritus Maintainers (in alphabetical order) - [adelez](https://github.com/adelez), Google LLC +- [canguler](https://github.com/canguler), Google LLC - [iamqizhao](https://github.com/iamqizhao), Google LLC +- [jadekler](https://github.com/jadekler), Google LLC - [jtattermusch](https://github.com/jtattermusch), Google LLC - [lyuxuan](https://github.com/lyuxuan), Google LLC - [makmukhi](https://github.com/makmukhi), Google LLC diff --git a/vendor/google.golang.org/grpc/Makefile b/vendor/google.golang.org/grpc/Makefile index 1f0722f16243..1f8960922b3b 100644 --- a/vendor/google.golang.org/grpc/Makefile +++ b/vendor/google.golang.org/grpc/Makefile @@ -41,8 +41,6 @@ vetdeps: clean \ proto \ test \ - testappengine \ - testappenginedeps \ testrace \ vet \ vetdeps diff --git a/vendor/google.golang.org/grpc/NOTICE.txt b/vendor/google.golang.org/grpc/NOTICE.txt new file mode 100644 index 000000000000..530197749e9d --- /dev/null +++ b/vendor/google.golang.org/grpc/NOTICE.txt @@ -0,0 +1,13 @@ +Copyright 2014 gRPC 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. diff --git a/vendor/google.golang.org/grpc/attributes/attributes.go b/vendor/google.golang.org/grpc/attributes/attributes.go index 3220d87be403..ae13ddac14e0 100644 --- a/vendor/google.golang.org/grpc/attributes/attributes.go +++ b/vendor/google.golang.org/grpc/attributes/attributes.go @@ -25,55 +25,77 @@ // later release. package attributes -import "fmt" - // Attributes is an immutable struct for storing and retrieving generic // key/value pairs. Keys must be hashable, and users should define their own -// types for keys. +// types for keys. Values should not be modified after they are added to an +// Attributes or if they were received from one. If values implement 'Equal(o +// interface{}) bool', it will be called by (*Attributes).Equal to determine +// whether two values with the same key should be considered equal. type Attributes struct { m map[interface{}]interface{} } -// New returns a new Attributes containing all key/value pairs in kvs. If the -// same key appears multiple times, the last value overwrites all previous -// values for that key. Panics if len(kvs) is not even. -func New(kvs ...interface{}) *Attributes { - if len(kvs)%2 != 0 { - panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs))) - } - a := &Attributes{m: make(map[interface{}]interface{}, len(kvs)/2)} - for i := 0; i < len(kvs)/2; i++ { - a.m[kvs[i*2]] = kvs[i*2+1] - } - return a +// New returns a new Attributes containing the key/value pair. +func New(key, value interface{}) *Attributes { + return &Attributes{m: map[interface{}]interface{}{key: value}} } -// WithValues returns a new Attributes containing all key/value pairs in a and -// kvs. Panics if len(kvs) is not even. If the same key appears multiple -// times, the last value overwrites all previous values for that key. To -// remove an existing key, use a nil value. -func (a *Attributes) WithValues(kvs ...interface{}) *Attributes { +// WithValue returns a new Attributes containing the previous keys and values +// and the new key/value pair. If the same key appears multiple times, the +// last value overwrites all previous values for that key. To remove an +// existing key, use a nil value. value should not be modified later. +func (a *Attributes) WithValue(key, value interface{}) *Attributes { if a == nil { - return New(kvs...) + return New(key, value) } - if len(kvs)%2 != 0 { - panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs))) - } - n := &Attributes{m: make(map[interface{}]interface{}, len(a.m)+len(kvs)/2)} + n := &Attributes{m: make(map[interface{}]interface{}, len(a.m)+1)} for k, v := range a.m { n.m[k] = v } - for i := 0; i < len(kvs)/2; i++ { - n.m[kvs[i*2]] = kvs[i*2+1] - } + n.m[key] = value return n } // Value returns the value associated with these attributes for key, or nil if -// no value is associated with key. +// no value is associated with key. The returned value should not be modified. func (a *Attributes) Value(key interface{}) interface{} { if a == nil { return nil } return a.m[key] } + +// Equal returns whether a and o are equivalent. If 'Equal(o interface{}) +// bool' is implemented for a value in the attributes, it is called to +// determine if the value matches the one stored in the other attributes. If +// Equal is not implemented, standard equality is used to determine if the two +// values are equal. Note that some types (e.g. maps) aren't comparable by +// default, so they must be wrapped in a struct, or in an alias type, with Equal +// defined. +func (a *Attributes) Equal(o *Attributes) bool { + if a == nil && o == nil { + return true + } + if a == nil || o == nil { + return false + } + if len(a.m) != len(o.m) { + return false + } + for k, v := range a.m { + ov, ok := o.m[k] + if !ok { + // o missing element of a + return false + } + if eq, ok := v.(interface{ Equal(o interface{}) bool }); ok { + if !eq.Equal(ov) { + return false + } + } else if v != ov { + // Fallback to a standard equality check if Value is unimplemented. + return false + } + } + return true +} diff --git a/vendor/google.golang.org/grpc/balancer/balancer.go b/vendor/google.golang.org/grpc/balancer/balancer.go index ab531f4c0b80..f7a7697cad02 100644 --- a/vendor/google.golang.org/grpc/balancer/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/balancer.go @@ -27,6 +27,7 @@ import ( "net" "strings" + "google.golang.org/grpc/channelz" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal" @@ -75,24 +76,26 @@ func Get(name string) Builder { return nil } -// SubConn represents a gRPC sub connection. -// Each sub connection contains a list of addresses. gRPC will -// try to connect to them (in sequence), and stop trying the -// remainder once one connection is successful. +// A SubConn represents a single connection to a gRPC backend service. // -// The reconnect backoff will be applied on the list, not a single address. -// For example, try_on_all_addresses -> backoff -> try_on_all_addresses. +// Each SubConn contains a list of addresses. // -// All SubConns start in IDLE, and will not try to connect. To trigger -// the connecting, Balancers must call Connect. -// When the connection encounters an error, it will reconnect immediately. -// When the connection becomes IDLE, it will not reconnect unless Connect is -// called. +// All SubConns start in IDLE, and will not try to connect. To trigger the +// connecting, Balancers must call Connect. If a connection re-enters IDLE, +// Balancers must call Connect again to trigger a new connection attempt. // -// This interface is to be implemented by gRPC. Users should not need a -// brand new implementation of this interface. For the situations like -// testing, the new implementation should embed this interface. This allows -// gRPC to add new methods to this interface. +// gRPC will try to connect to the addresses in sequence, and stop trying the +// remainder once the first connection is successful. If an attempt to connect +// to all addresses encounters an error, the SubConn will enter +// TRANSIENT_FAILURE for a backoff period, and then transition to IDLE. +// +// Once established, if a connection is lost, the SubConn will transition +// directly to IDLE. +// +// This interface is to be implemented by gRPC. Users should not need their own +// implementation of this interface. For situations like testing, any +// implementations should embed this interface. This allows gRPC to add new +// methods to this interface. type SubConn interface { // UpdateAddresses updates the addresses used in this SubConn. // gRPC checks if currently-connected address is still in the new list. @@ -172,25 +175,32 @@ type ClientConn interface { // BuildOptions contains additional information for Build. type BuildOptions struct { - // DialCreds is the transport credential the Balancer implementation can - // use to dial to a remote load balancer server. The Balancer implementations - // can ignore this if it does not need to talk to another party securely. + // DialCreds is the transport credentials to use when communicating with a + // remote load balancer server. Balancer implementations which do not + // communicate with a remote load balancer server can ignore this field. DialCreds credentials.TransportCredentials - // CredsBundle is the credentials bundle that the Balancer can use. + // CredsBundle is the credentials bundle to use when communicating with a + // remote load balancer server. Balancer implementations which do not + // communicate with a remote load balancer server can ignore this field. CredsBundle credentials.Bundle - // Dialer is the custom dialer the Balancer implementation can use to dial - // to a remote load balancer server. The Balancer implementations - // can ignore this if it doesn't need to talk to remote balancer. + // Dialer is the custom dialer to use when communicating with a remote load + // balancer server. Balancer implementations which do not communicate with a + // remote load balancer server can ignore this field. Dialer func(context.Context, string) (net.Conn, error) - // ChannelzParentID is the entity parent's channelz unique identification number. - ChannelzParentID int64 + // Authority is the server name to use as part of the authentication + // handshake when communicating with a remote load balancer server. Balancer + // implementations which do not communicate with a remote load balancer + // server can ignore this field. + Authority string + // ChannelzParentID is the parent ClientConn's channelz ID. + ChannelzParentID *channelz.Identifier // CustomUserAgent is the custom user agent set on the parent ClientConn. // The balancer should set the same custom user agent if it creates a // ClientConn. CustomUserAgent string - // Target contains the parsed address info of the dial target. It is the same resolver.Target as - // passed to the resolver. - // See the documentation for the resolver.Target type for details about what it contains. + // Target contains the parsed address info of the dial target. It is the + // same resolver.Target as passed to the resolver. See the documentation for + // the resolver.Target type for details about what it contains. Target resolver.Target } @@ -326,6 +336,20 @@ type Balancer interface { Close() } +// ExitIdler is an optional interface for balancers to implement. If +// implemented, ExitIdle will be called when ClientConn.Connect is called, if +// the ClientConn is idle. If unimplemented, ClientConn.Connect will cause +// all SubConns to connect. +// +// Notice: it will be required for all balancers to implement this in a future +// release. +type ExitIdler interface { + // ExitIdle instructs the LB policy to reconnect to backends / exit the + // IDLE state, if appropriate and possible. Note that SubConns that enter + // the IDLE state will not reconnect until SubConn.Connect is called. + ExitIdle() +} + // SubConnState describes the state of a SubConn. type SubConnState struct { // ConnectivityState is the connectivity state of the SubConn. @@ -353,8 +377,10 @@ var ErrBadResolverState = errors.New("bad resolver state") // // It's not thread safe. type ConnectivityStateEvaluator struct { - numReady uint64 // Number of addrConns in ready state. - numConnecting uint64 // Number of addrConns in connecting state. + numReady uint64 // Number of addrConns in ready state. + numConnecting uint64 // Number of addrConns in connecting state. + numTransientFailure uint64 // Number of addrConns in transient failure state. + numIdle uint64 // Number of addrConns in idle state. } // RecordTransition records state change happening in subConn and based on that @@ -362,9 +388,11 @@ type ConnectivityStateEvaluator struct { // // - If at least one SubConn in Ready, the aggregated state is Ready; // - Else if at least one SubConn in Connecting, the aggregated state is Connecting; -// - Else the aggregated state is TransientFailure. +// - Else if at least one SubConn is TransientFailure, the aggregated state is Transient Failure; +// - Else if at least one SubConn is Idle, the aggregated state is Idle; +// - Else there are no subconns and the aggregated state is Transient Failure // -// Idle and Shutdown are not considered. +// Shutdown is not considered. func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State { // Update counters. for idx, state := range []connectivity.State{oldState, newState} { @@ -374,6 +402,10 @@ func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState conne cse.numReady += updateVal case connectivity.Connecting: cse.numConnecting += updateVal + case connectivity.TransientFailure: + cse.numTransientFailure += updateVal + case connectivity.Idle: + cse.numIdle += updateVal } } @@ -384,5 +416,11 @@ func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState conne if cse.numConnecting > 0 { return connectivity.Connecting } + if cse.numTransientFailure > 0 { + return connectivity.TransientFailure + } + if cse.numIdle > 0 { + return connectivity.Idle + } return connectivity.TransientFailure } diff --git a/vendor/google.golang.org/grpc/balancer/base/balancer.go b/vendor/google.golang.org/grpc/balancer/base/balancer.go index c883efa0bbf5..a67074a3ad06 100644 --- a/vendor/google.golang.org/grpc/balancer/base/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/base/balancer.go @@ -22,7 +22,6 @@ import ( "errors" "fmt" - "google.golang.org/grpc/attributes" "google.golang.org/grpc/balancer" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/grpclog" @@ -42,7 +41,7 @@ func (bb *baseBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) cc: cc, pickerBuilder: bb.pickerBuilder, - subConns: make(map[resolver.Address]subConnInfo), + subConns: resolver.NewAddressMap(), scStates: make(map[balancer.SubConn]connectivity.State), csEvltr: &balancer.ConnectivityStateEvaluator{}, config: bb.config, @@ -58,11 +57,6 @@ func (bb *baseBuilder) Name() string { return bb.name } -type subConnInfo struct { - subConn balancer.SubConn - attrs *attributes.Attributes -} - type baseBalancer struct { cc balancer.ClientConn pickerBuilder PickerBuilder @@ -70,7 +64,7 @@ type baseBalancer struct { csEvltr *balancer.ConnectivityStateEvaluator state connectivity.State - subConns map[resolver.Address]subConnInfo // `attributes` is stripped from the keys of this map (the addresses) + subConns *resolver.AddressMap scStates map[balancer.SubConn]connectivity.State picker balancer.Picker config Config @@ -81,7 +75,7 @@ type baseBalancer struct { func (b *baseBalancer) ResolverError(err error) { b.resolverErr = err - if len(b.subConns) == 0 { + if b.subConns.Len() == 0 { b.state = connectivity.TransientFailure } @@ -105,52 +99,29 @@ func (b *baseBalancer) UpdateClientConnState(s balancer.ClientConnState) error { // Successful resolution; clear resolver error and ensure we return nil. b.resolverErr = nil // addrsSet is the set converted from addrs, it's used for quick lookup of an address. - addrsSet := make(map[resolver.Address]struct{}) + addrsSet := resolver.NewAddressMap() for _, a := range s.ResolverState.Addresses { - // Strip attributes from addresses before using them as map keys. So - // that when two addresses only differ in attributes pointers (but with - // the same attribute content), they are considered the same address. - // - // Note that this doesn't handle the case where the attribute content is - // different. So if users want to set different attributes to create - // duplicate connections to the same backend, it doesn't work. This is - // fine for now, because duplicate is done by setting Metadata today. - // - // TODO: read attributes to handle duplicate connections. - aNoAttrs := a - aNoAttrs.Attributes = nil - addrsSet[aNoAttrs] = struct{}{} - if scInfo, ok := b.subConns[aNoAttrs]; !ok { + addrsSet.Set(a, nil) + if _, ok := b.subConns.Get(a); !ok { // a is a new address (not existing in b.subConns). - // - // When creating SubConn, the original address with attributes is - // passed through. So that connection configurations in attributes - // (like creds) will be used. sc, err := b.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{HealthCheckEnabled: b.config.HealthCheck}) if err != nil { logger.Warningf("base.baseBalancer: failed to create new SubConn: %v", err) continue } - b.subConns[aNoAttrs] = subConnInfo{subConn: sc, attrs: a.Attributes} + b.subConns.Set(a, sc) b.scStates[sc] = connectivity.Idle + b.csEvltr.RecordTransition(connectivity.Shutdown, connectivity.Idle) sc.Connect() - } else { - // Always update the subconn's address in case the attributes - // changed. - // - // The SubConn does a reflect.DeepEqual of the new and old - // addresses. So this is a noop if the current address is the same - // as the old one (including attributes). - scInfo.attrs = a.Attributes - b.subConns[aNoAttrs] = scInfo - b.cc.UpdateAddresses(scInfo.subConn, []resolver.Address{a}) } } - for a, scInfo := range b.subConns { + for _, a := range b.subConns.Keys() { + sci, _ := b.subConns.Get(a) + sc := sci.(balancer.SubConn) // a was removed by resolver. - if _, ok := addrsSet[a]; !ok { - b.cc.RemoveSubConn(scInfo.subConn) - delete(b.subConns, a) + if _, ok := addrsSet.Get(a); !ok { + b.cc.RemoveSubConn(sc) + b.subConns.Delete(a) // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. // The entry will be deleted in UpdateSubConnState. } @@ -192,10 +163,11 @@ func (b *baseBalancer) regeneratePicker() { readySCs := make(map[balancer.SubConn]SubConnInfo) // Filter out all ready SCs from full subConn map. - for addr, scInfo := range b.subConns { - if st, ok := b.scStates[scInfo.subConn]; ok && st == connectivity.Ready { - addr.Attributes = scInfo.attrs - readySCs[scInfo.subConn] = SubConnInfo{Address: addr} + for _, addr := range b.subConns.Keys() { + sci, _ := b.subConns.Get(addr) + sc := sci.(balancer.SubConn) + if st, ok := b.scStates[sc]; ok && st == connectivity.Ready { + readySCs[sc] = SubConnInfo{Address: addr} } } b.picker = b.pickerBuilder.Build(PickerBuildInfo{ReadySCs: readySCs}) @@ -213,10 +185,14 @@ func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.Su } return } - if oldS == connectivity.TransientFailure && s == connectivity.Connecting { - // Once a subconn enters TRANSIENT_FAILURE, ignore subsequent + if oldS == connectivity.TransientFailure && + (s == connectivity.Connecting || s == connectivity.Idle) { + // Once a subconn enters TRANSIENT_FAILURE, ignore subsequent IDLE or // CONNECTING transitions to prevent the aggregated state from being // always CONNECTING when many backends exist but are all down. + if s == connectivity.Idle { + sc.Connect() + } return } b.scStates[sc] = s @@ -242,7 +218,6 @@ func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.Su b.state == connectivity.TransientFailure { b.regeneratePicker() } - b.cc.UpdateState(balancer.State{ConnectivityState: b.state, Picker: b.picker}) } @@ -251,6 +226,11 @@ func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.Su func (b *baseBalancer) Close() { } +// ExitIdle is a nop because the base balancer attempts to stay connected to +// all SubConns at all times. +func (b *baseBalancer) ExitIdle() { +} + // NewErrPicker returns a Picker that always returns err on Pick(). func NewErrPicker(err error) balancer.Picker { return &errPicker{err: err} diff --git a/vendor/google.golang.org/grpc/balancer/grpclb/state/state.go b/vendor/google.golang.org/grpc/balancer/grpclb/state/state.go index a24264a34f5f..4ecfa1c21511 100644 --- a/vendor/google.golang.org/grpc/balancer/grpclb/state/state.go +++ b/vendor/google.golang.org/grpc/balancer/grpclb/state/state.go @@ -39,7 +39,7 @@ type State struct { // Set returns a copy of the provided state with attributes containing s. s's // data should not be mutated after calling Set. func Set(state resolver.State, s *State) resolver.State { - state.Attributes = state.Attributes.WithValues(key, s) + state.Attributes = state.Attributes.WithValue(key, s) return state } diff --git a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go index 43c2a15373a1..274eb2f85802 100644 --- a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go +++ b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go @@ -47,11 +47,11 @@ func init() { type rrPickerBuilder struct{} func (*rrPickerBuilder) Build(info base.PickerBuildInfo) balancer.Picker { - logger.Infof("roundrobinPicker: newPicker called with info: %v", info) + logger.Infof("roundrobinPicker: Build called with info: %v", info) if len(info.ReadySCs) == 0 { return base.NewErrPicker(balancer.ErrNoSubConnAvailable) } - var scs []balancer.SubConn + scs := make([]balancer.SubConn, 0, len(info.ReadySCs)) for sc := range info.ReadySCs { scs = append(scs, sc) } diff --git a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go index dd8397963974..b1c23eaae0db 100644 --- a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go +++ b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go @@ -20,105 +20,178 @@ package grpc import ( "fmt" + "strings" "sync" "google.golang.org/grpc/balancer" "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/internal/balancer/gracefulswitch" "google.golang.org/grpc/internal/buffer" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/resolver" ) -// scStateUpdate contains the subConn and the new state it changed to. -type scStateUpdate struct { - sc balancer.SubConn - state connectivity.State - err error -} - -// ccBalancerWrapper is a wrapper on top of cc for balancers. -// It implements balancer.ClientConn interface. +// ccBalancerWrapper sits between the ClientConn and the Balancer. +// +// ccBalancerWrapper implements methods corresponding to the ones on the +// balancer.Balancer interface. The ClientConn is free to call these methods +// concurrently and the ccBalancerWrapper ensures that calls from the ClientConn +// to the Balancer happen synchronously and in order. +// +// ccBalancerWrapper also implements the balancer.ClientConn interface and is +// passed to the Balancer implementations. It invokes unexported methods on the +// ClientConn to handle these calls from the Balancer. +// +// It uses the gracefulswitch.Balancer internally to ensure that balancer +// switches happen in a graceful manner. type ccBalancerWrapper struct { - cc *ClientConn - balancerMu sync.Mutex // synchronizes calls to the balancer - balancer balancer.Balancer - updateCh *buffer.Unbounded - closed *grpcsync.Event - done *grpcsync.Event - - mu sync.Mutex - subConns map[*acBalancerWrapper]struct{} + cc *ClientConn + + // Since these fields are accessed only from handleXxx() methods which are + // synchronized by the watcher goroutine, we do not need a mutex to protect + // these fields. + balancer *gracefulswitch.Balancer + curBalancerName string + + updateCh *buffer.Unbounded // Updates written on this channel are processed by watcher(). + resultCh *buffer.Unbounded // Results of calls to UpdateClientConnState() are pushed here. + closed *grpcsync.Event // Indicates if close has been called. + done *grpcsync.Event // Indicates if close has completed its work. } -func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.BuildOptions) *ccBalancerWrapper { +// newCCBalancerWrapper creates a new balancer wrapper. The underlying balancer +// is not created until the switchTo() method is invoked. +func newCCBalancerWrapper(cc *ClientConn, bopts balancer.BuildOptions) *ccBalancerWrapper { ccb := &ccBalancerWrapper{ cc: cc, updateCh: buffer.NewUnbounded(), + resultCh: buffer.NewUnbounded(), closed: grpcsync.NewEvent(), done: grpcsync.NewEvent(), - subConns: make(map[*acBalancerWrapper]struct{}), } go ccb.watcher() - ccb.balancer = b.Build(ccb, bopts) + ccb.balancer = gracefulswitch.NewBalancer(ccb, bopts) return ccb } -// watcher balancer functions sequentially, so the balancer can be implemented -// lock-free. +// The following xxxUpdate structs wrap the arguments received as part of the +// corresponding update. The watcher goroutine uses the 'type' of the update to +// invoke the appropriate handler routine to handle the update. + +type ccStateUpdate struct { + ccs *balancer.ClientConnState +} + +type scStateUpdate struct { + sc balancer.SubConn + state connectivity.State + err error +} + +type exitIdleUpdate struct{} + +type resolverErrorUpdate struct { + err error +} + +type switchToUpdate struct { + name string +} + +type subConnUpdate struct { + acbw *acBalancerWrapper +} + +// watcher is a long-running goroutine which reads updates from a channel and +// invokes corresponding methods on the underlying balancer. It ensures that +// these methods are invoked in a synchronous fashion. It also ensures that +// these methods are invoked in the order in which the updates were received. func (ccb *ccBalancerWrapper) watcher() { for { select { - case t := <-ccb.updateCh.Get(): + case u := <-ccb.updateCh.Get(): ccb.updateCh.Load() if ccb.closed.HasFired() { break } - switch u := t.(type) { + switch update := u.(type) { + case *ccStateUpdate: + ccb.handleClientConnStateChange(update.ccs) case *scStateUpdate: - ccb.balancerMu.Lock() - ccb.balancer.UpdateSubConnState(u.sc, balancer.SubConnState{ConnectivityState: u.state, ConnectionError: u.err}) - ccb.balancerMu.Unlock() - case *acBalancerWrapper: - ccb.mu.Lock() - if ccb.subConns != nil { - delete(ccb.subConns, u) - ccb.cc.removeAddrConn(u.getAddrConn(), errConnDrain) - } - ccb.mu.Unlock() + ccb.handleSubConnStateChange(update) + case *exitIdleUpdate: + ccb.handleExitIdle() + case *resolverErrorUpdate: + ccb.handleResolverError(update.err) + case *switchToUpdate: + ccb.handleSwitchTo(update.name) + case *subConnUpdate: + ccb.handleRemoveSubConn(update.acbw) default: - logger.Errorf("ccBalancerWrapper.watcher: unknown update %+v, type %T", t, t) + logger.Errorf("ccBalancerWrapper.watcher: unknown update %+v, type %T", update, update) } case <-ccb.closed.Done(): } if ccb.closed.HasFired() { - ccb.balancerMu.Lock() - ccb.balancer.Close() - ccb.balancerMu.Unlock() - ccb.mu.Lock() - scs := ccb.subConns - ccb.subConns = nil - ccb.mu.Unlock() - ccb.UpdateState(balancer.State{ConnectivityState: connectivity.Connecting, Picker: nil}) - ccb.done.Fire() - // Fire done before removing the addr conns. We can safely unblock - // ccb.close and allow the removeAddrConns to happen - // asynchronously. - for acbw := range scs { - ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) - } + ccb.handleClose() return } } } -func (ccb *ccBalancerWrapper) close() { - ccb.closed.Fire() - <-ccb.done.Done() +// updateClientConnState is invoked by grpc to push a ClientConnState update to +// the underlying balancer. +// +// Unlike other methods invoked by grpc to push updates to the underlying +// balancer, this method cannot simply push the update onto the update channel +// and return. It needs to return the error returned by the underlying balancer +// back to grpc which propagates that to the resolver. +func (ccb *ccBalancerWrapper) updateClientConnState(ccs *balancer.ClientConnState) error { + ccb.updateCh.Put(&ccStateUpdate{ccs: ccs}) + + var res interface{} + select { + case res = <-ccb.resultCh.Get(): + ccb.resultCh.Load() + case <-ccb.closed.Done(): + // Return early if the balancer wrapper is closed while we are waiting for + // the underlying balancer to process a ClientConnState update. + return nil + } + // If the returned error is nil, attempting to type assert to error leads to + // panic. So, this needs to handled separately. + if res == nil { + return nil + } + return res.(error) +} + +// handleClientConnStateChange handles a ClientConnState update from the update +// channel and invokes the appropriate method on the underlying balancer. +// +// If the addresses specified in the update contain addresses of type "grpclb" +// and the selected LB policy is not "grpclb", these addresses will be filtered +// out and ccs will be modified with the updated address list. +func (ccb *ccBalancerWrapper) handleClientConnStateChange(ccs *balancer.ClientConnState) { + if ccb.curBalancerName != grpclbName { + // Filter any grpclb addresses since we don't have the grpclb balancer. + var addrs []resolver.Address + for _, addr := range ccs.ResolverState.Addresses { + if addr.Type == resolver.GRPCLB { + continue + } + addrs = append(addrs, addr) + } + ccs.ResolverState.Addresses = addrs + } + ccb.resultCh.Put(ccb.balancer.UpdateClientConnState(*ccs)) } -func (ccb *ccBalancerWrapper) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State, err error) { +// updateSubConnState is invoked by grpc to push a subConn state update to the +// underlying balancer. +func (ccb *ccBalancerWrapper) updateSubConnState(sc balancer.SubConn, s connectivity.State, err error) { // When updating addresses for a SubConn, if the address in use is not in // the new addresses, the old ac will be tearDown() and a new ac will be // created. tearDown() generates a state change with Shutdown state, we @@ -136,44 +209,125 @@ func (ccb *ccBalancerWrapper) handleSubConnStateChange(sc balancer.SubConn, s co }) } -func (ccb *ccBalancerWrapper) updateClientConnState(ccs *balancer.ClientConnState) error { - ccb.balancerMu.Lock() - defer ccb.balancerMu.Unlock() - return ccb.balancer.UpdateClientConnState(*ccs) +// handleSubConnStateChange handles a SubConnState update from the update +// channel and invokes the appropriate method on the underlying balancer. +func (ccb *ccBalancerWrapper) handleSubConnStateChange(update *scStateUpdate) { + ccb.balancer.UpdateSubConnState(update.sc, balancer.SubConnState{ConnectivityState: update.state, ConnectionError: update.err}) +} + +func (ccb *ccBalancerWrapper) exitIdle() { + ccb.updateCh.Put(&exitIdleUpdate{}) +} + +func (ccb *ccBalancerWrapper) handleExitIdle() { + if ccb.cc.GetState() != connectivity.Idle { + return + } + ccb.balancer.ExitIdle() } func (ccb *ccBalancerWrapper) resolverError(err error) { - ccb.balancerMu.Lock() + ccb.updateCh.Put(&resolverErrorUpdate{err: err}) +} + +func (ccb *ccBalancerWrapper) handleResolverError(err error) { ccb.balancer.ResolverError(err) - ccb.balancerMu.Unlock() +} + +// switchTo is invoked by grpc to instruct the balancer wrapper to switch to the +// LB policy identified by name. +// +// ClientConn calls newCCBalancerWrapper() at creation time. Upon receipt of the +// first good update from the name resolver, it determines the LB policy to use +// and invokes the switchTo() method. Upon receipt of every subsequent update +// from the name resolver, it invokes this method. +// +// the ccBalancerWrapper keeps track of the current LB policy name, and skips +// the graceful balancer switching process if the name does not change. +func (ccb *ccBalancerWrapper) switchTo(name string) { + ccb.updateCh.Put(&switchToUpdate{name: name}) +} + +// handleSwitchTo handles a balancer switch update from the update channel. It +// calls the SwitchTo() method on the gracefulswitch.Balancer with a +// balancer.Builder corresponding to name. If no balancer.Builder is registered +// for the given name, it uses the default LB policy which is "pick_first". +func (ccb *ccBalancerWrapper) handleSwitchTo(name string) { + // TODO: Other languages use case-insensitive balancer registries. We should + // switch as well. See: https://github.com/grpc/grpc-go/issues/5288. + if strings.EqualFold(ccb.curBalancerName, name) { + return + } + + // TODO: Ensure that name is a registered LB policy when we get here. + // We currently only validate the `loadBalancingConfig` field. We need to do + // the same for the `loadBalancingPolicy` field and reject the service config + // if the specified policy is not registered. + builder := balancer.Get(name) + if builder == nil { + channelz.Warningf(logger, ccb.cc.channelzID, "Channel switches to new LB policy %q, since the specified LB policy %q was not registered", PickFirstBalancerName, name) + builder = newPickfirstBuilder() + } else { + channelz.Infof(logger, ccb.cc.channelzID, "Channel switches to new LB policy %q", name) + } + + if err := ccb.balancer.SwitchTo(builder); err != nil { + channelz.Errorf(logger, ccb.cc.channelzID, "Channel failed to build new LB policy %q: %v", name, err) + return + } + ccb.curBalancerName = builder.Name() +} + +// handleRemoveSucConn handles a request from the underlying balancer to remove +// a subConn. +// +// See comments in RemoveSubConn() for more details. +func (ccb *ccBalancerWrapper) handleRemoveSubConn(acbw *acBalancerWrapper) { + ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) +} + +func (ccb *ccBalancerWrapper) close() { + ccb.closed.Fire() + <-ccb.done.Done() +} + +func (ccb *ccBalancerWrapper) handleClose() { + ccb.balancer.Close() + ccb.done.Fire() } func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { if len(addrs) <= 0 { return nil, fmt.Errorf("grpc: cannot create SubConn with empty address list") } - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return nil, fmt.Errorf("grpc: ClientConn balancer wrapper was closed") - } ac, err := ccb.cc.newAddrConn(addrs, opts) if err != nil { + channelz.Warningf(logger, ccb.cc.channelzID, "acBalancerWrapper: NewSubConn: failed to newAddrConn: %v", err) return nil, err } acbw := &acBalancerWrapper{ac: ac} acbw.ac.mu.Lock() ac.acbw = acbw acbw.ac.mu.Unlock() - ccb.subConns[acbw] = struct{}{} return acbw, nil } func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) { - // The RemoveSubConn() is handled in the run() goroutine, to avoid deadlock - // during switchBalancer() if the old balancer calls RemoveSubConn() in its - // Close(). - ccb.updateCh.Put(sc) + // Before we switched the ccBalancerWrapper to use gracefulswitch.Balancer, it + // was required to handle the RemoveSubConn() method asynchronously by pushing + // the update onto the update channel. This was done to avoid a deadlock as + // switchBalancer() was holding cc.mu when calling Close() on the old + // balancer, which would in turn call RemoveSubConn(). + // + // With the use of gracefulswitch.Balancer in ccBalancerWrapper, handling this + // asynchronously is probably not required anymore since the switchTo() method + // handles the balancer switch by pushing the update onto the channel. + // TODO(easwars): Handle this inline. + acbw, ok := sc.(*acBalancerWrapper) + if !ok { + return + } + ccb.updateCh.Put(&subConnUpdate{acbw: acbw}) } func (ccb *ccBalancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) { @@ -185,11 +339,6 @@ func (ccb *ccBalancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resol } func (ccb *ccBalancerWrapper) UpdateState(s balancer.State) { - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return - } // Update picker before updating state. Even though the ordering here does // not matter, it can lead to multiple calls of Pick in the common start-up // case where we wait for ready and then perform an RPC. If the picker is @@ -239,17 +388,17 @@ func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { return } - ac, err := cc.newAddrConn(addrs, opts) + newAC, err := cc.newAddrConn(addrs, opts) if err != nil { channelz.Warningf(logger, acbw.ac.channelzID, "acBalancerWrapper: UpdateAddresses: failed to newAddrConn: %v", err) return } - acbw.ac = ac - ac.mu.Lock() - ac.acbw = acbw - ac.mu.Unlock() + acbw.ac = newAC + newAC.mu.Lock() + newAC.acbw = acbw + newAC.mu.Unlock() if acState != connectivity.Idle { - ac.connect() + go newAC.connect() } } } @@ -257,7 +406,7 @@ func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { func (acbw *acBalancerWrapper) Connect() { acbw.mu.Lock() defer acbw.mu.Unlock() - acbw.ac.connect() + go acbw.ac.connect() } func (acbw *acBalancerWrapper) getAddrConn() *addrConn { diff --git a/vendor/google.golang.org/grpc/channelz/channelz.go b/vendor/google.golang.org/grpc/channelz/channelz.go new file mode 100644 index 000000000000..a220c47c59a5 --- /dev/null +++ b/vendor/google.golang.org/grpc/channelz/channelz.go @@ -0,0 +1,36 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package channelz exports internals of the channelz implementation as required +// by other gRPC packages. +// +// The implementation of the channelz spec as defined in +// https://github.com/grpc/proposal/blob/master/A14-channelz.md, is provided by +// the `internal/channelz` package. +// +// Experimental +// +// Notice: All APIs in this package are experimental and may be removed in a +// later release. +package channelz + +import "google.golang.org/grpc/internal/channelz" + +// Identifier is an opaque identifier which uniquely identifies an entity in the +// channelz database. +type Identifier = channelz.Identifier diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index 5cef39295bdc..de6d41c23841 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -23,6 +23,7 @@ import ( "errors" "fmt" "math" + "net/url" "reflect" "strings" "sync" @@ -37,7 +38,6 @@ import ( "google.golang.org/grpc/internal/backoff" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" - "google.golang.org/grpc/internal/grpcutil" iresolver "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/keepalive" @@ -79,17 +79,17 @@ var ( // errNoTransportSecurity indicates that there is no transport security // being set for ClientConn. Users should either set one or explicitly // call WithInsecure DialOption to disable security. - errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)") + errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithTransportCredentials(insecure.NewCredentials()) explicitly or set credentials)") // errTransportCredsAndBundle indicates that creds bundle is used together // with other individual Transport Credentials. errTransportCredsAndBundle = errors.New("grpc: credentials.Bundle may not be used with individual TransportCredentials") - // errTransportCredentialsMissing indicates that users want to transmit security - // information (e.g., OAuth2 token) which requires secure connection on an insecure - // connection. + // errNoTransportCredsInBundle indicated that the configured creds bundle + // returned a transport credentials which was nil. + errNoTransportCredsInBundle = errors.New("grpc: credentials.Bundle must return non-nil transport credentials") + // errTransportCredentialsMissing indicates that users want to transmit + // security information (e.g., OAuth2 token) which requires secure + // connection on an insecure connection. errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)") - // errCredentialsConflict indicates that grpc.WithTransportCredentials() - // and grpc.WithInsecure() are both called for a connection. - errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)") ) const ( @@ -159,35 +159,35 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * } }() - if channelz.IsOn() { - if cc.dopts.channelzParentID != 0 { - cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, cc.dopts.channelzParentID, target) - channelz.AddTraceEvent(logger, cc.channelzID, 0, &channelz.TraceEventDesc{ - Desc: "Channel Created", - Severity: channelz.CtInfo, - Parent: &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Nested Channel(id:%d) created", cc.channelzID), - Severity: channelz.CtInfo, - }, - }) - } else { - cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, 0, target) - channelz.Info(logger, cc.channelzID, "Channel Created") + pid := cc.dopts.channelzParentID + cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, pid, target) + ted := &channelz.TraceEventDesc{ + Desc: "Channel created", + Severity: channelz.CtInfo, + } + if cc.dopts.channelzParentID != nil { + ted.Parent = &channelz.TraceEventDesc{ + Desc: fmt.Sprintf("Nested Channel(id:%d) created", cc.channelzID.Int()), + Severity: channelz.CtInfo, } - cc.csMgr.channelzID = cc.channelzID } + channelz.AddTraceEvent(logger, cc.channelzID, 1, ted) + cc.csMgr.channelzID = cc.channelzID - if !cc.dopts.insecure { - if cc.dopts.copts.TransportCredentials == nil && cc.dopts.copts.CredsBundle == nil { - return nil, errNoTransportSecurity - } - if cc.dopts.copts.TransportCredentials != nil && cc.dopts.copts.CredsBundle != nil { - return nil, errTransportCredsAndBundle - } - } else { - if cc.dopts.copts.TransportCredentials != nil || cc.dopts.copts.CredsBundle != nil { - return nil, errCredentialsConflict - } + if cc.dopts.copts.TransportCredentials == nil && cc.dopts.copts.CredsBundle == nil { + return nil, errNoTransportSecurity + } + if cc.dopts.copts.TransportCredentials != nil && cc.dopts.copts.CredsBundle != nil { + return nil, errTransportCredsAndBundle + } + if cc.dopts.copts.CredsBundle != nil && cc.dopts.copts.CredsBundle.TransportCredentials() == nil { + return nil, errNoTransportCredsInBundle + } + transportCreds := cc.dopts.copts.TransportCredentials + if transportCreds == nil { + transportCreds = cc.dopts.copts.CredsBundle.TransportCredentials() + } + if transportCreds.Info().SecurityProtocol == "insecure" { for _, cd := range cc.dopts.copts.PerRPCCredentials { if cd.RequireTransportSecurity() { return nil, errTransportCredentialsMissing @@ -248,38 +248,15 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * } // Determine the resolver to use. - cc.parsedTarget = grpcutil.ParseTarget(cc.target, cc.dopts.copts.Dialer != nil) - channelz.Infof(logger, cc.channelzID, "parsed scheme: %q", cc.parsedTarget.Scheme) - resolverBuilder := cc.getResolver(cc.parsedTarget.Scheme) - if resolverBuilder == nil { - // If resolver builder is still nil, the parsed target's scheme is - // not registered. Fallback to default resolver and set Endpoint to - // the original target. - channelz.Infof(logger, cc.channelzID, "scheme %q not registered, fallback to default scheme", cc.parsedTarget.Scheme) - cc.parsedTarget = resolver.Target{ - Scheme: resolver.GetDefaultScheme(), - Endpoint: target, - } - resolverBuilder = cc.getResolver(cc.parsedTarget.Scheme) - if resolverBuilder == nil { - return nil, fmt.Errorf("could not get resolver for default scheme: %q", cc.parsedTarget.Scheme) - } + resolverBuilder, err := cc.parseTargetAndFindResolver() + if err != nil { + return nil, err } - - creds := cc.dopts.copts.TransportCredentials - if creds != nil && creds.Info().ServerName != "" { - cc.authority = creds.Info().ServerName - } else if cc.dopts.insecure && cc.dopts.authority != "" { - cc.authority = cc.dopts.authority - } else if strings.HasPrefix(cc.target, "unix:") || strings.HasPrefix(cc.target, "unix-abstract:") { - cc.authority = "localhost" - } else if strings.HasPrefix(cc.parsedTarget.Endpoint, ":") { - cc.authority = "localhost" + cc.parsedTarget.Endpoint - } else { - // Use endpoint from "scheme://authority/endpoint" as the default - // authority for ClientConn. - cc.authority = cc.parsedTarget.Endpoint + cc.authority, err = determineAuthority(cc.parsedTarget.Endpoint, cc.target, cc.dopts) + if err != nil { + return nil, err } + channelz.Infof(logger, cc.channelzID, "Channel authority set to %q", cc.authority) if cc.dopts.scChan != nil && !scSet { // Blocking wait for the initial service config. @@ -301,14 +278,15 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * if creds := cc.dopts.copts.TransportCredentials; creds != nil { credsClone = creds.Clone() } - cc.balancerBuildOpts = balancer.BuildOptions{ + cc.balancerWrapper = newCCBalancerWrapper(cc, balancer.BuildOptions{ DialCreds: credsClone, CredsBundle: cc.dopts.copts.CredsBundle, Dialer: cc.dopts.copts.Dialer, + Authority: cc.authority, CustomUserAgent: cc.dopts.copts.UserAgent, ChannelzParentID: cc.channelzID, Target: cc.parsedTarget, - } + }) // Build the resolver. rWrapper, err := newCCResolverWrapper(cc, resolverBuilder) @@ -322,6 +300,7 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * // A blocking dial blocks until the clientConn is ready. if cc.dopts.block { for { + cc.Connect() s := cc.GetState() if s == connectivity.Ready { break @@ -416,7 +395,7 @@ type connectivityStateManager struct { mu sync.Mutex state connectivity.State notifyChan chan struct{} - channelzID int64 + channelzID *channelz.Identifier } // updateState updates the connectivity.State of ClientConn. @@ -482,34 +461,36 @@ var _ ClientConnInterface = (*ClientConn)(nil) // handshakes. It also handles errors on established connections by // re-resolving the name and reconnecting. type ClientConn struct { - ctx context.Context - cancel context.CancelFunc - - target string - parsedTarget resolver.Target - authority string - dopts dialOptions - csMgr *connectivityStateManager - - balancerBuildOpts balancer.BuildOptions - blockingpicker *pickerWrapper - + ctx context.Context // Initialized using the background context at dial time. + cancel context.CancelFunc // Cancelled on close. + + // The following are initialized at dial time, and are read-only after that. + target string // User's dial target. + parsedTarget resolver.Target // See parseTargetAndFindResolver(). + authority string // See determineAuthority(). + dopts dialOptions // Default and user specified dial options. + channelzID *channelz.Identifier // Channelz identifier for the channel. + balancerWrapper *ccBalancerWrapper // Uses gracefulswitch.balancer underneath. + + // The following provide their own synchronization, and therefore don't + // require cc.mu to be held to access them. + csMgr *connectivityStateManager + blockingpicker *pickerWrapper safeConfigSelector iresolver.SafeConfigSelector + czData *channelzData + retryThrottler atomic.Value // Updated from service config. - mu sync.RWMutex - resolverWrapper *ccResolverWrapper - sc *ServiceConfig - conns map[*addrConn]struct{} - // Keepalive parameter can be updated if a GoAway is received. - mkp keepalive.ClientParameters - curBalancerName string - balancerWrapper *ccBalancerWrapper - retryThrottler atomic.Value - + // firstResolveEvent is used to track whether the name resolver sent us at + // least one update. RPCs block on this event. firstResolveEvent *grpcsync.Event - channelzID int64 // channelz unique identification number - czData *channelzData + // mu protects the following fields. + // TODO: split mu so the same mutex isn't used for everything. + mu sync.RWMutex + resolverWrapper *ccResolverWrapper // Initialized in Dial; cleared in Close. + sc *ServiceConfig // Latest service config received from the resolver. + conns map[*addrConn]struct{} // Set to nil on close. + mkp keepalive.ClientParameters // May be updated upon receipt of a GoAway. lceMu sync.Mutex // protects lastConnectionError lastConnectionError error @@ -539,12 +520,24 @@ func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connec // // Experimental // -// Notice: This API is EXPERIMENTAL and may be changed or removed in a -// later release. +// Notice: This API is EXPERIMENTAL and may be changed or removed in a later +// release. func (cc *ClientConn) GetState() connectivity.State { return cc.csMgr.getState() } +// Connect causes all subchannels in the ClientConn to attempt to connect if +// the channel is idle. Does not wait for the connection attempts to begin +// before returning. +// +// Experimental +// +// Notice: This API is EXPERIMENTAL and may be changed or removed in a later +// release. +func (cc *ClientConn) Connect() { + cc.balancerWrapper.exitIdle() +} + func (cc *ClientConn) scWatcher() { for { select { @@ -622,9 +615,7 @@ func (cc *ClientConn) updateResolverState(s resolver.State, err error) error { // with the new addresses. cc.maybeApplyDefaultServiceConfig(nil) - if cc.balancerWrapper != nil { - cc.balancerWrapper.resolverError(err) - } + cc.balancerWrapper.resolverError(err) // No addresses are valid with err set; return early. cc.mu.Unlock() @@ -632,7 +623,10 @@ func (cc *ClientConn) updateResolverState(s resolver.State, err error) error { } var ret error - if cc.dopts.disableServiceConfig || s.ServiceConfig == nil { + if cc.dopts.disableServiceConfig { + channelz.Infof(logger, cc.channelzID, "ignoring service config from resolver (%v) and applying the default because service config is disabled", s.ServiceConfig) + cc.maybeApplyDefaultServiceConfig(s.Addresses) + } else if s.ServiceConfig == nil { cc.maybeApplyDefaultServiceConfig(s.Addresses) // TODO: do we need to apply a failing LB policy if there is no // default, per the error handling design? @@ -649,16 +643,10 @@ func (cc *ClientConn) updateResolverState(s resolver.State, err error) error { cc.applyServiceConfigAndBalancer(sc, configSelector, s.Addresses) } else { ret = balancer.ErrBadResolverState - if cc.balancerWrapper == nil { - var err error - if s.ServiceConfig.Err != nil { - err = status.Errorf(codes.Unavailable, "error parsing service config: %v", s.ServiceConfig.Err) - } else { - err = status.Errorf(codes.Unavailable, "illegal service config type: %T", s.ServiceConfig.Config) - } - cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{cc.sc}) - cc.blockingpicker.updatePicker(base.NewErrPicker(err)) - cc.csMgr.updateState(connectivity.TransientFailure) + if cc.sc == nil { + // Apply the failing LB only if we haven't received valid service config + // from the name resolver in the past. + cc.applyFailingLB(s.ServiceConfig) cc.mu.Unlock() return ret } @@ -666,24 +654,12 @@ func (cc *ClientConn) updateResolverState(s resolver.State, err error) error { } var balCfg serviceconfig.LoadBalancingConfig - if cc.dopts.balancerBuilder == nil && cc.sc != nil && cc.sc.lbConfig != nil { + if cc.sc != nil && cc.sc.lbConfig != nil { balCfg = cc.sc.lbConfig.cfg } - - cbn := cc.curBalancerName bw := cc.balancerWrapper cc.mu.Unlock() - if cbn != grpclbName { - // Filter any grpclb addresses since we don't have the grpclb balancer. - for i := 0; i < len(s.Addresses); { - if s.Addresses[i].Type == resolver.GRPCLB { - copy(s.Addresses[i:], s.Addresses[i+1:]) - s.Addresses = s.Addresses[:len(s.Addresses)-1] - continue - } - i++ - } - } + uccsErr := bw.updateClientConnState(&balancer.ClientConnState{ResolverState: s, BalancerConfig: balCfg}) if ret == nil { ret = uccsErr // prefer ErrBadResolver state since any other error is @@ -692,56 +668,28 @@ func (cc *ClientConn) updateResolverState(s resolver.State, err error) error { return ret } -// switchBalancer starts the switching from current balancer to the balancer -// with the given name. -// -// It will NOT send the current address list to the new balancer. If needed, -// caller of this function should send address list to the new balancer after -// this function returns. +// applyFailingLB is akin to configuring an LB policy on the channel which +// always fails RPCs. Here, an actual LB policy is not configured, but an always +// erroring picker is configured, which returns errors with information about +// what was invalid in the received service config. A config selector with no +// service config is configured, and the connectivity state of the channel is +// set to TransientFailure. // // Caller must hold cc.mu. -func (cc *ClientConn) switchBalancer(name string) { - if strings.EqualFold(cc.curBalancerName, name) { - return - } - - channelz.Infof(logger, cc.channelzID, "ClientConn switching balancer to %q", name) - if cc.dopts.balancerBuilder != nil { - channelz.Info(logger, cc.channelzID, "ignoring balancer switching: Balancer DialOption used instead") - return - } - if cc.balancerWrapper != nil { - // Don't hold cc.mu while closing the balancers. The balancers may call - // methods that require cc.mu (e.g. cc.NewSubConn()). Holding the mutex - // would cause a deadlock in that case. - cc.mu.Unlock() - cc.balancerWrapper.close() - cc.mu.Lock() - } - - builder := balancer.Get(name) - if builder == nil { - channelz.Warningf(logger, cc.channelzID, "Channel switches to new LB policy %q due to fallback from invalid balancer name", PickFirstBalancerName) - channelz.Infof(logger, cc.channelzID, "failed to get balancer builder for: %v, using pick_first instead", name) - builder = newPickfirstBuilder() +func (cc *ClientConn) applyFailingLB(sc *serviceconfig.ParseResult) { + var err error + if sc.Err != nil { + err = status.Errorf(codes.Unavailable, "error parsing service config: %v", sc.Err) } else { - channelz.Infof(logger, cc.channelzID, "Channel switches to new LB policy %q", name) + err = status.Errorf(codes.Unavailable, "illegal service config type: %T", sc.Config) } - - cc.curBalancerName = builder.Name() - cc.balancerWrapper = newCCBalancerWrapper(cc, builder, cc.balancerBuildOpts) + cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{nil}) + cc.blockingpicker.updatePicker(base.NewErrPicker(err)) + cc.csMgr.updateState(connectivity.TransientFailure) } func (cc *ClientConn) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State, err error) { - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return - } - // TODO(bar switching) send updates to all balancer wrappers when balancer - // gracefully switching is supported. - cc.balancerWrapper.handleSubConnStateChange(sc, s, err) - cc.mu.Unlock() + cc.balancerWrapper.updateSubConnState(sc, s, err) } // newAddrConn creates an addrConn for addrs and adds it to cc.conns. @@ -764,17 +712,21 @@ func (cc *ClientConn) newAddrConn(addrs []resolver.Address, opts balancer.NewSub cc.mu.Unlock() return nil, ErrClientConnClosing } - if channelz.IsOn() { - ac.channelzID = channelz.RegisterSubChannel(ac, cc.channelzID, "") - channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{ - Desc: "Subchannel Created", - Severity: channelz.CtInfo, - Parent: &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Subchannel(id:%d) created", ac.channelzID), - Severity: channelz.CtInfo, - }, - }) + + var err error + ac.channelzID, err = channelz.RegisterSubChannel(ac, cc.channelzID, "") + if err != nil { + return nil, err } + channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{ + Desc: "Subchannel created", + Severity: channelz.CtInfo, + Parent: &channelz.TraceEventDesc{ + Desc: fmt.Sprintf("Subchannel(id:%d) created", ac.channelzID.Int()), + Severity: channelz.CtInfo, + }, + }) + cc.conns[ac] = struct{}{} cc.mu.Unlock() return ac, nil @@ -845,21 +797,35 @@ func (ac *addrConn) connect() error { ac.updateConnectivityState(connectivity.Connecting, nil) ac.mu.Unlock() - // Start a goroutine connecting to the server asynchronously. - go ac.resetTransport() + ac.resetTransport() return nil } +func equalAddresses(a, b []resolver.Address) bool { + if len(a) != len(b) { + return false + } + for i, v := range a { + if !v.Equal(b[i]) { + return false + } + } + return true +} + // tryUpdateAddrs tries to update ac.addrs with the new addresses list. // -// If ac is Connecting, it returns false. The caller should tear down the ac and -// create a new one. Note that the backoff will be reset when this happens. -// // If ac is TransientFailure, it updates ac.addrs and returns true. The updated // addresses will be picked up by retry in the next iteration after backoff. // // If ac is Shutdown or Idle, it updates ac.addrs and returns true. // +// If the addresses is the same as the old list, it does nothing and returns +// true. +// +// If ac is Connecting, it returns false. The caller should tear down the ac and +// create a new one. Note that the backoff will be reset when this happens. +// // If ac is Ready, it checks whether current connected address of ac is in the // new addrs list. // - If true, it updates ac.addrs and returns true. The ac will keep using @@ -876,6 +842,10 @@ func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { return true } + if equalAddresses(ac.addrs, addrs) { + return true + } + if ac.state == connectivity.Connecting { return false } @@ -883,6 +853,7 @@ func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { // ac.state is Ready, try to find the connected address. var curAddrFound bool for _, a := range addrs { + a.ServerName = ac.cc.getServerName(a) if reflect.DeepEqual(ac.curAddr, a) { curAddrFound = true break @@ -896,6 +867,26 @@ func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { return curAddrFound } +// getServerName determines the serverName to be used in the connection +// handshake. The default value for the serverName is the authority on the +// ClientConn, which either comes from the user's dial target or through an +// authority override specified using the WithAuthority dial option. Name +// resolvers can specify a per-address override for the serverName through the +// resolver.Address.ServerName field which is used only if the WithAuthority +// dial option was not used. The rationale is that per-address authority +// overrides specified by the name resolver can represent a security risk, while +// an override specified by the user is more dependable since they probably know +// what they are doing. +func (cc *ClientConn) getServerName(addr resolver.Address) string { + if cc.dopts.authority != "" { + return cc.dopts.authority + } + if addr.ServerName != "" { + return addr.ServerName + } + return cc.authority +} + func getMethodConfig(sc *ServiceConfig, method string) MethodConfig { if sc == nil { return MethodConfig{} @@ -935,14 +926,10 @@ func (cc *ClientConn) healthCheckConfig() *healthCheckConfig { } func (cc *ClientConn) getTransport(ctx context.Context, failfast bool, method string) (transport.ClientTransport, func(balancer.DoneInfo), error) { - t, done, err := cc.blockingpicker.pick(ctx, failfast, balancer.PickInfo{ + return cc.blockingpicker.pick(ctx, failfast, balancer.PickInfo{ Ctx: ctx, FullMethodName: method, }) - if err != nil { - return nil, nil, toRPCErr(err) - } - return t, done, nil } func (cc *ClientConn) applyServiceConfigAndBalancer(sc *ServiceConfig, configSelector iresolver.ConfigSelector, addrs []resolver.Address) { @@ -967,35 +954,26 @@ func (cc *ClientConn) applyServiceConfigAndBalancer(sc *ServiceConfig, configSel cc.retryThrottler.Store((*retryThrottler)(nil)) } - if cc.dopts.balancerBuilder == nil { - // Only look at balancer types and switch balancer if balancer dial - // option is not set. - var newBalancerName string - if cc.sc != nil && cc.sc.lbConfig != nil { - newBalancerName = cc.sc.lbConfig.name - } else { - var isGRPCLB bool - for _, a := range addrs { - if a.Type == resolver.GRPCLB { - isGRPCLB = true - break - } - } - if isGRPCLB { - newBalancerName = grpclbName - } else if cc.sc != nil && cc.sc.LB != nil { - newBalancerName = *cc.sc.LB - } else { - newBalancerName = PickFirstBalancerName + var newBalancerName string + if cc.sc != nil && cc.sc.lbConfig != nil { + newBalancerName = cc.sc.lbConfig.name + } else { + var isGRPCLB bool + for _, a := range addrs { + if a.Type == resolver.GRPCLB { + isGRPCLB = true + break } } - cc.switchBalancer(newBalancerName) - } else if cc.balancerWrapper == nil { - // Balancer dial option was set, and this is the first time handling - // resolved addresses. Build a balancer with dopts.balancerBuilder. - cc.curBalancerName = cc.dopts.balancerBuilder.Name() - cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, cc.balancerBuildOpts) + if isGRPCLB { + newBalancerName = grpclbName + } else if cc.sc != nil && cc.sc.LB != nil { + newBalancerName = *cc.sc.LB + } else { + newBalancerName = PickFirstBalancerName + } } + cc.balancerWrapper.switchTo(newBalancerName) } func (cc *ClientConn) resolveNow(o resolver.ResolveNowOptions) { @@ -1046,11 +1024,11 @@ func (cc *ClientConn) Close() error { rWrapper := cc.resolverWrapper cc.resolverWrapper = nil bWrapper := cc.balancerWrapper - cc.balancerWrapper = nil cc.mu.Unlock() + // The order of closing matters here since the balancer wrapper assumes the + // picker is closed before it is closed. cc.blockingpicker.close() - if bWrapper != nil { bWrapper.close() } @@ -1061,22 +1039,22 @@ func (cc *ClientConn) Close() error { for ac := range conns { ac.tearDown(ErrClientConnClosing) } - if channelz.IsOn() { - ted := &channelz.TraceEventDesc{ - Desc: "Channel Deleted", + ted := &channelz.TraceEventDesc{ + Desc: "Channel deleted", + Severity: channelz.CtInfo, + } + if cc.dopts.channelzParentID != nil { + ted.Parent = &channelz.TraceEventDesc{ + Desc: fmt.Sprintf("Nested channel(id:%d) deleted", cc.channelzID.Int()), Severity: channelz.CtInfo, } - if cc.dopts.channelzParentID != 0 { - ted.Parent = &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Nested channel(id:%d) deleted", cc.channelzID), - Severity: channelz.CtInfo, - } - } - channelz.AddTraceEvent(logger, cc.channelzID, 0, ted) - // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add trace reference to - // the entity being deleted, and thus prevent it from being deleted right away. - channelz.RemoveEntry(cc.channelzID) } + channelz.AddTraceEvent(logger, cc.channelzID, 0, ted) + // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add + // trace reference to the entity being deleted, and thus prevent it from being + // deleted right away. + channelz.RemoveEntry(cc.channelzID) + return nil } @@ -1106,7 +1084,7 @@ type addrConn struct { backoffIdx int // Needs to be stateful for resetConnectBackoff. resetBackoff chan struct{} - channelzID int64 // channelz unique identification number. + channelzID *channelz.Identifier czData *channelzData } @@ -1135,112 +1113,86 @@ func (ac *addrConn) adjustParams(r transport.GoAwayReason) { } func (ac *addrConn) resetTransport() { - for i := 0; ; i++ { - if i > 0 { - ac.cc.resolveNow(resolver.ResolveNowOptions{}) - } + ac.mu.Lock() + if ac.state == connectivity.Shutdown { + ac.mu.Unlock() + return + } + addrs := ac.addrs + backoffFor := ac.dopts.bs.Backoff(ac.backoffIdx) + // This will be the duration that dial gets to finish. + dialDuration := minConnectTimeout + if ac.dopts.minConnectTimeout != nil { + dialDuration = ac.dopts.minConnectTimeout() + } + + if dialDuration < backoffFor { + // Give dial more time as we keep failing to connect. + dialDuration = backoffFor + } + // We can potentially spend all the time trying the first address, and + // if the server accepts the connection and then hangs, the following + // addresses will never be tried. + // + // The spec doesn't mention what should be done for multiple addresses. + // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md#proposed-backoff-algorithm + connectDeadline := time.Now().Add(dialDuration) + + ac.updateConnectivityState(connectivity.Connecting, nil) + ac.mu.Unlock() + + if err := ac.tryAllAddrs(addrs, connectDeadline); err != nil { + ac.cc.resolveNow(resolver.ResolveNowOptions{}) + // After exhausting all addresses, the addrConn enters + // TRANSIENT_FAILURE. ac.mu.Lock() if ac.state == connectivity.Shutdown { ac.mu.Unlock() return } + ac.updateConnectivityState(connectivity.TransientFailure, err) - addrs := ac.addrs - backoffFor := ac.dopts.bs.Backoff(ac.backoffIdx) - // This will be the duration that dial gets to finish. - dialDuration := minConnectTimeout - if ac.dopts.minConnectTimeout != nil { - dialDuration = ac.dopts.minConnectTimeout() - } - - if dialDuration < backoffFor { - // Give dial more time as we keep failing to connect. - dialDuration = backoffFor - } - // We can potentially spend all the time trying the first address, and - // if the server accepts the connection and then hangs, the following - // addresses will never be tried. - // - // The spec doesn't mention what should be done for multiple addresses. - // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md#proposed-backoff-algorithm - connectDeadline := time.Now().Add(dialDuration) - - ac.updateConnectivityState(connectivity.Connecting, nil) - ac.transport = nil + // Backoff. + b := ac.resetBackoff ac.mu.Unlock() - newTr, addr, reconnect, err := ac.tryAllAddrs(addrs, connectDeadline) - if err != nil { - // After exhausting all addresses, the addrConn enters - // TRANSIENT_FAILURE. + timer := time.NewTimer(backoffFor) + select { + case <-timer.C: ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return - } - ac.updateConnectivityState(connectivity.TransientFailure, err) - - // Backoff. - b := ac.resetBackoff + ac.backoffIdx++ ac.mu.Unlock() - - timer := time.NewTimer(backoffFor) - select { - case <-timer.C: - ac.mu.Lock() - ac.backoffIdx++ - ac.mu.Unlock() - case <-b: - timer.Stop() - case <-ac.ctx.Done(): - timer.Stop() - return - } - continue + case <-b: + timer.Stop() + case <-ac.ctx.Done(): + timer.Stop() + return } ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - newTr.Close(fmt.Errorf("reached connectivity state: SHUTDOWN")) - return + if ac.state != connectivity.Shutdown { + ac.updateConnectivityState(connectivity.Idle, err) } - ac.curAddr = addr - ac.transport = newTr - ac.backoffIdx = 0 - - hctx, hcancel := context.WithCancel(ac.ctx) - ac.startHealthCheck(hctx) ac.mu.Unlock() - - // Block until the created transport is down. And when this happens, - // we restart from the top of the addr list. - <-reconnect.Done() - hcancel() - // restart connecting - the top of the loop will set state to - // CONNECTING. This is against the current connectivity semantics doc, - // however it allows for graceful behavior for RPCs not yet dispatched - // - unfortunate timing would otherwise lead to the RPC failing even - // though the TRANSIENT_FAILURE state (called for by the doc) would be - // instantaneous. - // - // Ideally we should transition to Idle here and block until there is - // RPC activity that leads to the balancer requesting a reconnect of - // the associated SubConn. + return } + // Success; reset backoff. + ac.mu.Lock() + ac.backoffIdx = 0 + ac.mu.Unlock() } -// tryAllAddrs tries to creates a connection to the addresses, and stop when at the -// first successful one. It returns the transport, the address and a Event in -// the successful case. The Event fires when the returned transport disconnects. -func (ac *addrConn) tryAllAddrs(addrs []resolver.Address, connectDeadline time.Time) (transport.ClientTransport, resolver.Address, *grpcsync.Event, error) { +// tryAllAddrs tries to creates a connection to the addresses, and stop when at +// the first successful one. It returns an error if no address was successfully +// connected, or updates ac appropriately with the new transport. +func (ac *addrConn) tryAllAddrs(addrs []resolver.Address, connectDeadline time.Time) error { var firstConnErr error for _, addr := range addrs { ac.mu.Lock() if ac.state == connectivity.Shutdown { ac.mu.Unlock() - return nil, resolver.Address{}, nil, errConnClosing + return errConnClosing } ac.cc.mu.RLock() @@ -1255,9 +1207,9 @@ func (ac *addrConn) tryAllAddrs(addrs []resolver.Address, connectDeadline time.T channelz.Infof(logger, ac.channelzID, "Subchannel picks a new address %q to connect", addr.Addr) - newTr, reconnect, err := ac.createTransport(addr, copts, connectDeadline) + err := ac.createTransport(addr, copts, connectDeadline) if err == nil { - return newTr, addr, reconnect, nil + return nil } if firstConnErr == nil { firstConnErr = err @@ -1266,86 +1218,118 @@ func (ac *addrConn) tryAllAddrs(addrs []resolver.Address, connectDeadline time.T } // Couldn't connect to any address. - return nil, resolver.Address{}, nil, firstConnErr + return firstConnErr } -// createTransport creates a connection to addr. It returns the transport and a -// Event in the successful case. The Event fires when the returned transport -// disconnects. -func (ac *addrConn) createTransport(addr resolver.Address, copts transport.ConnectOptions, connectDeadline time.Time) (transport.ClientTransport, *grpcsync.Event, error) { - prefaceReceived := make(chan struct{}) - onCloseCalled := make(chan struct{}) - reconnect := grpcsync.NewEvent() +// createTransport creates a connection to addr. It returns an error if the +// address was not successfully connected, or updates ac appropriately with the +// new transport. +func (ac *addrConn) createTransport(addr resolver.Address, copts transport.ConnectOptions, connectDeadline time.Time) error { + // TODO: Delete prefaceReceived and move the logic to wait for it into the + // transport. + prefaceReceived := grpcsync.NewEvent() + connClosed := grpcsync.NewEvent() - // addr.ServerName takes precedent over ClientConn authority, if present. - if addr.ServerName == "" { - addr.ServerName = ac.cc.authority - } + addr.ServerName = ac.cc.getServerName(addr) + hctx, hcancel := context.WithCancel(ac.ctx) + hcStarted := false // protected by ac.mu - once := sync.Once{} - onGoAway := func(r transport.GoAwayReason) { + onClose := func() { ac.mu.Lock() - ac.adjustParams(r) - once.Do(func() { - if ac.state == connectivity.Ready { - // Prevent this SubConn from being used for new RPCs by setting its - // state to Connecting. - // - // TODO: this should be Idle when grpc-go properly supports it. - ac.updateConnectivityState(connectivity.Connecting, nil) - } - }) - ac.mu.Unlock() - reconnect.Fire() + defer ac.mu.Unlock() + defer connClosed.Fire() + defer hcancel() + if !hcStarted || hctx.Err() != nil { + // We didn't start the health check or set the state to READY, so + // no need to do anything else here. + // + // OR, we have already cancelled the health check context, meaning + // we have already called onClose once for this transport. In this + // case it would be dangerous to clear the transport and update the + // state, since there may be a new transport in this addrConn. + return + } + ac.transport = nil + // Refresh the name resolver + ac.cc.resolveNow(resolver.ResolveNowOptions{}) + if ac.state != connectivity.Shutdown { + ac.updateConnectivityState(connectivity.Idle, nil) + } } - onClose := func() { + onGoAway := func(r transport.GoAwayReason) { ac.mu.Lock() - once.Do(func() { - if ac.state == connectivity.Ready { - // Prevent this SubConn from being used for new RPCs by setting its - // state to Connecting. - // - // TODO: this should be Idle when grpc-go properly supports it. - ac.updateConnectivityState(connectivity.Connecting, nil) - } - }) + ac.adjustParams(r) ac.mu.Unlock() - close(onCloseCalled) - reconnect.Fire() - } - - onPrefaceReceipt := func() { - close(prefaceReceived) + onClose() } connectCtx, cancel := context.WithDeadline(ac.ctx, connectDeadline) defer cancel() - if channelz.IsOn() { - copts.ChannelzParentID = ac.channelzID - } + copts.ChannelzParentID = ac.channelzID - newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, addr, copts, onPrefaceReceipt, onGoAway, onClose) + newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, addr, copts, func() { prefaceReceived.Fire() }, onGoAway, onClose) if err != nil { // newTr is either nil, or closed. - channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %v. Err: %v. Reconnecting...", addr, err) - return nil, nil, err + hcancel() + channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %s. Err: %v", addr, err) + return err } select { - case <-time.After(time.Until(connectDeadline)): + case <-connectCtx.Done(): // We didn't get the preface in time. - newTr.Close(fmt.Errorf("failed to receive server preface within timeout")) - channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %v: didn't receive server preface in time. Reconnecting...", addr) - return nil, nil, errors.New("timed out waiting for server handshake") - case <-prefaceReceived: + // The error we pass to Close() is immaterial since there are no open + // streams at this point, so no trailers with error details will be sent + // out. We just need to pass a non-nil error. + newTr.Close(transport.ErrConnClosing) + if connectCtx.Err() == context.DeadlineExceeded { + err := errors.New("failed to receive server preface within timeout") + channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %s: %v", addr, err) + return err + } + return nil + case <-prefaceReceived.Done(): // We got the preface - huzzah! things are good. - case <-onCloseCalled: - // The transport has already closed - noop. - return nil, nil, errors.New("connection closed") - // TODO(deklerk) this should bail on ac.ctx.Done(). Add a test and fix. + ac.mu.Lock() + defer ac.mu.Unlock() + if connClosed.HasFired() { + // onClose called first; go idle but do nothing else. + if ac.state != connectivity.Shutdown { + ac.updateConnectivityState(connectivity.Idle, nil) + } + return nil + } + if ac.state == connectivity.Shutdown { + // This can happen if the subConn was removed while in `Connecting` + // state. tearDown() would have set the state to `Shutdown`, but + // would not have closed the transport since ac.transport would not + // been set at that point. + // + // We run this in a goroutine because newTr.Close() calls onClose() + // inline, which requires locking ac.mu. + // + // The error we pass to Close() is immaterial since there are no open + // streams at this point, so no trailers with error details will be sent + // out. We just need to pass a non-nil error. + go newTr.Close(transport.ErrConnClosing) + return nil + } + ac.curAddr = addr + ac.transport = newTr + hcStarted = true + ac.startHealthCheck(hctx) // Will set state to READY if appropriate. + return nil + case <-connClosed.Done(): + // The transport has already closed. If we received the preface, too, + // this is not an error. + select { + case <-prefaceReceived.Done(): + return nil + default: + return errors.New("connection closed before server preface received") + } } - return newTr, reconnect, nil } // startHealthCheck starts the health checking stream (RPC) to watch the health @@ -1429,26 +1413,14 @@ func (ac *addrConn) resetConnectBackoff() { ac.mu.Unlock() } -// getReadyTransport returns the transport if ac's state is READY. -// Otherwise it returns nil, false. -// If ac's state is IDLE, it will trigger ac to connect. -func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) { +// getReadyTransport returns the transport if ac's state is READY or nil if not. +func (ac *addrConn) getReadyTransport() transport.ClientTransport { ac.mu.Lock() - if ac.state == connectivity.Ready && ac.transport != nil { - t := ac.transport - ac.mu.Unlock() - return t, true - } - var idle bool - if ac.state == connectivity.Idle { - idle = true - } - ac.mu.Unlock() - // Trigger idle ac to connect. - if idle { - ac.connect() + defer ac.mu.Unlock() + if ac.state == connectivity.Ready { + return ac.transport } - return nil, false + return nil } // tearDown starts to tear down the addrConn. @@ -1478,19 +1450,18 @@ func (ac *addrConn) tearDown(err error) { curTr.GracefulClose() ac.mu.Lock() } - if channelz.IsOn() { - channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{ - Desc: "Subchannel Deleted", + channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{ + Desc: "Subchannel deleted", + Severity: channelz.CtInfo, + Parent: &channelz.TraceEventDesc{ + Desc: fmt.Sprintf("Subchannel(id:%d) deleted", ac.channelzID.Int()), Severity: channelz.CtInfo, - Parent: &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Subchanel(id:%d) deleted", ac.channelzID), - Severity: channelz.CtInfo, - }, - }) - // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add trace reference to - // the entity being deleted, and thus prevent it from being deleted right away. - channelz.RemoveEntry(ac.channelzID) - } + }, + }) + // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add + // trace reference to the entity being deleted, and thus prevent it from + // being deleted right away. + channelz.RemoveEntry(ac.channelzID) ac.mu.Unlock() } @@ -1599,3 +1570,114 @@ func (cc *ClientConn) connectionError() error { defer cc.lceMu.Unlock() return cc.lastConnectionError } + +func (cc *ClientConn) parseTargetAndFindResolver() (resolver.Builder, error) { + channelz.Infof(logger, cc.channelzID, "original dial target is: %q", cc.target) + + var rb resolver.Builder + parsedTarget, err := parseTarget(cc.target) + if err != nil { + channelz.Infof(logger, cc.channelzID, "dial target %q parse failed: %v", cc.target, err) + } else { + channelz.Infof(logger, cc.channelzID, "parsed dial target is: %+v", parsedTarget) + rb = cc.getResolver(parsedTarget.Scheme) + if rb != nil { + cc.parsedTarget = parsedTarget + return rb, nil + } + } + + // We are here because the user's dial target did not contain a scheme or + // specified an unregistered scheme. We should fallback to the default + // scheme, except when a custom dialer is specified in which case, we should + // always use passthrough scheme. + defScheme := resolver.GetDefaultScheme() + channelz.Infof(logger, cc.channelzID, "fallback to scheme %q", defScheme) + canonicalTarget := defScheme + ":///" + cc.target + + parsedTarget, err = parseTarget(canonicalTarget) + if err != nil { + channelz.Infof(logger, cc.channelzID, "dial target %q parse failed: %v", canonicalTarget, err) + return nil, err + } + channelz.Infof(logger, cc.channelzID, "parsed dial target is: %+v", parsedTarget) + rb = cc.getResolver(parsedTarget.Scheme) + if rb == nil { + return nil, fmt.Errorf("could not get resolver for default scheme: %q", parsedTarget.Scheme) + } + cc.parsedTarget = parsedTarget + return rb, nil +} + +// parseTarget uses RFC 3986 semantics to parse the given target into a +// resolver.Target struct containing scheme, authority and endpoint. Query +// params are stripped from the endpoint. +func parseTarget(target string) (resolver.Target, error) { + u, err := url.Parse(target) + if err != nil { + return resolver.Target{}, err + } + // For targets of the form "[scheme]://[authority]/endpoint, the endpoint + // value returned from url.Parse() contains a leading "/". Although this is + // in accordance with RFC 3986, we do not want to break existing resolver + // implementations which expect the endpoint without the leading "/". So, we + // end up stripping the leading "/" here. But this will result in an + // incorrect parsing for something like "unix:///path/to/socket". Since we + // own the "unix" resolver, we can workaround in the unix resolver by using + // the `URL` field instead of the `Endpoint` field. + endpoint := u.Path + if endpoint == "" { + endpoint = u.Opaque + } + endpoint = strings.TrimPrefix(endpoint, "/") + return resolver.Target{ + Scheme: u.Scheme, + Authority: u.Host, + Endpoint: endpoint, + URL: *u, + }, nil +} + +// Determine channel authority. The order of precedence is as follows: +// - user specified authority override using `WithAuthority` dial option +// - creds' notion of server name for the authentication handshake +// - endpoint from dial target of the form "scheme://[authority]/endpoint" +func determineAuthority(endpoint, target string, dopts dialOptions) (string, error) { + // Historically, we had two options for users to specify the serverName or + // authority for a channel. One was through the transport credentials + // (either in its constructor, or through the OverrideServerName() method). + // The other option (for cases where WithInsecure() dial option was used) + // was to use the WithAuthority() dial option. + // + // A few things have changed since: + // - `insecure` package with an implementation of the `TransportCredentials` + // interface for the insecure case + // - WithAuthority() dial option support for secure credentials + authorityFromCreds := "" + if creds := dopts.copts.TransportCredentials; creds != nil && creds.Info().ServerName != "" { + authorityFromCreds = creds.Info().ServerName + } + authorityFromDialOption := dopts.authority + if (authorityFromCreds != "" && authorityFromDialOption != "") && authorityFromCreds != authorityFromDialOption { + return "", fmt.Errorf("ClientConn's authority from transport creds %q and dial option %q don't match", authorityFromCreds, authorityFromDialOption) + } + + switch { + case authorityFromDialOption != "": + return authorityFromDialOption, nil + case authorityFromCreds != "": + return authorityFromCreds, nil + case strings.HasPrefix(target, "unix:") || strings.HasPrefix(target, "unix-abstract:"): + // TODO: remove when the unix resolver implements optional interface to + // return channel authority. + return "localhost", nil + case strings.HasPrefix(endpoint, ":"): + return "localhost" + endpoint, nil + default: + // TODO: Define an optional interface on the resolver builder to return + // the channel authority given the user's dial target. For resolvers + // which don't implement this interface, we will use the endpoint from + // "scheme://authority/endpoint" as the default authority. + return endpoint, nil + } +} diff --git a/vendor/google.golang.org/grpc/connectivity/connectivity.go b/vendor/google.golang.org/grpc/connectivity/connectivity.go index 010156261505..4a89926422bc 100644 --- a/vendor/google.golang.org/grpc/connectivity/connectivity.go +++ b/vendor/google.golang.org/grpc/connectivity/connectivity.go @@ -18,7 +18,6 @@ // Package connectivity defines connectivity semantics. // For details, see https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md. -// All APIs in this package are experimental. package connectivity import ( @@ -45,7 +44,7 @@ func (s State) String() string { return "SHUTDOWN" default: logger.Errorf("unknown connectivity state: %d", s) - return "Invalid-State" + return "INVALID_STATE" } } @@ -61,3 +60,35 @@ const ( // Shutdown indicates the ClientConn has started shutting down. Shutdown ) + +// ServingMode indicates the current mode of operation of the server. +// +// Only xDS enabled gRPC servers currently report their serving mode. +type ServingMode int + +const ( + // ServingModeStarting indicates that the server is starting up. + ServingModeStarting ServingMode = iota + // ServingModeServing indicates that the server contains all required + // configuration and is serving RPCs. + ServingModeServing + // ServingModeNotServing indicates that the server is not accepting new + // connections. Existing connections will be closed gracefully, allowing + // in-progress RPCs to complete. A server enters this mode when it does not + // contain the required configuration to serve RPCs. + ServingModeNotServing +) + +func (s ServingMode) String() string { + switch s { + case ServingModeStarting: + return "STARTING" + case ServingModeServing: + return "SERVING" + case ServingModeNotServing: + return "NOT_SERVING" + default: + logger.Errorf("unknown serving mode: %d", s) + return "INVALID_MODE" + } +} diff --git a/vendor/google.golang.org/grpc/credentials/credentials.go b/vendor/google.golang.org/grpc/credentials/credentials.go index 7eee7e4ec126..96ff1877e754 100644 --- a/vendor/google.golang.org/grpc/credentials/credentials.go +++ b/vendor/google.golang.org/grpc/credentials/credentials.go @@ -140,6 +140,11 @@ type TransportCredentials interface { // Additionally, ClientHandshakeInfo data will be available via the context // passed to this call. // + // The second argument to this method is the `:authority` header value used + // while creating new streams on this connection after authentication + // succeeds. Implementations must use this as the server name during the + // authentication handshake. + // // If the returned net.Conn is closed, it MUST close the net.Conn provided. ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error) // ServerHandshake does the authentication handshake for servers. It returns @@ -153,9 +158,13 @@ type TransportCredentials interface { Info() ProtocolInfo // Clone makes a copy of this TransportCredentials. Clone() TransportCredentials - // OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server. - // gRPC internals also use it to override the virtual hosting name if it is set. - // It must be called before dialing. Currently, this is only used by grpclb. + // OverrideServerName specifies the value used for the following: + // - verifying the hostname on the returned certificates + // - as SNI in the client's handshake to support virtual hosting + // - as the value for `:authority` header at stream creation time + // + // Deprecated: use grpc.WithAuthority instead. Will be supported + // throughout 1.x. OverrideServerName(string) error } @@ -169,8 +178,18 @@ type TransportCredentials interface { // // This API is experimental. type Bundle interface { + // TransportCredentials returns the transport credentials from the Bundle. + // + // Implementations must return non-nil transport credentials. If transport + // security is not needed by the Bundle, implementations may choose to + // return insecure.NewCredentials(). TransportCredentials() TransportCredentials + + // PerRPCCredentials returns the per-RPC credentials from the Bundle. + // + // May be nil if per-RPC credentials are not needed. PerRPCCredentials() PerRPCCredentials + // NewWithMode should make a copy of Bundle, and switch mode. Modifying the // existing Bundle may cause races. // diff --git a/vendor/google.golang.org/grpc/credentials/insecure/insecure.go b/vendor/google.golang.org/grpc/credentials/insecure/insecure.go new file mode 100644 index 000000000000..82bee1443bfe --- /dev/null +++ b/vendor/google.golang.org/grpc/credentials/insecure/insecure.go @@ -0,0 +1,98 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package insecure provides an implementation of the +// credentials.TransportCredentials interface which disables transport security. +package insecure + +import ( + "context" + "net" + + "google.golang.org/grpc/credentials" +) + +// NewCredentials returns a credentials which disables transport security. +// +// Note that using this credentials with per-RPC credentials which require +// transport security is incompatible and will cause grpc.Dial() to fail. +func NewCredentials() credentials.TransportCredentials { + return insecureTC{} +} + +// insecureTC implements the insecure transport credentials. The handshake +// methods simply return the passed in net.Conn and set the security level to +// NoSecurity. +type insecureTC struct{} + +func (insecureTC) ClientHandshake(ctx context.Context, _ string, conn net.Conn) (net.Conn, credentials.AuthInfo, error) { + return conn, info{credentials.CommonAuthInfo{SecurityLevel: credentials.NoSecurity}}, nil +} + +func (insecureTC) ServerHandshake(conn net.Conn) (net.Conn, credentials.AuthInfo, error) { + return conn, info{credentials.CommonAuthInfo{SecurityLevel: credentials.NoSecurity}}, nil +} + +func (insecureTC) Info() credentials.ProtocolInfo { + return credentials.ProtocolInfo{SecurityProtocol: "insecure"} +} + +func (insecureTC) Clone() credentials.TransportCredentials { + return insecureTC{} +} + +func (insecureTC) OverrideServerName(string) error { + return nil +} + +// info contains the auth information for an insecure connection. +// It implements the AuthInfo interface. +type info struct { + credentials.CommonAuthInfo +} + +// AuthType returns the type of info as a string. +func (info) AuthType() string { + return "insecure" +} + +// insecureBundle implements an insecure bundle. +// An insecure bundle provides a thin wrapper around insecureTC to support +// the credentials.Bundle interface. +type insecureBundle struct{} + +// NewBundle returns a bundle with disabled transport security and no per rpc credential. +func NewBundle() credentials.Bundle { + return insecureBundle{} +} + +// NewWithMode returns a new insecure Bundle. The mode is ignored. +func (insecureBundle) NewWithMode(string) (credentials.Bundle, error) { + return insecureBundle{}, nil +} + +// PerRPCCredentials returns an nil implementation as insecure +// bundle does not support a per rpc credential. +func (insecureBundle) PerRPCCredentials() credentials.PerRPCCredentials { + return nil +} + +// TransportCredentials returns the underlying insecure transport credential. +func (insecureBundle) TransportCredentials() credentials.TransportCredentials { + return NewCredentials() +} diff --git a/vendor/google.golang.org/grpc/credentials/tls.go b/vendor/google.golang.org/grpc/credentials/tls.go index 8ee7124f2265..784822d0560a 100644 --- a/vendor/google.golang.org/grpc/credentials/tls.go +++ b/vendor/google.golang.org/grpc/credentials/tls.go @@ -230,4 +230,7 @@ var cipherSuiteLookup = map[uint16]string{ tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", + tls.TLS_AES_128_GCM_SHA256: "TLS_AES_128_GCM_SHA256", + tls.TLS_AES_256_GCM_SHA384: "TLS_AES_256_GCM_SHA384", + tls.TLS_CHACHA20_POLY1305_SHA256: "TLS_CHACHA20_POLY1305_SHA256", } diff --git a/vendor/google.golang.org/grpc/dialoptions.go b/vendor/google.golang.org/grpc/dialoptions.go index 7a497237bbd3..f2f605a17c47 100644 --- a/vendor/google.golang.org/grpc/dialoptions.go +++ b/vendor/google.golang.org/grpc/dialoptions.go @@ -20,16 +20,15 @@ package grpc import ( "context" - "fmt" "net" "time" "google.golang.org/grpc/backoff" - "google.golang.org/grpc/balancer" + "google.golang.org/grpc/channelz" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/internal" internalbackoff "google.golang.org/grpc/internal/backoff" - "google.golang.org/grpc/internal/envconfig" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/resolver" @@ -45,20 +44,17 @@ type dialOptions struct { chainUnaryInts []UnaryClientInterceptor chainStreamInts []StreamClientInterceptor - cp Compressor - dc Decompressor - bs internalbackoff.Strategy - block bool - returnLastError bool - insecure bool - timeout time.Duration - scChan <-chan ServiceConfig - authority string - copts transport.ConnectOptions - callOptions []CallOption - // This is used by WithBalancerName dial option. - balancerBuilder balancer.Builder - channelzParentID int64 + cp Compressor + dc Decompressor + bs internalbackoff.Strategy + block bool + returnLastError bool + timeout time.Duration + scChan <-chan ServiceConfig + authority string + copts transport.ConnectOptions + callOptions []CallOption + channelzParentID *channelz.Identifier disableServiceConfig bool disableRetry bool disableHealthCheck bool @@ -196,25 +192,6 @@ func WithDecompressor(dc Decompressor) DialOption { }) } -// WithBalancerName sets the balancer that the ClientConn will be initialized -// with. Balancer registered with balancerName will be used. This function -// panics if no balancer was registered by balancerName. -// -// The balancer cannot be overridden by balancer option specified by service -// config. -// -// Deprecated: use WithDefaultServiceConfig and WithDisableServiceConfig -// instead. Will be removed in a future 1.x release. -func WithBalancerName(balancerName string) DialOption { - builder := balancer.Get(balancerName) - if builder == nil { - panic(fmt.Sprintf("grpc.WithBalancerName: no balancer is registered for name %v", balancerName)) - } - return newFuncDialOption(func(o *dialOptions) { - o.balancerBuilder = builder - }) -} - // WithServiceConfig returns a DialOption which has a channel to read the // service configuration. // @@ -228,18 +205,14 @@ func WithServiceConfig(c <-chan ServiceConfig) DialOption { }) } -// WithConnectParams configures the dialer to use the provided ConnectParams. +// WithConnectParams configures the ClientConn to use the provided ConnectParams +// for creating and maintaining connections to servers. // // The backoff configuration specified as part of the ConnectParams overrides // all defaults specified in // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Consider // using the backoff.DefaultConfig as a base, in cases where you want to // override only a subset of the backoff configuration. -// -// Experimental -// -// Notice: This API is EXPERIMENTAL and may be changed or removed in a -// later release. func WithConnectParams(p ConnectParams) DialOption { return newFuncDialOption(func(o *dialOptions) { o.bs = internalbackoff.Exponential{Config: p.Backoff} @@ -277,7 +250,7 @@ func withBackoff(bs internalbackoff.Strategy) DialOption { }) } -// WithBlock returns a DialOption which makes caller of Dial blocks until the +// WithBlock returns a DialOption which makes callers of Dial block until the // underlying connection is up. Without this, Dial returns immediately and // connecting the server happens in background. func WithBlock() DialOption { @@ -303,11 +276,17 @@ func WithReturnConnectionError() DialOption { } // WithInsecure returns a DialOption which disables transport security for this -// ClientConn. Note that transport security is required unless WithInsecure is -// set. +// ClientConn. Under the hood, it uses insecure.NewCredentials(). +// +// Note that using this DialOption with per-RPC credentials (through +// WithCredentialsBundle or WithPerRPCCredentials) which require transport +// security is incompatible and will cause grpc.Dial() to fail. +// +// Deprecated: use WithTransportCredentials and insecure.NewCredentials() +// instead. Will be supported throughout 1.x. func WithInsecure() DialOption { return newFuncDialOption(func(o *dialOptions) { - o.insecure = true + o.copts.TransportCredentials = insecure.NewCredentials() }) } @@ -482,8 +461,7 @@ func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOpt } // WithAuthority returns a DialOption that specifies the value to be used as the -// :authority pseudo-header. This value only works with WithInsecure and has no -// effect if TransportCredentials are present. +// :authority pseudo-header and as the server name in authentication handshake. func WithAuthority(a string) DialOption { return newFuncDialOption(func(o *dialOptions) { o.authority = a @@ -498,7 +476,7 @@ func WithAuthority(a string) DialOption { // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. -func WithChannelzParentID(id int64) DialOption { +func WithChannelzParentID(id *channelz.Identifier) DialOption { return newFuncDialOption(func(o *dialOptions) { o.channelzParentID = id }) @@ -519,14 +497,16 @@ func WithDisableServiceConfig() DialOption { // WithDefaultServiceConfig returns a DialOption that configures the default // service config, which will be used in cases where: // -// 1. WithDisableServiceConfig is also used. -// 2. Resolver does not return a service config or if the resolver returns an -// invalid service config. +// 1. WithDisableServiceConfig is also used, or // -// Experimental +// 2. The name resolver does not provide a service config or provides an +// invalid service config. // -// Notice: This API is EXPERIMENTAL and may be changed or removed in a -// later release. +// The parameter s is the JSON representation of the default service config. +// For more information about service configs, see: +// https://github.com/grpc/grpc/blob/master/doc/service_config.md +// For a simple example of usage, see: +// examples/features/load_balancing/client/main.go func WithDefaultServiceConfig(s string) DialOption { return newFuncDialOption(func(o *dialOptions) { o.defaultServiceConfigRawJSON = &s @@ -538,14 +518,8 @@ func WithDefaultServiceConfig(s string) DialOption { // will happen automatically if no data is written to the wire or if the RPC is // unprocessed by the remote server. // -// Retry support is currently disabled by default, but will be enabled by -// default in the future. Until then, it may be enabled by setting the -// environment variable "GRPC_GO_RETRY" to "on". -// -// Experimental -// -// Notice: This API is EXPERIMENTAL and may be changed or removed in a -// later release. +// Retry support is currently enabled by default, but may be disabled by +// setting the environment variable "GRPC_GO_RETRY" to "off". func WithDisableRetry() DialOption { return newFuncDialOption(func(o *dialOptions) { o.disableRetry = true @@ -585,7 +559,6 @@ func withHealthCheckFunc(f internal.HealthChecker) DialOption { func defaultDialOptions() dialOptions { return dialOptions{ - disableRetry: !envconfig.Retry, healthCheckFunc: internal.HealthCheckFunc, copts: transport.ConnectOptions{ WriteBufferSize: defaultWriteBufSize, diff --git a/vendor/google.golang.org/grpc/encoding/encoding.go b/vendor/google.golang.org/grpc/encoding/encoding.go index 6d84f74c7d08..18e530fc9024 100644 --- a/vendor/google.golang.org/grpc/encoding/encoding.go +++ b/vendor/google.golang.org/grpc/encoding/encoding.go @@ -108,7 +108,7 @@ var registeredCodecs = make(map[string]Codec) // more details. // // NOTE: this function must only be called during initialization time (i.e. in -// an init() function), and is not thread-safe. If multiple Compressors are +// an init() function), and is not thread-safe. If multiple Codecs are // registered with the same name, the one registered last will take effect. func RegisterCodec(codec Codec) { if codec == nil { diff --git a/vendor/google.golang.org/grpc/grpclog/loggerv2.go b/vendor/google.golang.org/grpc/grpclog/loggerv2.go index 4ee33171e008..7c1f66409034 100644 --- a/vendor/google.golang.org/grpc/grpclog/loggerv2.go +++ b/vendor/google.golang.org/grpc/grpclog/loggerv2.go @@ -19,11 +19,14 @@ package grpclog import ( + "encoding/json" + "fmt" "io" "io/ioutil" "log" "os" "strconv" + "strings" "google.golang.org/grpc/internal/grpclog" ) @@ -95,8 +98,9 @@ var severityName = []string{ // loggerT is the default logger used by grpclog. type loggerT struct { - m []*log.Logger - v int + m []*log.Logger + v int + jsonFormat bool } // NewLoggerV2 creates a loggerV2 with the provided writers. @@ -105,19 +109,32 @@ type loggerT struct { // Warning logs will be written to warningW and infoW. // Info logs will be written to infoW. func NewLoggerV2(infoW, warningW, errorW io.Writer) LoggerV2 { - return NewLoggerV2WithVerbosity(infoW, warningW, errorW, 0) + return newLoggerV2WithConfig(infoW, warningW, errorW, loggerV2Config{}) } // NewLoggerV2WithVerbosity creates a loggerV2 with the provided writers and // verbosity level. func NewLoggerV2WithVerbosity(infoW, warningW, errorW io.Writer, v int) LoggerV2 { + return newLoggerV2WithConfig(infoW, warningW, errorW, loggerV2Config{verbose: v}) +} + +type loggerV2Config struct { + verbose int + jsonFormat bool +} + +func newLoggerV2WithConfig(infoW, warningW, errorW io.Writer, c loggerV2Config) LoggerV2 { var m []*log.Logger - m = append(m, log.New(infoW, severityName[infoLog]+": ", log.LstdFlags)) - m = append(m, log.New(io.MultiWriter(infoW, warningW), severityName[warningLog]+": ", log.LstdFlags)) + flag := log.LstdFlags + if c.jsonFormat { + flag = 0 + } + m = append(m, log.New(infoW, "", flag)) + m = append(m, log.New(io.MultiWriter(infoW, warningW), "", flag)) ew := io.MultiWriter(infoW, warningW, errorW) // ew will be used for error and fatal. - m = append(m, log.New(ew, severityName[errorLog]+": ", log.LstdFlags)) - m = append(m, log.New(ew, severityName[fatalLog]+": ", log.LstdFlags)) - return &loggerT{m: m, v: v} + m = append(m, log.New(ew, "", flag)) + m = append(m, log.New(ew, "", flag)) + return &loggerT{m: m, v: c.verbose, jsonFormat: c.jsonFormat} } // newLoggerV2 creates a loggerV2 to be used as default logger. @@ -142,58 +159,79 @@ func newLoggerV2() LoggerV2 { if vl, err := strconv.Atoi(vLevel); err == nil { v = vl } - return NewLoggerV2WithVerbosity(infoW, warningW, errorW, v) + + jsonFormat := strings.EqualFold(os.Getenv("GRPC_GO_LOG_FORMATTER"), "json") + + return newLoggerV2WithConfig(infoW, warningW, errorW, loggerV2Config{ + verbose: v, + jsonFormat: jsonFormat, + }) +} + +func (g *loggerT) output(severity int, s string) { + sevStr := severityName[severity] + if !g.jsonFormat { + g.m[severity].Output(2, fmt.Sprintf("%v: %v", sevStr, s)) + return + } + // TODO: we can also include the logging component, but that needs more + // (API) changes. + b, _ := json.Marshal(map[string]string{ + "severity": sevStr, + "message": s, + }) + g.m[severity].Output(2, string(b)) } func (g *loggerT) Info(args ...interface{}) { - g.m[infoLog].Print(args...) + g.output(infoLog, fmt.Sprint(args...)) } func (g *loggerT) Infoln(args ...interface{}) { - g.m[infoLog].Println(args...) + g.output(infoLog, fmt.Sprintln(args...)) } func (g *loggerT) Infof(format string, args ...interface{}) { - g.m[infoLog].Printf(format, args...) + g.output(infoLog, fmt.Sprintf(format, args...)) } func (g *loggerT) Warning(args ...interface{}) { - g.m[warningLog].Print(args...) + g.output(warningLog, fmt.Sprint(args...)) } func (g *loggerT) Warningln(args ...interface{}) { - g.m[warningLog].Println(args...) + g.output(warningLog, fmt.Sprintln(args...)) } func (g *loggerT) Warningf(format string, args ...interface{}) { - g.m[warningLog].Printf(format, args...) + g.output(warningLog, fmt.Sprintf(format, args...)) } func (g *loggerT) Error(args ...interface{}) { - g.m[errorLog].Print(args...) + g.output(errorLog, fmt.Sprint(args...)) } func (g *loggerT) Errorln(args ...interface{}) { - g.m[errorLog].Println(args...) + g.output(errorLog, fmt.Sprintln(args...)) } func (g *loggerT) Errorf(format string, args ...interface{}) { - g.m[errorLog].Printf(format, args...) + g.output(errorLog, fmt.Sprintf(format, args...)) } func (g *loggerT) Fatal(args ...interface{}) { - g.m[fatalLog].Fatal(args...) - // No need to call os.Exit() again because log.Logger.Fatal() calls os.Exit(). + g.output(fatalLog, fmt.Sprint(args...)) + os.Exit(1) } func (g *loggerT) Fatalln(args ...interface{}) { - g.m[fatalLog].Fatalln(args...) - // No need to call os.Exit() again because log.Logger.Fatal() calls os.Exit(). + g.output(fatalLog, fmt.Sprintln(args...)) + os.Exit(1) } func (g *loggerT) Fatalf(format string, args ...interface{}) { - g.m[fatalLog].Fatalf(format, args...) - // No need to call os.Exit() again because log.Logger.Fatal() calls os.Exit(). + g.output(fatalLog, fmt.Sprintf(format, args...)) + os.Exit(1) } func (g *loggerT) V(l int) bool { @@ -210,12 +248,12 @@ func (g *loggerT) V(l int) bool { // later release. type DepthLoggerV2 interface { LoggerV2 - // InfoDepth logs to INFO log at the specified depth. Arguments are handled in the manner of fmt.Print. + // InfoDepth logs to INFO log at the specified depth. Arguments are handled in the manner of fmt.Println. InfoDepth(depth int, args ...interface{}) - // WarningDepth logs to WARNING log at the specified depth. Arguments are handled in the manner of fmt.Print. + // WarningDepth logs to WARNING log at the specified depth. Arguments are handled in the manner of fmt.Println. WarningDepth(depth int, args ...interface{}) - // ErrorDetph logs to ERROR log at the specified depth. Arguments are handled in the manner of fmt.Print. + // ErrorDepth logs to ERROR log at the specified depth. Arguments are handled in the manner of fmt.Println. ErrorDepth(depth int, args ...interface{}) - // FatalDepth logs to FATAL log at the specified depth. Arguments are handled in the manner of fmt.Print. + // FatalDepth logs to FATAL log at the specified depth. Arguments are handled in the manner of fmt.Println. FatalDepth(depth int, args ...interface{}) } diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go index bdc3ae284e7a..69f525d1baeb 100644 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go +++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.1.0 +// - protoc-gen-go-grpc v1.2.0 // - protoc v3.14.0 // source: grpc/health/v1/health.proto diff --git a/vendor/google.golang.org/grpc/interceptor.go b/vendor/google.golang.org/grpc/interceptor.go index 668e0adcf0a9..bb96ef57be89 100644 --- a/vendor/google.golang.org/grpc/interceptor.go +++ b/vendor/google.golang.org/grpc/interceptor.go @@ -72,9 +72,12 @@ type UnaryServerInfo struct { } // UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal -// execution of a unary RPC. If a UnaryHandler returns an error, it should be produced by the -// status package, or else gRPC will use codes.Unknown as the status code and err.Error() as -// the status message of the RPC. +// execution of a unary RPC. +// +// If a UnaryHandler returns an error, it should either be produced by the +// status package, or be one of the context errors. Otherwise, gRPC will use +// codes.Unknown as the status code and err.Error() as the status message of the +// RPC. type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error) // UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info diff --git a/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go b/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go new file mode 100644 index 000000000000..7ba8f4d18319 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/balancer/gracefulswitch/gracefulswitch.go @@ -0,0 +1,382 @@ +/* + * + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package gracefulswitch implements a graceful switch load balancer. +package gracefulswitch + +import ( + "errors" + "fmt" + "sync" + + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/balancer/base" + "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/resolver" +) + +var errBalancerClosed = errors.New("gracefulSwitchBalancer is closed") +var _ balancer.Balancer = (*Balancer)(nil) + +// NewBalancer returns a graceful switch Balancer. +func NewBalancer(cc balancer.ClientConn, opts balancer.BuildOptions) *Balancer { + return &Balancer{ + cc: cc, + bOpts: opts, + } +} + +// Balancer is a utility to gracefully switch from one balancer to +// a new balancer. It implements the balancer.Balancer interface. +type Balancer struct { + bOpts balancer.BuildOptions + cc balancer.ClientConn + + // mu protects the following fields and all fields within balancerCurrent + // and balancerPending. mu does not need to be held when calling into the + // child balancers, as all calls into these children happen only as a direct + // result of a call into the gracefulSwitchBalancer, which are also + // guaranteed to be synchronous. There is one exception: an UpdateState call + // from a child balancer when current and pending are populated can lead to + // calling Close() on the current. To prevent that racing with an + // UpdateSubConnState from the channel, we hold currentMu during Close and + // UpdateSubConnState calls. + mu sync.Mutex + balancerCurrent *balancerWrapper + balancerPending *balancerWrapper + closed bool // set to true when this balancer is closed + + // currentMu must be locked before mu. This mutex guards against this + // sequence of events: UpdateSubConnState() called, finds the + // balancerCurrent, gives up lock, updateState comes in, causes Close() on + // balancerCurrent before the UpdateSubConnState is called on the + // balancerCurrent. + currentMu sync.Mutex +} + +// swap swaps out the current lb with the pending lb and updates the ClientConn. +// The caller must hold gsb.mu. +func (gsb *Balancer) swap() { + gsb.cc.UpdateState(gsb.balancerPending.lastState) + cur := gsb.balancerCurrent + gsb.balancerCurrent = gsb.balancerPending + gsb.balancerPending = nil + go func() { + gsb.currentMu.Lock() + defer gsb.currentMu.Unlock() + cur.Close() + }() +} + +// Helper function that checks if the balancer passed in is current or pending. +// The caller must hold gsb.mu. +func (gsb *Balancer) balancerCurrentOrPending(bw *balancerWrapper) bool { + return bw == gsb.balancerCurrent || bw == gsb.balancerPending +} + +// SwitchTo initializes the graceful switch process, which completes based on +// connectivity state changes on the current/pending balancer. Thus, the switch +// process is not complete when this method returns. This method must be called +// synchronously alongside the rest of the balancer.Balancer methods this +// Graceful Switch Balancer implements. +func (gsb *Balancer) SwitchTo(builder balancer.Builder) error { + gsb.mu.Lock() + if gsb.closed { + gsb.mu.Unlock() + return errBalancerClosed + } + bw := &balancerWrapper{ + gsb: gsb, + lastState: balancer.State{ + ConnectivityState: connectivity.Connecting, + Picker: base.NewErrPicker(balancer.ErrNoSubConnAvailable), + }, + subconns: make(map[balancer.SubConn]bool), + } + balToClose := gsb.balancerPending // nil if there is no pending balancer + if gsb.balancerCurrent == nil { + gsb.balancerCurrent = bw + } else { + gsb.balancerPending = bw + } + gsb.mu.Unlock() + balToClose.Close() + // This function takes a builder instead of a balancer because builder.Build + // can call back inline, and this utility needs to handle the callbacks. + newBalancer := builder.Build(bw, gsb.bOpts) + if newBalancer == nil { + // This is illegal and should never happen; we clear the balancerWrapper + // we were constructing if it happens to avoid a potential panic. + gsb.mu.Lock() + if gsb.balancerPending != nil { + gsb.balancerPending = nil + } else { + gsb.balancerCurrent = nil + } + gsb.mu.Unlock() + return balancer.ErrBadResolverState + } + + // This write doesn't need to take gsb.mu because this field never gets read + // or written to on any calls from the current or pending. Calls from grpc + // to this balancer are guaranteed to be called synchronously, so this + // bw.Balancer field will never be forwarded to until this SwitchTo() + // function returns. + bw.Balancer = newBalancer + return nil +} + +// Returns nil if the graceful switch balancer is closed. +func (gsb *Balancer) latestBalancer() *balancerWrapper { + gsb.mu.Lock() + defer gsb.mu.Unlock() + if gsb.balancerPending != nil { + return gsb.balancerPending + } + return gsb.balancerCurrent +} + +// UpdateClientConnState forwards the update to the latest balancer created. +func (gsb *Balancer) UpdateClientConnState(state balancer.ClientConnState) error { + // The resolver data is only relevant to the most recent LB Policy. + balToUpdate := gsb.latestBalancer() + if balToUpdate == nil { + return errBalancerClosed + } + // Perform this call without gsb.mu to prevent deadlocks if the child calls + // back into the channel. The latest balancer can never be closed during a + // call from the channel, even without gsb.mu held. + return balToUpdate.UpdateClientConnState(state) +} + +// ResolverError forwards the error to the latest balancer created. +func (gsb *Balancer) ResolverError(err error) { + // The resolver data is only relevant to the most recent LB Policy. + balToUpdate := gsb.latestBalancer() + if balToUpdate == nil { + return + } + // Perform this call without gsb.mu to prevent deadlocks if the child calls + // back into the channel. The latest balancer can never be closed during a + // call from the channel, even without gsb.mu held. + balToUpdate.ResolverError(err) +} + +// ExitIdle forwards the call to the latest balancer created. +// +// If the latest balancer does not support ExitIdle, the subConns are +// re-connected to manually. +func (gsb *Balancer) ExitIdle() { + balToUpdate := gsb.latestBalancer() + if balToUpdate == nil { + return + } + // There is no need to protect this read with a mutex, as the write to the + // Balancer field happens in SwitchTo, which completes before this can be + // called. + if ei, ok := balToUpdate.Balancer.(balancer.ExitIdler); ok { + ei.ExitIdle() + return + } + for sc := range balToUpdate.subconns { + sc.Connect() + } +} + +// UpdateSubConnState forwards the update to the appropriate child. +func (gsb *Balancer) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) { + gsb.currentMu.Lock() + defer gsb.currentMu.Unlock() + gsb.mu.Lock() + // Forward update to the appropriate child. Even if there is a pending + // balancer, the current balancer should continue to get SubConn updates to + // maintain the proper state while the pending is still connecting. + var balToUpdate *balancerWrapper + if gsb.balancerCurrent != nil && gsb.balancerCurrent.subconns[sc] { + balToUpdate = gsb.balancerCurrent + } else if gsb.balancerPending != nil && gsb.balancerPending.subconns[sc] { + balToUpdate = gsb.balancerPending + } + gsb.mu.Unlock() + if balToUpdate == nil { + // SubConn belonged to a stale lb policy that has not yet fully closed, + // or the balancer was already closed. + return + } + balToUpdate.UpdateSubConnState(sc, state) +} + +// Close closes any active child balancers. +func (gsb *Balancer) Close() { + gsb.mu.Lock() + gsb.closed = true + currentBalancerToClose := gsb.balancerCurrent + gsb.balancerCurrent = nil + pendingBalancerToClose := gsb.balancerPending + gsb.balancerPending = nil + gsb.mu.Unlock() + + currentBalancerToClose.Close() + pendingBalancerToClose.Close() +} + +// balancerWrapper wraps a balancer.Balancer, and overrides some Balancer +// methods to help cleanup SubConns created by the wrapped balancer. +// +// It implements the balancer.ClientConn interface and is passed down in that +// capacity to the wrapped balancer. It maintains a set of subConns created by +// the wrapped balancer and calls from the latter to create/update/remove +// SubConns update this set before being forwarded to the parent ClientConn. +// State updates from the wrapped balancer can result in invocation of the +// graceful switch logic. +type balancerWrapper struct { + balancer.Balancer + gsb *Balancer + + lastState balancer.State + subconns map[balancer.SubConn]bool // subconns created by this balancer +} + +func (bw *balancerWrapper) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) { + if state.ConnectivityState == connectivity.Shutdown { + bw.gsb.mu.Lock() + delete(bw.subconns, sc) + bw.gsb.mu.Unlock() + } + // There is no need to protect this read with a mutex, as the write to the + // Balancer field happens in SwitchTo, which completes before this can be + // called. + bw.Balancer.UpdateSubConnState(sc, state) +} + +// Close closes the underlying LB policy and removes the subconns it created. bw +// must not be referenced via balancerCurrent or balancerPending in gsb when +// called. gsb.mu must not be held. Does not panic with a nil receiver. +func (bw *balancerWrapper) Close() { + // before Close is called. + if bw == nil { + return + } + // There is no need to protect this read with a mutex, as Close() is + // impossible to be called concurrently with the write in SwitchTo(). The + // callsites of Close() for this balancer in Graceful Switch Balancer will + // never be called until SwitchTo() returns. + bw.Balancer.Close() + bw.gsb.mu.Lock() + for sc := range bw.subconns { + bw.gsb.cc.RemoveSubConn(sc) + } + bw.gsb.mu.Unlock() +} + +func (bw *balancerWrapper) UpdateState(state balancer.State) { + // Hold the mutex for this entire call to ensure it cannot occur + // concurrently with other updateState() calls. This causes updates to + // lastState and calls to cc.UpdateState to happen atomically. + bw.gsb.mu.Lock() + defer bw.gsb.mu.Unlock() + bw.lastState = state + + if !bw.gsb.balancerCurrentOrPending(bw) { + return + } + + if bw == bw.gsb.balancerCurrent { + // In the case that the current balancer exits READY, and there is a pending + // balancer, you can forward the pending balancer's cached State up to + // ClientConn and swap the pending into the current. This is because there + // is no reason to gracefully switch from and keep using the old policy as + // the ClientConn is not connected to any backends. + if state.ConnectivityState != connectivity.Ready && bw.gsb.balancerPending != nil { + bw.gsb.swap() + return + } + // Even if there is a pending balancer waiting to be gracefully switched to, + // continue to forward current balancer updates to the Client Conn. Ignoring + // state + picker from the current would cause undefined behavior/cause the + // system to behave incorrectly from the current LB policies perspective. + // Also, the current LB is still being used by grpc to choose SubConns per + // RPC, and thus should use the most updated form of the current balancer. + bw.gsb.cc.UpdateState(state) + return + } + // This method is now dealing with a state update from the pending balancer. + // If the current balancer is currently in a state other than READY, the new + // policy can be swapped into place immediately. This is because there is no + // reason to gracefully switch from and keep using the old policy as the + // ClientConn is not connected to any backends. + if state.ConnectivityState != connectivity.Connecting || bw.gsb.balancerCurrent.lastState.ConnectivityState != connectivity.Ready { + bw.gsb.swap() + } +} + +func (bw *balancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { + bw.gsb.mu.Lock() + if !bw.gsb.balancerCurrentOrPending(bw) { + bw.gsb.mu.Unlock() + return nil, fmt.Errorf("%T at address %p that called NewSubConn is deleted", bw, bw) + } + bw.gsb.mu.Unlock() + + sc, err := bw.gsb.cc.NewSubConn(addrs, opts) + if err != nil { + return nil, err + } + bw.gsb.mu.Lock() + if !bw.gsb.balancerCurrentOrPending(bw) { // balancer was closed during this call + bw.gsb.cc.RemoveSubConn(sc) + bw.gsb.mu.Unlock() + return nil, fmt.Errorf("%T at address %p that called NewSubConn is deleted", bw, bw) + } + bw.subconns[sc] = true + bw.gsb.mu.Unlock() + return sc, nil +} + +func (bw *balancerWrapper) ResolveNow(opts resolver.ResolveNowOptions) { + // Ignore ResolveNow requests from anything other than the most recent + // balancer, because older balancers were already removed from the config. + if bw != bw.gsb.latestBalancer() { + return + } + bw.gsb.cc.ResolveNow(opts) +} + +func (bw *balancerWrapper) RemoveSubConn(sc balancer.SubConn) { + bw.gsb.mu.Lock() + if !bw.gsb.balancerCurrentOrPending(bw) { + bw.gsb.mu.Unlock() + return + } + bw.gsb.mu.Unlock() + bw.gsb.cc.RemoveSubConn(sc) +} + +func (bw *balancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) { + bw.gsb.mu.Lock() + if !bw.gsb.balancerCurrentOrPending(bw) { + bw.gsb.mu.Unlock() + return + } + bw.gsb.mu.Unlock() + bw.gsb.cc.UpdateAddresses(sc, addrs) +} + +func (bw *balancerWrapper) Target() string { + return bw.gsb.cc.Target() +} diff --git a/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go b/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go index 5cc3aeddb213..0a25ce43f3f0 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go @@ -31,7 +31,7 @@ import ( // Logger is the global binary logger. It can be used to get binary logger for // each method. type Logger interface { - getMethodLogger(methodName string) *MethodLogger + GetMethodLogger(methodName string) MethodLogger } // binLogger is the global binary logger for the binary. One of this should be @@ -49,17 +49,24 @@ func SetLogger(l Logger) { binLogger = l } +// GetLogger gets the binarg logger. +// +// Only call this at init time. +func GetLogger() Logger { + return binLogger +} + // GetMethodLogger returns the methodLogger for the given methodName. // // methodName should be in the format of "/service/method". // // Each methodLogger returned by this method is a new instance. This is to // generate sequence id within the call. -func GetMethodLogger(methodName string) *MethodLogger { +func GetMethodLogger(methodName string) MethodLogger { if binLogger == nil { return nil } - return binLogger.getMethodLogger(methodName) + return binLogger.GetMethodLogger(methodName) } func init() { @@ -68,17 +75,29 @@ func init() { binLogger = NewLoggerFromConfigString(configStr) } -type methodLoggerConfig struct { +// MethodLoggerConfig contains the setting for logging behavior of a method +// logger. Currently, it contains the max length of header and message. +type MethodLoggerConfig struct { // Max length of header and message. - hdr, msg uint64 + Header, Message uint64 +} + +// LoggerConfig contains the config for loggers to create method loggers. +type LoggerConfig struct { + All *MethodLoggerConfig + Services map[string]*MethodLoggerConfig + Methods map[string]*MethodLoggerConfig + + Blacklist map[string]struct{} } type logger struct { - all *methodLoggerConfig - services map[string]*methodLoggerConfig - methods map[string]*methodLoggerConfig + config LoggerConfig +} - blacklist map[string]struct{} +// NewLoggerFromConfig builds a logger with the given LoggerConfig. +func NewLoggerFromConfig(config LoggerConfig) Logger { + return &logger{config: config} } // newEmptyLogger creates an empty logger. The map fields need to be filled in @@ -88,57 +107,57 @@ func newEmptyLogger() *logger { } // Set method logger for "*". -func (l *logger) setDefaultMethodLogger(ml *methodLoggerConfig) error { - if l.all != nil { +func (l *logger) setDefaultMethodLogger(ml *MethodLoggerConfig) error { + if l.config.All != nil { return fmt.Errorf("conflicting global rules found") } - l.all = ml + l.config.All = ml return nil } // Set method logger for "service/*". // // New methodLogger with same service overrides the old one. -func (l *logger) setServiceMethodLogger(service string, ml *methodLoggerConfig) error { - if _, ok := l.services[service]; ok { +func (l *logger) setServiceMethodLogger(service string, ml *MethodLoggerConfig) error { + if _, ok := l.config.Services[service]; ok { return fmt.Errorf("conflicting service rules for service %v found", service) } - if l.services == nil { - l.services = make(map[string]*methodLoggerConfig) + if l.config.Services == nil { + l.config.Services = make(map[string]*MethodLoggerConfig) } - l.services[service] = ml + l.config.Services[service] = ml return nil } // Set method logger for "service/method". // // New methodLogger with same method overrides the old one. -func (l *logger) setMethodMethodLogger(method string, ml *methodLoggerConfig) error { - if _, ok := l.blacklist[method]; ok { +func (l *logger) setMethodMethodLogger(method string, ml *MethodLoggerConfig) error { + if _, ok := l.config.Blacklist[method]; ok { return fmt.Errorf("conflicting blacklist rules for method %v found", method) } - if _, ok := l.methods[method]; ok { + if _, ok := l.config.Methods[method]; ok { return fmt.Errorf("conflicting method rules for method %v found", method) } - if l.methods == nil { - l.methods = make(map[string]*methodLoggerConfig) + if l.config.Methods == nil { + l.config.Methods = make(map[string]*MethodLoggerConfig) } - l.methods[method] = ml + l.config.Methods[method] = ml return nil } // Set blacklist method for "-service/method". func (l *logger) setBlacklist(method string) error { - if _, ok := l.blacklist[method]; ok { + if _, ok := l.config.Blacklist[method]; ok { return fmt.Errorf("conflicting blacklist rules for method %v found", method) } - if _, ok := l.methods[method]; ok { + if _, ok := l.config.Methods[method]; ok { return fmt.Errorf("conflicting method rules for method %v found", method) } - if l.blacklist == nil { - l.blacklist = make(map[string]struct{}) + if l.config.Blacklist == nil { + l.config.Blacklist = make(map[string]struct{}) } - l.blacklist[method] = struct{}{} + l.config.Blacklist[method] = struct{}{} return nil } @@ -148,23 +167,23 @@ func (l *logger) setBlacklist(method string) error { // // Each methodLogger returned by this method is a new instance. This is to // generate sequence id within the call. -func (l *logger) getMethodLogger(methodName string) *MethodLogger { +func (l *logger) GetMethodLogger(methodName string) MethodLogger { s, m, err := grpcutil.ParseMethod(methodName) if err != nil { grpclogLogger.Infof("binarylogging: failed to parse %q: %v", methodName, err) return nil } - if ml, ok := l.methods[s+"/"+m]; ok { - return newMethodLogger(ml.hdr, ml.msg) + if ml, ok := l.config.Methods[s+"/"+m]; ok { + return newMethodLogger(ml.Header, ml.Message) } - if _, ok := l.blacklist[s+"/"+m]; ok { + if _, ok := l.config.Blacklist[s+"/"+m]; ok { return nil } - if ml, ok := l.services[s]; ok { - return newMethodLogger(ml.hdr, ml.msg) + if ml, ok := l.config.Services[s]; ok { + return newMethodLogger(ml.Header, ml.Message) } - if l.all == nil { + if l.config.All == nil { return nil } - return newMethodLogger(l.all.hdr, l.all.msg) + return newMethodLogger(l.config.All.Header, l.config.All.Message) } diff --git a/vendor/google.golang.org/grpc/internal/binarylog/env_config.go b/vendor/google.golang.org/grpc/internal/binarylog/env_config.go index d8f4e7602fde..ab589a76bf96 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/env_config.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/env_config.go @@ -89,7 +89,7 @@ func (l *logger) fillMethodLoggerWithConfigString(config string) error { if err != nil { return fmt.Errorf("invalid config: %q, %v", config, err) } - if err := l.setDefaultMethodLogger(&methodLoggerConfig{hdr: hdr, msg: msg}); err != nil { + if err := l.setDefaultMethodLogger(&MethodLoggerConfig{Header: hdr, Message: msg}); err != nil { return fmt.Errorf("invalid config: %v", err) } return nil @@ -104,11 +104,11 @@ func (l *logger) fillMethodLoggerWithConfigString(config string) error { return fmt.Errorf("invalid header/message length config: %q, %v", suffix, err) } if m == "*" { - if err := l.setServiceMethodLogger(s, &methodLoggerConfig{hdr: hdr, msg: msg}); err != nil { + if err := l.setServiceMethodLogger(s, &MethodLoggerConfig{Header: hdr, Message: msg}); err != nil { return fmt.Errorf("invalid config: %v", err) } } else { - if err := l.setMethodMethodLogger(s+"/"+m, &methodLoggerConfig{hdr: hdr, msg: msg}); err != nil { + if err := l.setMethodMethodLogger(s+"/"+m, &MethodLoggerConfig{Header: hdr, Message: msg}); err != nil { return fmt.Errorf("invalid config: %v", err) } } diff --git a/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go b/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go index 0cdb41831509..24df0a1a0c4e 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go @@ -48,7 +48,11 @@ func (g *callIDGenerator) reset() { var idGen callIDGenerator // MethodLogger is the sub-logger for each method. -type MethodLogger struct { +type MethodLogger interface { + Log(LogEntryConfig) +} + +type methodLogger struct { headerMaxLen, messageMaxLen uint64 callID uint64 @@ -57,8 +61,8 @@ type MethodLogger struct { sink Sink // TODO(blog): make this plugable. } -func newMethodLogger(h, m uint64) *MethodLogger { - return &MethodLogger{ +func newMethodLogger(h, m uint64) *methodLogger { + return &methodLogger{ headerMaxLen: h, messageMaxLen: m, @@ -69,8 +73,10 @@ func newMethodLogger(h, m uint64) *MethodLogger { } } -// Log creates a proto binary log entry, and logs it to the sink. -func (ml *MethodLogger) Log(c LogEntryConfig) { +// Build is an internal only method for building the proto message out of the +// input event. It's made public to enable other library to reuse as much logic +// in methodLogger as possible. +func (ml *methodLogger) Build(c LogEntryConfig) *pb.GrpcLogEntry { m := c.toProto() timestamp, _ := ptypes.TimestampProto(time.Now()) m.Timestamp = timestamp @@ -85,11 +91,15 @@ func (ml *MethodLogger) Log(c LogEntryConfig) { case *pb.GrpcLogEntry_Message: m.PayloadTruncated = ml.truncateMessage(pay.Message) } + return m +} - ml.sink.Write(m) +// Log creates a proto binary log entry, and logs it to the sink. +func (ml *methodLogger) Log(c LogEntryConfig) { + ml.sink.Write(ml.Build(c)) } -func (ml *MethodLogger) truncateMetadata(mdPb *pb.Metadata) (truncated bool) { +func (ml *methodLogger) truncateMetadata(mdPb *pb.Metadata) (truncated bool) { if ml.headerMaxLen == maxUInt { return false } @@ -119,7 +129,7 @@ func (ml *MethodLogger) truncateMetadata(mdPb *pb.Metadata) (truncated bool) { return truncated } -func (ml *MethodLogger) truncateMessage(msgPb *pb.Message) (truncated bool) { +func (ml *methodLogger) truncateMessage(msgPb *pb.Message) (truncated bool) { if ml.messageMaxLen == maxUInt { return false } diff --git a/vendor/google.golang.org/grpc/internal/binarylog/sink.go b/vendor/google.golang.org/grpc/internal/binarylog/sink.go index 7d7a3056b71e..c2fdd58b3198 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/sink.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/sink.go @@ -69,7 +69,8 @@ type writerSink struct { func (ws *writerSink) Write(e *pb.GrpcLogEntry) error { b, err := proto.Marshal(e) if err != nil { - grpclogLogger.Infof("binary logging: failed to marshal proto message: %v", err) + grpclogLogger.Errorf("binary logging: failed to marshal proto message: %v", err) + return err } hdr := make([]byte, 4) binary.BigEndian.PutUint32(hdr, uint32(len(b))) @@ -85,24 +86,27 @@ func (ws *writerSink) Write(e *pb.GrpcLogEntry) error { func (ws *writerSink) Close() error { return nil } type bufferedSink struct { - mu sync.Mutex - closer io.Closer - out Sink // out is built on buf. - buf *bufio.Writer // buf is kept for flush. - - writeStartOnce sync.Once - writeTicker *time.Ticker + mu sync.Mutex + closer io.Closer + out Sink // out is built on buf. + buf *bufio.Writer // buf is kept for flush. + flusherStarted bool + + writeTicker *time.Ticker + done chan struct{} } func (fs *bufferedSink) Write(e *pb.GrpcLogEntry) error { - // Start the write loop when Write is called. - fs.writeStartOnce.Do(fs.startFlushGoroutine) fs.mu.Lock() + defer fs.mu.Unlock() + if !fs.flusherStarted { + // Start the write loop when Write is called. + fs.startFlushGoroutine() + fs.flusherStarted = true + } if err := fs.out.Write(e); err != nil { - fs.mu.Unlock() return err } - fs.mu.Unlock() return nil } @@ -113,7 +117,12 @@ const ( func (fs *bufferedSink) startFlushGoroutine() { fs.writeTicker = time.NewTicker(bufFlushDuration) go func() { - for range fs.writeTicker.C { + for { + select { + case <-fs.done: + return + case <-fs.writeTicker.C: + } fs.mu.Lock() if err := fs.buf.Flush(); err != nil { grpclogLogger.Warningf("failed to flush to Sink: %v", err) @@ -124,10 +133,12 @@ func (fs *bufferedSink) startFlushGoroutine() { } func (fs *bufferedSink) Close() error { + fs.mu.Lock() + defer fs.mu.Unlock() if fs.writeTicker != nil { fs.writeTicker.Stop() } - fs.mu.Lock() + close(fs.done) if err := fs.buf.Flush(); err != nil { grpclogLogger.Warningf("failed to flush to Sink: %v", err) } @@ -137,7 +148,6 @@ func (fs *bufferedSink) Close() error { if err := fs.out.Close(); err != nil { grpclogLogger.Warningf("failed to close the Sink: %v", err) } - fs.mu.Unlock() return nil } @@ -155,5 +165,6 @@ func NewBufferedSink(o io.WriteCloser) Sink { closer: o, out: newWriterSink(bufW), buf: bufW, + done: make(chan struct{}), } } diff --git a/vendor/google.golang.org/grpc/internal/channelz/funcs.go b/vendor/google.golang.org/grpc/internal/channelz/funcs.go index f7314139303e..777cbcd7921d 100644 --- a/vendor/google.golang.org/grpc/internal/channelz/funcs.go +++ b/vendor/google.golang.org/grpc/internal/channelz/funcs.go @@ -24,6 +24,8 @@ package channelz import ( + "context" + "errors" "fmt" "sort" "sync" @@ -49,7 +51,8 @@ var ( // TurnOn turns on channelz data collection. func TurnOn() { if !IsOn() { - NewChannelzStorage() + db.set(newChannelMap()) + idGen.reset() atomic.StoreInt32(&curState, 1) } } @@ -94,46 +97,40 @@ func (d *dbWrapper) get() *channelMap { return d.DB } -// NewChannelzStorage initializes channelz data storage and id generator. +// NewChannelzStorageForTesting initializes channelz data storage and id +// generator for testing purposes. // -// This function returns a cleanup function to wait for all channelz state to be reset by the -// grpc goroutines when those entities get closed. By using this cleanup function, we make sure tests -// don't mess up each other, i.e. lingering goroutine from previous test doing entity removal happen -// to remove some entity just register by the new test, since the id space is the same. -// -// Note: This function is exported for testing purpose only. User should not call -// it in most cases. -func NewChannelzStorage() (cleanup func() error) { - db.set(&channelMap{ - topLevelChannels: make(map[int64]struct{}), - channels: make(map[int64]*channel), - listenSockets: make(map[int64]*listenSocket), - normalSockets: make(map[int64]*normalSocket), - servers: make(map[int64]*server), - subChannels: make(map[int64]*subChannel), - }) +// Returns a cleanup function to be invoked by the test, which waits for up to +// 10s for all channelz state to be reset by the grpc goroutines when those +// entities get closed. This cleanup function helps with ensuring that tests +// don't mess up each other. +func NewChannelzStorageForTesting() (cleanup func() error) { + db.set(newChannelMap()) idGen.reset() + return func() error { - var err error cm := db.get() if cm == nil { return nil } - for i := 0; i < 1000; i++ { - cm.mu.Lock() - if len(cm.topLevelChannels) == 0 && len(cm.servers) == 0 && len(cm.channels) == 0 && len(cm.subChannels) == 0 && len(cm.listenSockets) == 0 && len(cm.normalSockets) == 0 { - cm.mu.Unlock() - // all things stored in the channelz map have been cleared. + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + cm.mu.RLock() + topLevelChannels, servers, channels, subChannels, listenSockets, normalSockets := len(cm.topLevelChannels), len(cm.servers), len(cm.channels), len(cm.subChannels), len(cm.listenSockets), len(cm.normalSockets) + cm.mu.RUnlock() + + if err := ctx.Err(); err != nil { + return fmt.Errorf("after 10s the channelz map has not been cleaned up yet, topchannels: %d, servers: %d, channels: %d, subchannels: %d, listen sockets: %d, normal sockets: %d", topLevelChannels, servers, channels, subChannels, listenSockets, normalSockets) + } + if topLevelChannels == 0 && servers == 0 && channels == 0 && subChannels == 0 && listenSockets == 0 && normalSockets == 0 { return nil } - cm.mu.Unlock() - time.Sleep(10 * time.Millisecond) + <-ticker.C } - - cm.mu.Lock() - err = fmt.Errorf("after 10s the channelz map has not been cleaned up yet, topchannels: %d, servers: %d, channels: %d, subchannels: %d, listen sockets: %d, normal sockets: %d", len(cm.topLevelChannels), len(cm.servers), len(cm.channels), len(cm.subChannels), len(cm.listenSockets), len(cm.normalSockets)) - cm.mu.Unlock() - return err } } @@ -188,54 +185,77 @@ func GetServer(id int64) *ServerMetric { return db.get().GetServer(id) } -// RegisterChannel registers the given channel c in channelz database with ref -// as its reference name, and add it to the child list of its parent (identified -// by pid). pid = 0 means no parent. It returns the unique channelz tracking id -// assigned to this channel. -func RegisterChannel(c Channel, pid int64, ref string) int64 { +// RegisterChannel registers the given channel c in the channelz database with +// ref as its reference name, and adds it to the child list of its parent +// (identified by pid). pid == nil means no parent. +// +// Returns a unique channelz identifier assigned to this channel. +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterChannel(c Channel, pid *Identifier, ref string) *Identifier { id := idGen.genID() + var parent int64 + isTopChannel := true + if pid != nil { + isTopChannel = false + parent = pid.Int() + } + + if !IsOn() { + return newIdentifer(RefChannel, id, pid) + } + cn := &channel{ refName: ref, c: c, subChans: make(map[int64]string), nestedChans: make(map[int64]string), id: id, - pid: pid, + pid: parent, trace: &channelTrace{createdTime: time.Now(), events: make([]*TraceEvent, 0, getMaxTraceEntry())}, } - if pid == 0 { - db.get().addChannel(id, cn, true, pid, ref) - } else { - db.get().addChannel(id, cn, false, pid, ref) - } - return id + db.get().addChannel(id, cn, isTopChannel, parent) + return newIdentifer(RefChannel, id, pid) } -// RegisterSubChannel registers the given channel c in channelz database with ref -// as its reference name, and add it to the child list of its parent (identified -// by pid). It returns the unique channelz tracking id assigned to this subchannel. -func RegisterSubChannel(c Channel, pid int64, ref string) int64 { - if pid == 0 { - logger.Error("a SubChannel's parent id cannot be 0") - return 0 +// RegisterSubChannel registers the given subChannel c in the channelz database +// with ref as its reference name, and adds it to the child list of its parent +// (identified by pid). +// +// Returns a unique channelz identifier assigned to this subChannel. +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterSubChannel(c Channel, pid *Identifier, ref string) (*Identifier, error) { + if pid == nil { + return nil, errors.New("a SubChannel's parent id cannot be nil") } id := idGen.genID() + if !IsOn() { + return newIdentifer(RefSubChannel, id, pid), nil + } + sc := &subChannel{ refName: ref, c: c, sockets: make(map[int64]string), id: id, - pid: pid, + pid: pid.Int(), trace: &channelTrace{createdTime: time.Now(), events: make([]*TraceEvent, 0, getMaxTraceEntry())}, } - db.get().addSubChannel(id, sc, pid, ref) - return id + db.get().addSubChannel(id, sc, pid.Int()) + return newIdentifer(RefSubChannel, id, pid), nil } // RegisterServer registers the given server s in channelz database. It returns // the unique channelz tracking id assigned to this server. -func RegisterServer(s Server, ref string) int64 { +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterServer(s Server, ref string) *Identifier { id := idGen.genID() + if !IsOn() { + return newIdentifer(RefServer, id, nil) + } + svr := &server{ refName: ref, s: s, @@ -244,71 +264,92 @@ func RegisterServer(s Server, ref string) int64 { id: id, } db.get().addServer(id, svr) - return id + return newIdentifer(RefServer, id, nil) } // RegisterListenSocket registers the given listen socket s in channelz database // with ref as its reference name, and add it to the child list of its parent // (identified by pid). It returns the unique channelz tracking id assigned to // this listen socket. -func RegisterListenSocket(s Socket, pid int64, ref string) int64 { - if pid == 0 { - logger.Error("a ListenSocket's parent id cannot be 0") - return 0 +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterListenSocket(s Socket, pid *Identifier, ref string) (*Identifier, error) { + if pid == nil { + return nil, errors.New("a ListenSocket's parent id cannot be 0") } id := idGen.genID() - ls := &listenSocket{refName: ref, s: s, id: id, pid: pid} - db.get().addListenSocket(id, ls, pid, ref) - return id + if !IsOn() { + return newIdentifer(RefListenSocket, id, pid), nil + } + + ls := &listenSocket{refName: ref, s: s, id: id, pid: pid.Int()} + db.get().addListenSocket(id, ls, pid.Int()) + return newIdentifer(RefListenSocket, id, pid), nil } // RegisterNormalSocket registers the given normal socket s in channelz database -// with ref as its reference name, and add it to the child list of its parent +// with ref as its reference name, and adds it to the child list of its parent // (identified by pid). It returns the unique channelz tracking id assigned to // this normal socket. -func RegisterNormalSocket(s Socket, pid int64, ref string) int64 { - if pid == 0 { - logger.Error("a NormalSocket's parent id cannot be 0") - return 0 +// +// If channelz is not turned ON, the channelz database is not mutated. +func RegisterNormalSocket(s Socket, pid *Identifier, ref string) (*Identifier, error) { + if pid == nil { + return nil, errors.New("a NormalSocket's parent id cannot be 0") } id := idGen.genID() - ns := &normalSocket{refName: ref, s: s, id: id, pid: pid} - db.get().addNormalSocket(id, ns, pid, ref) - return id + if !IsOn() { + return newIdentifer(RefNormalSocket, id, pid), nil + } + + ns := &normalSocket{refName: ref, s: s, id: id, pid: pid.Int()} + db.get().addNormalSocket(id, ns, pid.Int()) + return newIdentifer(RefNormalSocket, id, pid), nil } -// RemoveEntry removes an entry with unique channelz trakcing id to be id from +// RemoveEntry removes an entry with unique channelz tracking id to be id from // channelz database. -func RemoveEntry(id int64) { - db.get().removeEntry(id) +// +// If channelz is not turned ON, this function is a no-op. +func RemoveEntry(id *Identifier) { + if !IsOn() { + return + } + db.get().removeEntry(id.Int()) } -// TraceEventDesc is what the caller of AddTraceEvent should provide to describe the event to be added -// to the channel trace. -// The Parent field is optional. It is used for event that will be recorded in the entity's parent -// trace also. +// TraceEventDesc is what the caller of AddTraceEvent should provide to describe +// the event to be added to the channel trace. +// +// The Parent field is optional. It is used for an event that will be recorded +// in the entity's parent trace. type TraceEventDesc struct { Desc string Severity Severity Parent *TraceEventDesc } -// AddTraceEvent adds trace related to the entity with specified id, using the provided TraceEventDesc. -func AddTraceEvent(l grpclog.DepthLoggerV2, id int64, depth int, desc *TraceEventDesc) { - for d := desc; d != nil; d = d.Parent { - switch d.Severity { - case CtUnknown, CtInfo: - l.InfoDepth(depth+1, d.Desc) - case CtWarning: - l.WarningDepth(depth+1, d.Desc) - case CtError: - l.ErrorDepth(depth+1, d.Desc) - } +// AddTraceEvent adds trace related to the entity with specified id, using the +// provided TraceEventDesc. +// +// If channelz is not turned ON, this will simply log the event descriptions. +func AddTraceEvent(l grpclog.DepthLoggerV2, id *Identifier, depth int, desc *TraceEventDesc) { + // Log only the trace description associated with the bottom most entity. + switch desc.Severity { + case CtUnknown, CtInfo: + l.InfoDepth(depth+1, withParens(id)+desc.Desc) + case CtWarning: + l.WarningDepth(depth+1, withParens(id)+desc.Desc) + case CtError: + l.ErrorDepth(depth+1, withParens(id)+desc.Desc) } + if getMaxTraceEntry() == 0 { return } - db.get().traceEvent(id, desc) + if IsOn() { + db.get().traceEvent(id.Int(), desc) + } } // channelMap is the storage data structure for channelz. @@ -326,6 +367,17 @@ type channelMap struct { normalSockets map[int64]*normalSocket } +func newChannelMap() *channelMap { + return &channelMap{ + topLevelChannels: make(map[int64]struct{}), + channels: make(map[int64]*channel), + listenSockets: make(map[int64]*listenSocket), + normalSockets: make(map[int64]*normalSocket), + servers: make(map[int64]*server), + subChannels: make(map[int64]*subChannel), + } +} + func (c *channelMap) addServer(id int64, s *server) { c.mu.Lock() s.cm = c @@ -333,7 +385,7 @@ func (c *channelMap) addServer(id int64, s *server) { c.mu.Unlock() } -func (c *channelMap) addChannel(id int64, cn *channel, isTopChannel bool, pid int64, ref string) { +func (c *channelMap) addChannel(id int64, cn *channel, isTopChannel bool, pid int64) { c.mu.Lock() cn.cm = c cn.trace.cm = c @@ -346,7 +398,7 @@ func (c *channelMap) addChannel(id int64, cn *channel, isTopChannel bool, pid in c.mu.Unlock() } -func (c *channelMap) addSubChannel(id int64, sc *subChannel, pid int64, ref string) { +func (c *channelMap) addSubChannel(id int64, sc *subChannel, pid int64) { c.mu.Lock() sc.cm = c sc.trace.cm = c @@ -355,7 +407,7 @@ func (c *channelMap) addSubChannel(id int64, sc *subChannel, pid int64, ref stri c.mu.Unlock() } -func (c *channelMap) addListenSocket(id int64, ls *listenSocket, pid int64, ref string) { +func (c *channelMap) addListenSocket(id int64, ls *listenSocket, pid int64) { c.mu.Lock() ls.cm = c c.listenSockets[id] = ls @@ -363,7 +415,7 @@ func (c *channelMap) addListenSocket(id int64, ls *listenSocket, pid int64, ref c.mu.Unlock() } -func (c *channelMap) addNormalSocket(id int64, ns *normalSocket, pid int64, ref string) { +func (c *channelMap) addNormalSocket(id int64, ns *normalSocket, pid int64) { c.mu.Lock() ns.cm = c c.normalSockets[id] = ns @@ -630,7 +682,7 @@ func (c *channelMap) GetServerSockets(id int64, startID int64, maxResults int64) if count == 0 { end = true } - var s []*SocketMetric + s := make([]*SocketMetric, 0, len(sks)) for _, ns := range sks { sm := &SocketMetric{} sm.SocketData = ns.s.ChannelzMetric() diff --git a/vendor/google.golang.org/grpc/internal/channelz/id.go b/vendor/google.golang.org/grpc/internal/channelz/id.go new file mode 100644 index 000000000000..c9a27acd3710 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/channelz/id.go @@ -0,0 +1,75 @@ +/* + * + * Copyright 2022 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package channelz + +import "fmt" + +// Identifier is an opaque identifier which uniquely identifies an entity in the +// channelz database. +type Identifier struct { + typ RefChannelType + id int64 + str string + pid *Identifier +} + +// Type returns the entity type corresponding to id. +func (id *Identifier) Type() RefChannelType { + return id.typ +} + +// Int returns the integer identifier corresponding to id. +func (id *Identifier) Int() int64 { + return id.id +} + +// String returns a string representation of the entity corresponding to id. +// +// This includes some information about the parent as well. Examples: +// Top-level channel: [Channel #channel-number] +// Nested channel: [Channel #parent-channel-number Channel #channel-number] +// Sub channel: [Channel #parent-channel SubChannel #subchannel-number] +func (id *Identifier) String() string { + return id.str +} + +// Equal returns true if other is the same as id. +func (id *Identifier) Equal(other *Identifier) bool { + if (id != nil) != (other != nil) { + return false + } + if id == nil && other == nil { + return true + } + return id.typ == other.typ && id.id == other.id && id.pid == other.pid +} + +// NewIdentifierForTesting returns a new opaque identifier to be used only for +// testing purposes. +func NewIdentifierForTesting(typ RefChannelType, id int64, pid *Identifier) *Identifier { + return newIdentifer(typ, id, pid) +} + +func newIdentifer(typ RefChannelType, id int64, pid *Identifier) *Identifier { + str := fmt.Sprintf("%s #%d", typ, id) + if pid != nil { + str = fmt.Sprintf("%s %s", pid, str) + } + return &Identifier{typ: typ, id: id, str: str, pid: pid} +} diff --git a/vendor/google.golang.org/grpc/internal/channelz/logging.go b/vendor/google.golang.org/grpc/internal/channelz/logging.go index b0013f9c8865..8e13a3d2ce7b 100644 --- a/vendor/google.golang.org/grpc/internal/channelz/logging.go +++ b/vendor/google.golang.org/grpc/internal/channelz/logging.go @@ -26,77 +26,54 @@ import ( var logger = grpclog.Component("channelz") +func withParens(id *Identifier) string { + return "[" + id.String() + "] " +} + // Info logs and adds a trace event if channelz is on. -func Info(l grpclog.DepthLoggerV2, id int64, args ...interface{}) { - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: fmt.Sprint(args...), - Severity: CtInfo, - }) - } else { - l.InfoDepth(1, args...) - } +func Info(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprint(args...), + Severity: CtInfo, + }) } // Infof logs and adds a trace event if channelz is on. -func Infof(l grpclog.DepthLoggerV2, id int64, format string, args ...interface{}) { - msg := fmt.Sprintf(format, args...) - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: msg, - Severity: CtInfo, - }) - } else { - l.InfoDepth(1, msg) - } +func Infof(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprintf(format, args...), + Severity: CtInfo, + }) } // Warning logs and adds a trace event if channelz is on. -func Warning(l grpclog.DepthLoggerV2, id int64, args ...interface{}) { - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: fmt.Sprint(args...), - Severity: CtWarning, - }) - } else { - l.WarningDepth(1, args...) - } +func Warning(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprint(args...), + Severity: CtWarning, + }) } // Warningf logs and adds a trace event if channelz is on. -func Warningf(l grpclog.DepthLoggerV2, id int64, format string, args ...interface{}) { - msg := fmt.Sprintf(format, args...) - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: msg, - Severity: CtWarning, - }) - } else { - l.WarningDepth(1, msg) - } +func Warningf(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprintf(format, args...), + Severity: CtWarning, + }) } // Error logs and adds a trace event if channelz is on. -func Error(l grpclog.DepthLoggerV2, id int64, args ...interface{}) { - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: fmt.Sprint(args...), - Severity: CtError, - }) - } else { - l.ErrorDepth(1, args...) - } +func Error(l grpclog.DepthLoggerV2, id *Identifier, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprint(args...), + Severity: CtError, + }) } // Errorf logs and adds a trace event if channelz is on. -func Errorf(l grpclog.DepthLoggerV2, id int64, format string, args ...interface{}) { - msg := fmt.Sprintf(format, args...) - if IsOn() { - AddTraceEvent(l, id, 1, &TraceEventDesc{ - Desc: msg, - Severity: CtError, - }) - } else { - l.ErrorDepth(1, msg) - } +func Errorf(l grpclog.DepthLoggerV2, id *Identifier, format string, args ...interface{}) { + AddTraceEvent(l, id, 1, &TraceEventDesc{ + Desc: fmt.Sprintf(format, args...), + Severity: CtError, + }) } diff --git a/vendor/google.golang.org/grpc/internal/channelz/types.go b/vendor/google.golang.org/grpc/internal/channelz/types.go index 3c595d154bd3..ad0ce4dabf06 100644 --- a/vendor/google.golang.org/grpc/internal/channelz/types.go +++ b/vendor/google.golang.org/grpc/internal/channelz/types.go @@ -686,12 +686,33 @@ const ( type RefChannelType int const ( + // RefUnknown indicates an unknown entity type, the zero value for this type. + RefUnknown RefChannelType = iota // RefChannel indicates the referenced entity is a Channel. - RefChannel RefChannelType = iota + RefChannel // RefSubChannel indicates the referenced entity is a SubChannel. RefSubChannel + // RefServer indicates the referenced entity is a Server. + RefServer + // RefListenSocket indicates the referenced entity is a ListenSocket. + RefListenSocket + // RefNormalSocket indicates the referenced entity is a NormalSocket. + RefNormalSocket ) +var refChannelTypeToString = map[RefChannelType]string{ + RefUnknown: "Unknown", + RefChannel: "Channel", + RefSubChannel: "SubChannel", + RefServer: "Server", + RefListenSocket: "ListenSocket", + RefNormalSocket: "NormalSocket", +} + +func (r RefChannelType) String() string { + return refChannelTypeToString[r] +} + func (c *channelTrace) dumpData() *ChannelTrace { c.mu.Lock() ct := &ChannelTrace{EventNum: c.eventCount, CreationTime: c.createdTime} diff --git a/vendor/google.golang.org/grpc/internal/channelz/types_linux.go b/vendor/google.golang.org/grpc/internal/channelz/types_linux.go index 692dd6181778..1b1c4cce34a9 100644 --- a/vendor/google.golang.org/grpc/internal/channelz/types_linux.go +++ b/vendor/google.golang.org/grpc/internal/channelz/types_linux.go @@ -1,5 +1,3 @@ -// +build !appengine - /* * * Copyright 2018 gRPC authors. diff --git a/vendor/google.golang.org/grpc/internal/channelz/types_nonlinux.go b/vendor/google.golang.org/grpc/internal/channelz/types_nonlinux.go index 19c2fc521dcf..8b06eed1ab8b 100644 --- a/vendor/google.golang.org/grpc/internal/channelz/types_nonlinux.go +++ b/vendor/google.golang.org/grpc/internal/channelz/types_nonlinux.go @@ -1,4 +1,5 @@ -// +build !linux appengine +//go:build !linux +// +build !linux /* * @@ -37,6 +38,6 @@ type SocketOptionData struct { // Windows OS doesn't support Socket Option func (s *SocketOptionData) Getsockopt(fd uintptr) { once.Do(func() { - logger.Warning("Channelz: socket options are not supported on non-linux os and appengine.") + logger.Warning("Channelz: socket options are not supported on non-linux environments") }) } diff --git a/vendor/google.golang.org/grpc/internal/channelz/util_linux.go b/vendor/google.golang.org/grpc/internal/channelz/util_linux.go index fdf409d55de3..8d194e44e1dc 100644 --- a/vendor/google.golang.org/grpc/internal/channelz/util_linux.go +++ b/vendor/google.golang.org/grpc/internal/channelz/util_linux.go @@ -1,5 +1,3 @@ -// +build linux,!appengine - /* * * Copyright 2018 gRPC authors. diff --git a/vendor/google.golang.org/grpc/internal/channelz/util_nonlinux.go b/vendor/google.golang.org/grpc/internal/channelz/util_nonlinux.go index 8864a0811164..837ddc402400 100644 --- a/vendor/google.golang.org/grpc/internal/channelz/util_nonlinux.go +++ b/vendor/google.golang.org/grpc/internal/channelz/util_nonlinux.go @@ -1,4 +1,5 @@ -// +build !linux appengine +//go:build !linux +// +build !linux /* * diff --git a/vendor/google.golang.org/grpc/internal/credentials/spiffe.go b/vendor/google.golang.org/grpc/internal/credentials/spiffe.go index be70b6cdfc31..25ade623058e 100644 --- a/vendor/google.golang.org/grpc/internal/credentials/spiffe.go +++ b/vendor/google.golang.org/grpc/internal/credentials/spiffe.go @@ -1,5 +1,3 @@ -// +build !appengine - /* * * Copyright 2020 gRPC authors. diff --git a/vendor/google.golang.org/grpc/internal/credentials/syscallconn.go b/vendor/google.golang.org/grpc/internal/credentials/syscallconn.go index f499a614c20e..2919632d657e 100644 --- a/vendor/google.golang.org/grpc/internal/credentials/syscallconn.go +++ b/vendor/google.golang.org/grpc/internal/credentials/syscallconn.go @@ -1,5 +1,3 @@ -// +build !appengine - /* * * Copyright 2018 gRPC authors. diff --git a/vendor/google.golang.org/grpc/internal/credentials/util.go b/vendor/google.golang.org/grpc/internal/credentials/util.go index 55664fa46b81..f792fd22cafc 100644 --- a/vendor/google.golang.org/grpc/internal/credentials/util.go +++ b/vendor/google.golang.org/grpc/internal/credentials/util.go @@ -18,7 +18,9 @@ package credentials -import "crypto/tls" +import ( + "crypto/tls" +) const alpnProtoStrH2 = "h2" diff --git a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go index 73931a94bcad..6f0272543110 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go @@ -26,13 +26,10 @@ import ( const ( prefix = "GRPC_GO_" - retryStr = prefix + "RETRY" txtErrIgnoreStr = prefix + "IGNORE_TXT_ERRORS" ) var ( - // Retry is set if retry is explicitly enabled via "GRPC_GO_RETRY=on". - Retry = strings.EqualFold(os.Getenv(retryStr), "on") // TXTErrIgnore is set if TXT errors should be ignored ("GRPC_GO_IGNORE_TXT_ERRORS" is not "false"). TXTErrIgnore = !strings.EqualFold(os.Getenv(txtErrIgnoreStr), "false") ) diff --git a/vendor/google.golang.org/grpc/internal/envconfig/xds.go b/vendor/google.golang.org/grpc/internal/envconfig/xds.go new file mode 100644 index 000000000000..7d996e51b5c1 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/envconfig/xds.go @@ -0,0 +1,101 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package envconfig + +import ( + "os" + "strings" +) + +const ( + // XDSBootstrapFileNameEnv is the env variable to set bootstrap file name. + // Do not use this and read from env directly. Its value is read and kept in + // variable XDSBootstrapFileName. + // + // When both bootstrap FileName and FileContent are set, FileName is used. + XDSBootstrapFileNameEnv = "GRPC_XDS_BOOTSTRAP" + // XDSBootstrapFileContentEnv is the env variable to set bootstrap file + // content. Do not use this and read from env directly. Its value is read + // and kept in variable XDSBootstrapFileContent. + // + // When both bootstrap FileName and FileContent are set, FileName is used. + XDSBootstrapFileContentEnv = "GRPC_XDS_BOOTSTRAP_CONFIG" + + ringHashSupportEnv = "GRPC_XDS_EXPERIMENTAL_ENABLE_RING_HASH" + clientSideSecuritySupportEnv = "GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT" + aggregateAndDNSSupportEnv = "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER" + rbacSupportEnv = "GRPC_XDS_EXPERIMENTAL_RBAC" + outlierDetectionSupportEnv = "GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION" + federationEnv = "GRPC_EXPERIMENTAL_XDS_FEDERATION" + rlsInXDSEnv = "GRPC_EXPERIMENTAL_XDS_RLS_LB" + + c2pResolverTestOnlyTrafficDirectorURIEnv = "GRPC_TEST_ONLY_GOOGLE_C2P_RESOLVER_TRAFFIC_DIRECTOR_URI" +) + +var ( + // XDSBootstrapFileName holds the name of the file which contains xDS + // bootstrap configuration. Users can specify the location of the bootstrap + // file by setting the environment variable "GRPC_XDS_BOOTSTRAP". + // + // When both bootstrap FileName and FileContent are set, FileName is used. + XDSBootstrapFileName = os.Getenv(XDSBootstrapFileNameEnv) + // XDSBootstrapFileContent holds the content of the xDS bootstrap + // configuration. Users can specify the bootstrap config by setting the + // environment variable "GRPC_XDS_BOOTSTRAP_CONFIG". + // + // When both bootstrap FileName and FileContent are set, FileName is used. + XDSBootstrapFileContent = os.Getenv(XDSBootstrapFileContentEnv) + // XDSRingHash indicates whether ring hash support is enabled, which can be + // disabled by setting the environment variable + // "GRPC_XDS_EXPERIMENTAL_ENABLE_RING_HASH" to "false". + XDSRingHash = !strings.EqualFold(os.Getenv(ringHashSupportEnv), "false") + // XDSClientSideSecurity is used to control processing of security + // configuration on the client-side. + // + // Note that there is no env var protection for the server-side because we + // have a brand new API on the server-side and users explicitly need to use + // the new API to get security integration on the server. + XDSClientSideSecurity = !strings.EqualFold(os.Getenv(clientSideSecuritySupportEnv), "false") + // XDSAggregateAndDNS indicates whether processing of aggregated cluster + // and DNS cluster is enabled, which can be enabled by setting the + // environment variable + // "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER" to + // "true". + XDSAggregateAndDNS = strings.EqualFold(os.Getenv(aggregateAndDNSSupportEnv), "true") + + // XDSRBAC indicates whether xDS configured RBAC HTTP Filter is enabled, + // which can be disabled by setting the environment variable + // "GRPC_XDS_EXPERIMENTAL_RBAC" to "false". + XDSRBAC = !strings.EqualFold(os.Getenv(rbacSupportEnv), "false") + // XDSOutlierDetection indicates whether outlier detection support is + // enabled, which can be enabled by setting the environment variable + // "GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION" to "true". + XDSOutlierDetection = strings.EqualFold(os.Getenv(outlierDetectionSupportEnv), "true") + // XDSFederation indicates whether federation support is enabled. + XDSFederation = strings.EqualFold(os.Getenv(federationEnv), "true") + + // XDSRLS indicates whether processing of Cluster Specifier plugins and + // support for the RLS CLuster Specifier is enabled, which can be enabled by + // setting the environment variable "GRPC_EXPERIMENTAL_XDS_RLS_LB" to + // "true". + XDSRLS = strings.EqualFold(os.Getenv(rlsInXDSEnv), "true") + + // C2PResolverTestOnlyTrafficDirectorURI is the TD URI for testing. + C2PResolverTestOnlyTrafficDirectorURI = os.Getenv(c2pResolverTestOnlyTrafficDirectorURIEnv) +) diff --git a/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go b/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go index e6f975cbf6a8..30a3b4258fc0 100644 --- a/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go +++ b/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go @@ -115,12 +115,12 @@ type LoggerV2 interface { // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type DepthLoggerV2 interface { - // InfoDepth logs to INFO log at the specified depth. Arguments are handled in the manner of fmt.Print. + // InfoDepth logs to INFO log at the specified depth. Arguments are handled in the manner of fmt.Println. InfoDepth(depth int, args ...interface{}) - // WarningDepth logs to WARNING log at the specified depth. Arguments are handled in the manner of fmt.Print. + // WarningDepth logs to WARNING log at the specified depth. Arguments are handled in the manner of fmt.Println. WarningDepth(depth int, args ...interface{}) - // ErrorDetph logs to ERROR log at the specified depth. Arguments are handled in the manner of fmt.Print. + // ErrorDepth logs to ERROR log at the specified depth. Arguments are handled in the manner of fmt.Println. ErrorDepth(depth int, args ...interface{}) - // FatalDepth logs to FATAL log at the specified depth. Arguments are handled in the manner of fmt.Print. + // FatalDepth logs to FATAL log at the specified depth. Arguments are handled in the manner of fmt.Println. FatalDepth(depth int, args ...interface{}) } diff --git a/vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go b/vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go index 7bc3583b5fcc..740f83c2b766 100644 --- a/vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go +++ b/vendor/google.golang.org/grpc/internal/grpcrand/grpcrand.go @@ -58,3 +58,10 @@ func Float64() float64 { defer mu.Unlock() return r.Float64() } + +// Uint64 implements rand.Uint64 on the grpcrand global source. +func Uint64() uint64 { + mu.Lock() + defer mu.Unlock() + return r.Uint64() +} diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/grpcutil.go b/vendor/google.golang.org/grpc/internal/grpcutil/grpcutil.go new file mode 100644 index 000000000000..e2f948e8f4f4 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpcutil/grpcutil.go @@ -0,0 +1,20 @@ +/* + * + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package grpcutil provides utility functions used across the gRPC codebase. +package grpcutil diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/regex.go b/vendor/google.golang.org/grpc/internal/grpcutil/regex.go new file mode 100644 index 000000000000..7a092b2b8041 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpcutil/regex.go @@ -0,0 +1,31 @@ +/* + * + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpcutil + +import "regexp" + +// FullMatchWithRegex returns whether the full text matches the regex provided. +func FullMatchWithRegex(re *regexp.Regexp, text string) bool { + if len(text) == 0 { + return re.MatchString(text) + } + re.Longest() + rem := re.FindString(text) + return len(rem) == len(text) +} diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go index 1b596bf3579f..6d355b0b0134 100644 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ b/vendor/google.golang.org/grpc/internal/internal.go @@ -38,11 +38,10 @@ var ( // KeepaliveMinPingTime is the minimum ping interval. This must be 10s by // default, but tests may wish to set it lower for convenience. KeepaliveMinPingTime = 10 * time.Second - // ParseServiceConfigForTesting is for creating a fake - // ClientConn for resolver testing only - ParseServiceConfigForTesting interface{} // func(string) *serviceconfig.ParseResult + // ParseServiceConfig parses a JSON representation of the service config. + ParseServiceConfig interface{} // func(string) *serviceconfig.ParseResult // EqualServiceConfigForTesting is for testing service config generation and - // parsing. Both a and b should be returned by ParseServiceConfigForTesting. + // parsing. Both a and b should be returned by ParseServiceConfig. // This function compares the config without rawJSON stripped, in case the // there's difference in white space. EqualServiceConfigForTesting func(a, b serviceconfig.Config) bool @@ -86,3 +85,9 @@ const ( // that supports backend returned by grpclb balancer. CredsBundleModeBackendFromBalancer = "backend-from-balancer" ) + +// RLSLoadBalancingPolicyName is the name of the RLS LB policy. +// +// It currently has an experimental suffix which would be removed once +// end-to-end testing of the policy is completed. +const RLSLoadBalancingPolicyName = "rls_experimental" diff --git a/vendor/google.golang.org/grpc/internal/metadata/metadata.go b/vendor/google.golang.org/grpc/internal/metadata/metadata.go index 302262613a02..b2980f8ac44a 100644 --- a/vendor/google.golang.org/grpc/internal/metadata/metadata.go +++ b/vendor/google.golang.org/grpc/internal/metadata/metadata.go @@ -22,6 +22,9 @@ package metadata import ( + "fmt" + "strings" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/resolver" ) @@ -30,14 +33,38 @@ type mdKeyType string const mdKey = mdKeyType("grpc.internal.address.metadata") +type mdValue metadata.MD + +func (m mdValue) Equal(o interface{}) bool { + om, ok := o.(mdValue) + if !ok { + return false + } + if len(m) != len(om) { + return false + } + for k, v := range m { + ov := om[k] + if len(ov) != len(v) { + return false + } + for i, ve := range v { + if ov[i] != ve { + return false + } + } + } + return true +} + // Get returns the metadata of addr. func Get(addr resolver.Address) metadata.MD { attrs := addr.Attributes if attrs == nil { return nil } - md, _ := attrs.Value(mdKey).(metadata.MD) - return md + md, _ := attrs.Value(mdKey).(mdValue) + return metadata.MD(md) } // Set sets (overrides) the metadata in addr. @@ -45,6 +72,49 @@ func Get(addr resolver.Address) metadata.MD { // When a SubConn is created with this address, the RPCs sent on it will all // have this metadata. func Set(addr resolver.Address, md metadata.MD) resolver.Address { - addr.Attributes = addr.Attributes.WithValues(mdKey, md) + addr.Attributes = addr.Attributes.WithValue(mdKey, mdValue(md)) return addr } + +// Validate returns an error if the input md contains invalid keys or values. +// +// If the header is not a pseudo-header, the following items are checked: +// - header names must contain one or more characters from this set [0-9 a-z _ - .]. +// - if the header-name ends with a "-bin" suffix, no validation of the header value is performed. +// - otherwise, the header value must contain one or more characters from the set [%x20-%x7E]. +func Validate(md metadata.MD) error { + for k, vals := range md { + // pseudo-header will be ignored + if k[0] == ':' { + continue + } + // check key, for i that saving a conversion if not using for range + for i := 0; i < len(k); i++ { + r := k[i] + if !(r >= 'a' && r <= 'z') && !(r >= '0' && r <= '9') && r != '.' && r != '-' && r != '_' { + return fmt.Errorf("header key %q contains illegal characters not in [0-9a-z-_.]", k) + } + } + if strings.HasSuffix(k, "-bin") { + continue + } + // check value + for _, val := range vals { + if hasNotPrintable(val) { + return fmt.Errorf("header key %q contains value with non-printable ASCII characters", k) + } + } + } + return nil +} + +// hasNotPrintable return true if msg contains any characters which are not in %x20-%x7E +func hasNotPrintable(msg string) bool { + // for i that saving a conversion if not using for range + for i := 0; i < len(msg); i++ { + if msg[i] < 0x20 || msg[i] > 0x7E { + return true + } + } + return false +} diff --git a/vendor/google.golang.org/grpc/internal/pretty/pretty.go b/vendor/google.golang.org/grpc/internal/pretty/pretty.go new file mode 100644 index 000000000000..0177af4b5114 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/pretty/pretty.go @@ -0,0 +1,82 @@ +/* + * + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package pretty defines helper functions to pretty-print structs for logging. +package pretty + +import ( + "bytes" + "encoding/json" + "fmt" + + "github.com/golang/protobuf/jsonpb" + protov1 "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/encoding/protojson" + protov2 "google.golang.org/protobuf/proto" +) + +const jsonIndent = " " + +// ToJSON marshals the input into a json string. +// +// If marshal fails, it falls back to fmt.Sprintf("%+v"). +func ToJSON(e interface{}) string { + switch ee := e.(type) { + case protov1.Message: + mm := jsonpb.Marshaler{Indent: jsonIndent} + ret, err := mm.MarshalToString(ee) + if err != nil { + // This may fail for proto.Anys, e.g. for xDS v2, LDS, the v2 + // messages are not imported, and this will fail because the message + // is not found. + return fmt.Sprintf("%+v", ee) + } + return ret + case protov2.Message: + mm := protojson.MarshalOptions{ + Multiline: true, + Indent: jsonIndent, + } + ret, err := mm.Marshal(ee) + if err != nil { + // This may fail for proto.Anys, e.g. for xDS v2, LDS, the v2 + // messages are not imported, and this will fail because the message + // is not found. + return fmt.Sprintf("%+v", ee) + } + return string(ret) + default: + ret, err := json.MarshalIndent(ee, "", jsonIndent) + if err != nil { + return fmt.Sprintf("%+v", ee) + } + return string(ret) + } +} + +// FormatJSON formats the input json bytes with indentation. +// +// If Indent fails, it returns the unchanged input as string. +func FormatJSON(b []byte) string { + var out bytes.Buffer + err := json.Indent(&out, b, "", jsonIndent) + if err != nil { + return string(b) + } + return out.String() +} diff --git a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go index 5e7f36703d4b..c7a18a948adb 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go +++ b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go @@ -117,9 +117,12 @@ type ClientInterceptor interface { NewStream(ctx context.Context, ri RPCInfo, done func(), newStream func(ctx context.Context, done func()) (ClientStream, error)) (ClientStream, error) } -// ServerInterceptor is unimplementable; do not use. +// ServerInterceptor is an interceptor for incoming RPC's on gRPC server side. type ServerInterceptor interface { - notDefined() + // AllowRPC checks if an incoming RPC is allowed to proceed based on + // information about connection RPC was received on, and HTTP Headers. This + // information will be piped into context. + AllowRPC(ctx context.Context) error // TODO: Make this a real interceptor for filters such as rate limiting. } type csKeyType string @@ -129,7 +132,7 @@ const csKey = csKeyType("grpc.internal.resolver.configSelector") // SetConfigSelector sets the config selector in state and returns the new // state. func SetConfigSelector(state resolver.State, cs ConfigSelector) resolver.State { - state.Attributes = state.Attributes.WithValues(csKey, cs) + state.Attributes = state.Attributes.WithValue(csKey, cs) return state } diff --git a/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go b/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go index 03825bbe7b56..75301c514913 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go +++ b/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go @@ -277,18 +277,13 @@ func (d *dnsResolver) lookupSRV() ([]resolver.Address, error) { return newAddrs, nil } -var filterError = func(err error) error { +func handleDNSError(err error, lookupType string) error { if dnsErr, ok := err.(*net.DNSError); ok && !dnsErr.IsTimeout && !dnsErr.IsTemporary { // Timeouts and temporary errors should be communicated to gRPC to // attempt another DNS query (with backoff). Other errors should be // suppressed (they may represent the absence of a TXT record). return nil } - return err -} - -func handleDNSError(err error, lookupType string) error { - err = filterError(err) if err != nil { err = fmt.Errorf("dns: %v record lookup error: %v", lookupType, err) logger.Info(err) @@ -323,12 +318,12 @@ func (d *dnsResolver) lookupTXT() *serviceconfig.ParseResult { } func (d *dnsResolver) lookupHost() ([]resolver.Address, error) { - var newAddrs []resolver.Address addrs, err := d.resolver.LookupHost(d.ctx, d.host) if err != nil { err = handleDNSError(err, "A") return nil, err } + newAddrs := make([]resolver.Address, 0, len(addrs)) for _, a := range addrs { ip, ok := formatIP(a) if !ok { diff --git a/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go b/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go index 0d5a811ddfad..20852e59df29 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go +++ b/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go @@ -37,7 +37,17 @@ func (b *builder) Build(target resolver.Target, cc resolver.ClientConn, _ resolv if target.Authority != "" { return nil, fmt.Errorf("invalid (non-empty) authority: %v", target.Authority) } - addr := resolver.Address{Addr: target.Endpoint} + + // gRPC was parsing the dial target manually before PR #4817, and we + // switched to using url.Parse() in that PR. To avoid breaking existing + // resolver implementations we ended up stripping the leading "/" from the + // endpoint. This obviously does not work for the "unix" scheme. Hence we + // end up using the parsed URL instead. + endpoint := target.URL.Path + if endpoint == "" { + endpoint = target.URL.Opaque + } + addr := resolver.Address{Addr: endpoint} if b.scheme == unixAbstractScheme { // prepend "\x00" to address for unix-abstract addr.Addr = "\x00" + addr.Addr diff --git a/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go b/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go index c0634d152c2e..badbdbf597f3 100644 --- a/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go +++ b/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go @@ -78,6 +78,7 @@ func (bc *BalancerConfig) UnmarshalJSON(b []byte) error { return err } + var names []string for i, lbcfg := range ir { if len(lbcfg) != 1 { return fmt.Errorf("invalid loadBalancingConfig: entry %v does not contain exactly 1 policy/config pair: %q", i, lbcfg) @@ -92,6 +93,7 @@ func (bc *BalancerConfig) UnmarshalJSON(b []byte) error { for name, jsonCfg = range lbcfg { } + names = append(names, name) builder := balancer.Get(name) if builder == nil { // If the balancer is not registered, move on to the next config. @@ -120,7 +122,7 @@ func (bc *BalancerConfig) UnmarshalJSON(b []byte) error { // return. This means we had a loadBalancingConfig slice but did not // encounter a registered policy. The config is considered invalid in this // case. - return fmt.Errorf("invalid loadBalancingConfig: no supported policies found") + return fmt.Errorf("invalid loadBalancingConfig: no supported policies found in %v", names) } // MethodConfig defines the configuration recommended by the service providers for a diff --git a/vendor/google.golang.org/grpc/internal/status/status.go b/vendor/google.golang.org/grpc/internal/status/status.go index 710223b8ded0..e5c6513edd13 100644 --- a/vendor/google.golang.org/grpc/internal/status/status.go +++ b/vendor/google.golang.org/grpc/internal/status/status.go @@ -97,7 +97,7 @@ func (s *Status) Err() error { if s.Code() == codes.OK { return nil } - return &Error{e: s.Proto()} + return &Error{s: s} } // WithDetails returns a new status with the provided details messages appended to the status. @@ -136,19 +136,23 @@ func (s *Status) Details() []interface{} { return details } +func (s *Status) String() string { + return fmt.Sprintf("rpc error: code = %s desc = %s", s.Code(), s.Message()) +} + // Error wraps a pointer of a status proto. It implements error and Status, // and a nil *Error should never be returned by this package. type Error struct { - e *spb.Status + s *Status } func (e *Error) Error() string { - return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(e.e.GetCode()), e.e.GetMessage()) + return e.s.String() } // GRPCStatus returns the Status represented by se. func (e *Error) GRPCStatus() *Status { - return FromProto(e.e) + return e.s } // Is implements future error.Is functionality. @@ -158,5 +162,5 @@ func (e *Error) Is(target error) bool { if !ok { return false } - return proto.Equal(e.e, tse.e) + return proto.Equal(e.s.s, tse.s.s) } diff --git a/vendor/google.golang.org/grpc/internal/syscall/syscall_linux.go b/vendor/google.golang.org/grpc/internal/syscall/syscall_linux.go index 4b2964f2a1e3..b3a72276dee4 100644 --- a/vendor/google.golang.org/grpc/internal/syscall/syscall_linux.go +++ b/vendor/google.golang.org/grpc/internal/syscall/syscall_linux.go @@ -1,5 +1,3 @@ -// +build !appengine - /* * * Copyright 2018 gRPC authors. diff --git a/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go b/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go index 7913ef1dbfb5..999f52cd75bd 100644 --- a/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go +++ b/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go @@ -1,4 +1,5 @@ -// +build !linux appengine +//go:build !linux +// +build !linux /* * @@ -35,41 +36,41 @@ var logger = grpclog.Component("core") func log() { once.Do(func() { - logger.Info("CPU time info is unavailable on non-linux or appengine environment.") + logger.Info("CPU time info is unavailable on non-linux environments.") }) } -// GetCPUTime returns the how much CPU time has passed since the start of this process. -// It always returns 0 under non-linux or appengine environment. +// GetCPUTime returns the how much CPU time has passed since the start of this +// process. It always returns 0 under non-linux environments. func GetCPUTime() int64 { log() return 0 } -// Rusage is an empty struct under non-linux or appengine environment. +// Rusage is an empty struct under non-linux environments. type Rusage struct{} -// GetRusage is a no-op function under non-linux or appengine environment. +// GetRusage is a no-op function under non-linux environments. func GetRusage() *Rusage { log() return nil } // CPUTimeDiff returns the differences of user CPU time and system CPU time used -// between two Rusage structs. It a no-op function for non-linux or appengine environment. +// between two Rusage structs. It a no-op function for non-linux environments. func CPUTimeDiff(first *Rusage, latest *Rusage) (float64, float64) { log() return 0, 0 } -// SetTCPUserTimeout is a no-op function under non-linux or appengine environments +// SetTCPUserTimeout is a no-op function under non-linux environments. func SetTCPUserTimeout(conn net.Conn, timeout time.Duration) error { log() return nil } -// GetTCPUserTimeout is a no-op function under non-linux or appengine environments -// a negative return value indicates the operation is not supported +// GetTCPUserTimeout is a no-op function under non-linux environments. +// A negative return value indicates the operation is not supported func GetTCPUserTimeout(conn net.Conn) (int, error) { log() return -1, nil diff --git a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go index 45532f8aeaab..244f4b081d52 100644 --- a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go +++ b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go @@ -133,9 +133,11 @@ type cleanupStream struct { func (c *cleanupStream) isTransportResponseFrame() bool { return c.rst } // Results in a RST_STREAM type earlyAbortStream struct { + httpStatus uint32 streamID uint32 contentSubtype string status *status.Status + rst bool } func (*earlyAbortStream) isTransportResponseFrame() bool { return false } @@ -771,9 +773,12 @@ func (l *loopyWriter) earlyAbortStreamHandler(eas *earlyAbortStream) error { if l.side == clientSide { return errors.New("earlyAbortStream not handled on client") } - + // In case the caller forgets to set the http status, default to 200. + if eas.httpStatus == 0 { + eas.httpStatus = 200 + } headerFields := []hpack.HeaderField{ - {Name: ":status", Value: "200"}, + {Name: ":status", Value: strconv.Itoa(int(eas.httpStatus))}, {Name: "content-type", Value: grpcutil.ContentType(eas.contentSubtype)}, {Name: "grpc-status", Value: strconv.Itoa(int(eas.status.Code()))}, {Name: "grpc-message", Value: encodeGrpcMessage(eas.status.Message())}, @@ -782,6 +787,11 @@ func (l *loopyWriter) earlyAbortStreamHandler(eas *earlyAbortStream) error { if err := l.writeHeader(eas.streamID, true, headerFields, nil); err != nil { return err } + if eas.rst { + if err := l.framer.fr.WriteRSTStream(eas.streamID, http2.ErrCodeNo); err != nil { + return err + } + } return nil } diff --git a/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go b/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go index f262edd8ecda..97198c515889 100644 --- a/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go +++ b/vendor/google.golang.org/grpc/internal/transport/flowcontrol.go @@ -136,12 +136,10 @@ type inFlow struct { // newLimit updates the inflow window to a new value n. // It assumes that n is always greater than the old limit. -func (f *inFlow) newLimit(n uint32) uint32 { +func (f *inFlow) newLimit(n uint32) { f.mu.Lock() - d := n - f.limit f.limit = n f.mu.Unlock() - return d } func (f *inFlow) maybeAdjust(n uint32) uint32 { diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/vendor/google.golang.org/grpc/internal/transport/http2_client.go index d10b6aacbcfe..24ca59084b43 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -24,6 +24,8 @@ import ( "io" "math" "net" + "net/http" + "path/filepath" "strconv" "strings" "sync" @@ -130,7 +132,7 @@ type http2Client struct { kpDormant bool // Fields below are for channelz metric collection. - channelzID int64 // channelz unique identification number + channelzID *channelz.Identifier czData *channelzData onGoAway func(GoAwayReason) @@ -145,13 +147,20 @@ func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error address := addr.Addr networkType, ok := networktype.Get(addr) if fn != nil { + // Special handling for unix scheme with custom dialer. Back in the day, + // we did not have a unix resolver and therefore targets with a unix + // scheme would end up using the passthrough resolver. So, user's used a + // custom dialer in this case and expected the original dial target to + // be passed to the custom dialer. Now, we have a unix resolver. But if + // a custom dialer is specified, we want to retain the old behavior in + // terms of the address being passed to the custom dialer. if networkType == "unix" && !strings.HasPrefix(address, "\x00") { - // For backward compatibility, if the user dialed "unix:///path", - // the passthrough resolver would be used and the user's custom - // dialer would see "unix:///path". Since the unix resolver is used - // and the address is now "/path", prepend "unix://" so the user's - // custom dialer sees the same address. - return fn(ctx, "unix://"+address) + // Supported unix targets are either "unix://absolute-path" or + // "unix:relative-path". + if filepath.IsAbs(address) { + return fn(ctx, "unix://"+address) + } + return fn(ctx, "unix:"+address) } return fn(ctx, address) } @@ -192,6 +201,12 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts } }() + // gRPC, resolver, balancer etc. can specify arbitrary data in the + // Attributes field of resolver.Address, which is shoved into connectCtx + // and passed to the dialer and credential handshaker. This makes it possible for + // address specific arbitrary data to reach custom dialers and credential handshakers. + connectCtx = icredentials.NewClientHandshakeInfoContext(connectCtx, credentials.ClientHandshakeInfo{Attributes: addr.Attributes}) + conn, err := dial(connectCtx, opts.Dialer, addr, opts.UseProxy, opts.UserAgent) if err != nil { if opts.FailOnNonTempDialError { @@ -236,12 +251,15 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts } } if transportCreds != nil { - // gRPC, resolver, balancer etc. can specify arbitrary data in the - // Attributes field of resolver.Address, which is shoved into connectCtx - // and passed to the credential handshaker. This makes it possible for - // address specific arbitrary data to reach the credential handshaker. - connectCtx = icredentials.NewClientHandshakeInfoContext(connectCtx, credentials.ClientHandshakeInfo{Attributes: addr.Attributes}) - conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.ServerName, conn) + rawConn := conn + // Pull the deadline from the connectCtx, which will be used for + // timeouts in the authentication protocol handshake. Can ignore the + // boolean as the deadline will return the zero value, which will make + // the conn not timeout on I/O operations. + deadline, _ := connectCtx.Deadline() + rawConn.SetDeadline(deadline) + conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.ServerName, rawConn) + rawConn.SetDeadline(time.Time{}) if err != nil { return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err) } @@ -333,8 +351,9 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts } t.statsHandler.HandleConn(t.ctx, connBegin) } - if channelz.IsOn() { - t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, fmt.Sprintf("%s -> %s", t.localAddr, t.remoteAddr)) + t.channelzID, err = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, fmt.Sprintf("%s -> %s", t.localAddr, t.remoteAddr)) + if err != nil { + return nil, err } if t.keepaliveEnabled { t.kpDormancyCond = sync.NewCond(&t.mu) @@ -570,7 +589,7 @@ func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[s return nil, err } - return nil, status.Errorf(codes.Unauthenticated, "transport: %v", err) + return nil, status.Errorf(codes.Unauthenticated, "transport: per-RPC creds failed due to error: %v", err) } for k, v := range data { // Capital header names are illegal in HTTP/2. @@ -607,26 +626,34 @@ func (t *http2Client) getCallAuthData(ctx context.Context, audience string, call return callAuthData, nil } -// PerformedIOError wraps an error to indicate IO may have been performed -// before the error occurred. -type PerformedIOError struct { +// NewStreamError wraps an error and reports additional information. Typically +// NewStream errors result in transparent retry, as they mean nothing went onto +// the wire. However, there are two notable exceptions: +// +// 1. If the stream headers violate the max header list size allowed by the +// server. It's possible this could succeed on another transport, even if +// it's unlikely, but do not transparently retry. +// 2. If the credentials errored when requesting their headers. In this case, +// it's possible a retry can fix the problem, but indefinitely transparently +// retrying is not appropriate as it is likely the credentials, if they can +// eventually succeed, would need I/O to do so. +type NewStreamError struct { Err error + + AllowTransparentRetry bool } -// Error implements error. -func (p PerformedIOError) Error() string { - return p.Err.Error() +func (e NewStreamError) Error() string { + return e.Err.Error() } // NewStream creates a stream and registers it into the transport as "active" -// streams. -func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) { +// streams. All non-nil errors returned will be *NewStreamError. +func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error) { ctx = peer.NewContext(ctx, t.getPeer()) headerFields, err := t.createHeaderFields(ctx, callHdr) if err != nil { - // We may have performed I/O in the per-RPC creds callback, so do not - // allow transparent retry. - return nil, PerformedIOError{err} + return nil, &NewStreamError{Err: err, AllowTransparentRetry: false} } s := t.newStream(ctx, callHdr) cleanup := func(err error) { @@ -726,23 +753,24 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea return true }, hdr) if err != nil { - return nil, err + // Connection closed. + return nil, &NewStreamError{Err: err, AllowTransparentRetry: true} } if success { break } if hdrListSizeErr != nil { - return nil, hdrListSizeErr + return nil, &NewStreamError{Err: hdrListSizeErr} } firstTry = false select { case <-ch: - case <-s.ctx.Done(): - return nil, ContextErr(s.ctx.Err()) + case <-ctx.Done(): + return nil, &NewStreamError{Err: ContextErr(ctx.Err())} case <-t.goAway: - return nil, errStreamDrain + return nil, &NewStreamError{Err: errStreamDrain, AllowTransparentRetry: true} case <-t.ctx.Done(): - return nil, ErrConnClosing + return nil, &NewStreamError{Err: ErrConnClosing, AllowTransparentRetry: true} } } if t.statsHandler != nil { @@ -871,9 +899,7 @@ func (t *http2Client) Close(err error) { t.controlBuf.finish() t.cancel() t.conn.Close() - if channelz.IsOn() { - channelz.RemoveEntry(t.channelzID) - } + channelz.RemoveEntry(t.channelzID) // Append info about previous goaways if there were any, since this may be important // for understanding the root cause for this connection to be closed. _, goAwayDebugMessage := t.GetGoAwayReason() @@ -1055,7 +1081,7 @@ func (t *http2Client) handleData(f *http2.DataFrame) { } // The server has closed the stream without sending trailers. Record that // the read direction is closed, and set the status appropriately. - if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) { + if f.StreamEnded() { t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true) } } @@ -1226,7 +1252,11 @@ func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) { t.goAwayReason = GoAwayTooManyPings } } - t.goAwayDebugMessage = fmt.Sprintf("code: %s, debug data: %v", f.ErrCode, string(f.DebugData())) + if len(f.DebugData()) == 0 { + t.goAwayDebugMessage = fmt.Sprintf("code: %s", f.ErrCode) + } else { + t.goAwayDebugMessage = fmt.Sprintf("code: %s, debug data: %q", f.ErrCode, string(f.DebugData())) + } } func (t *http2Client) GetGoAwayReason() (GoAwayReason, string) { @@ -1272,29 +1302,41 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { // that the peer is speaking gRPC and we are in gRPC mode. isGRPC = !initialHeader mdata = make(map[string][]string) - contentTypeErr string + contentTypeErr = "malformed header: missing HTTP content-type" grpcMessage string statusGen *status.Status - - httpStatus string - rawStatus string + recvCompress string + httpStatusCode *int + httpStatusErr string + rawStatusCode = codes.Unknown // headerError is set if an error is encountered while parsing the headers headerError string ) + if initialHeader { + httpStatusErr = "malformed header: missing HTTP status" + } + for _, hf := range frame.Fields { switch hf.Name { case "content-type": if _, validContentType := grpcutil.ContentSubtype(hf.Value); !validContentType { - contentTypeErr = fmt.Sprintf("transport: received the unexpected content-type %q", hf.Value) + contentTypeErr = fmt.Sprintf("transport: received unexpected content-type %q", hf.Value) break } + contentTypeErr = "" mdata[hf.Name] = append(mdata[hf.Name], hf.Value) isGRPC = true case "grpc-encoding": - s.recvCompress = hf.Value + recvCompress = hf.Value case "grpc-status": - rawStatus = hf.Value + code, err := strconv.ParseInt(hf.Value, 10, 32) + if err != nil { + se := status.New(codes.Internal, fmt.Sprintf("transport: malformed grpc-status: %v", err)) + t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream) + return + } + rawStatusCode = codes.Code(uint32(code)) case "grpc-message": grpcMessage = decodeGrpcMessage(hf.Value) case "grpc-status-details-bin": @@ -1304,7 +1346,27 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { headerError = fmt.Sprintf("transport: malformed grpc-status-details-bin: %v", err) } case ":status": - httpStatus = hf.Value + if hf.Value == "200" { + httpStatusErr = "" + statusCode := 200 + httpStatusCode = &statusCode + break + } + + c, err := strconv.ParseInt(hf.Value, 10, 32) + if err != nil { + se := status.New(codes.Internal, fmt.Sprintf("transport: malformed http-status: %v", err)) + t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream) + return + } + statusCode := int(c) + httpStatusCode = &statusCode + + httpStatusErr = fmt.Sprintf( + "unexpected HTTP status code received from server: %d (%s)", + statusCode, + http.StatusText(statusCode), + ) default: if isReservedHeader(hf.Name) && !isWhitelistedHeader(hf.Name) { break @@ -1319,30 +1381,25 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { } } - if !isGRPC { - var ( - code = codes.Internal // when header does not include HTTP status, return INTERNAL - httpStatusCode int - ) - - if httpStatus != "" { - c, err := strconv.ParseInt(httpStatus, 10, 32) - if err != nil { - se := status.New(codes.Internal, fmt.Sprintf("transport: malformed http-status: %v", err)) - t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream) - return - } - httpStatusCode = int(c) + if !isGRPC || httpStatusErr != "" { + var code = codes.Internal // when header does not include HTTP status, return INTERNAL + if httpStatusCode != nil { var ok bool - code, ok = HTTPStatusConvTab[httpStatusCode] + code, ok = HTTPStatusConvTab[*httpStatusCode] if !ok { code = codes.Unknown } } - + var errs []string + if httpStatusErr != "" { + errs = append(errs, httpStatusErr) + } + if contentTypeErr != "" { + errs = append(errs, contentTypeErr) + } // Verify the HTTP response is a 200. - se := status.New(code, constructHTTPErrMsg(&httpStatusCode, contentTypeErr)) + se := status.New(code, strings.Join(errs, "; ")) t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream) return } @@ -1354,26 +1411,6 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { } isHeader := false - defer func() { - if t.statsHandler != nil { - if isHeader { - inHeader := &stats.InHeader{ - Client: true, - WireLength: int(frame.Header().Length), - Header: s.header.Copy(), - Compression: s.recvCompress, - } - t.statsHandler.HandleRPC(s.ctx, inHeader) - } else { - inTrailer := &stats.InTrailer{ - Client: true, - WireLength: int(frame.Header().Length), - Trailer: s.trailer.Copy(), - } - t.statsHandler.HandleRPC(s.ctx, inTrailer) - } - } - }() // If headerChan hasn't been closed yet if atomic.CompareAndSwapUint32(&s.headerChanClosed, 0, 1) { @@ -1384,6 +1421,7 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { // These values can be set without any synchronization because // stream goroutine will read it only after seeing a closed // headerChan which we'll close after setting this. + s.recvCompress = recvCompress if len(mdata) > 0 { s.header = mdata } @@ -1394,21 +1432,30 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { close(s.headerChan) } + if t.statsHandler != nil { + if isHeader { + inHeader := &stats.InHeader{ + Client: true, + WireLength: int(frame.Header().Length), + Header: metadata.MD(mdata).Copy(), + Compression: s.recvCompress, + } + t.statsHandler.HandleRPC(s.ctx, inHeader) + } else { + inTrailer := &stats.InTrailer{ + Client: true, + WireLength: int(frame.Header().Length), + Trailer: metadata.MD(mdata).Copy(), + } + t.statsHandler.HandleRPC(s.ctx, inTrailer) + } + } + if !endStream { return } if statusGen == nil { - rawStatusCode := codes.Unknown - if rawStatus != "" { - code, err := strconv.ParseInt(rawStatus, 10, 32) - if err != nil { - se := status.New(codes.Internal, fmt.Sprintf("transport: malformed grpc-status: %v", err)) - t.closeStream(s, se.Err(), true, http2.ErrCodeProtocol, se, nil, endStream) - return - } - rawStatusCode = codes.Code(uint32(code)) - } statusGen = status.New(rawStatusCode, grpcMessage) } @@ -1509,7 +1556,7 @@ func minTime(a, b time.Duration) time.Duration { return b } -// keepalive running in a separate goroutune makes sure the connection is alive by sending pings. +// keepalive running in a separate goroutine makes sure the connection is alive by sending pings. func (t *http2Client) keepalive() { p := &ping{data: [8]byte{}} // True iff a ping has been sent, and no data has been received since then. diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/vendor/google.golang.org/grpc/internal/transport/http2_server.go index e3799d50aa71..45d7bd145e3e 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -21,7 +21,6 @@ package transport import ( "bytes" "context" - "errors" "fmt" "io" "math" @@ -36,6 +35,7 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" "google.golang.org/grpc/internal/grpcutil" + "google.golang.org/grpc/internal/syscall" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" @@ -52,10 +52,10 @@ import ( var ( // ErrIllegalHeaderWrite indicates that setting header is illegal because of // the stream's state. - ErrIllegalHeaderWrite = errors.New("transport: the stream is done or WriteHeader was already called") + ErrIllegalHeaderWrite = status.Error(codes.Internal, "transport: SendHeader called multiple times") // ErrHeaderListSizeLimitViolation indicates that the header list size is larger // than the limit set by peer. - ErrHeaderListSizeLimitViolation = errors.New("transport: trying to send header list size larger than the limit set by peer") + ErrHeaderListSizeLimitViolation = status.Error(codes.Internal, "transport: trying to send header list size larger than the limit set by peer") ) // serverConnectionCounter counts the number of connections a server has seen @@ -73,7 +73,6 @@ type http2Server struct { writerDone chan struct{} // sync point to enable testing. remoteAddr net.Addr localAddr net.Addr - maxStreamID uint32 // max stream ID ever seen authInfo credentials.AuthInfo // auth info about the connection inTapHandle tap.ServerInHandle framer *framer @@ -118,21 +117,42 @@ type http2Server struct { idle time.Time // Fields below are for channelz metric collection. - channelzID int64 // channelz unique identification number + channelzID *channelz.Identifier czData *channelzData bufferPool *bufferPool connectionID uint64 + + // maxStreamMu guards the maximum stream ID + // This lock may not be taken if mu is already held. + maxStreamMu sync.Mutex + maxStreamID uint32 // max stream ID ever seen } // NewServerTransport creates a http2 transport with conn and configuration // options from config. // // It returns a non-nil transport and a nil error on success. On failure, it -// returns a non-nil transport and a nil-error. For a special case where the +// returns a nil transport and a non-nil error. For a special case where the // underlying conn gets closed before the client preface could be read, it // returns a nil transport and a nil error. func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, err error) { + var authInfo credentials.AuthInfo + rawConn := conn + if config.Credentials != nil { + var err error + conn, authInfo, err = config.Credentials.ServerHandshake(rawConn) + if err != nil { + // ErrConnDispatched means that the connection was dispatched away + // from gRPC; those connections should be left open. io.EOF means + // the connection was closed before handshaking completed, which can + // happen naturally from probers. Return these errors directly. + if err == credentials.ErrConnDispatched || err == io.EOF { + return nil, err + } + return nil, connectionErrorf(false, err, "ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err) + } + } writeBufSize := config.WriteBufferSize readBufSize := config.ReadBufferSize maxHeaderListSize := defaultServerMaxHeaderListSize @@ -211,18 +231,24 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, if kp.Timeout == 0 { kp.Timeout = defaultServerKeepaliveTimeout } + if kp.Time != infinity { + if err = syscall.SetTCPUserTimeout(conn, kp.Timeout); err != nil { + return nil, connectionErrorf(false, err, "transport: failed to set TCP_USER_TIMEOUT: %v", err) + } + } kep := config.KeepalivePolicy if kep.MinTime == 0 { kep.MinTime = defaultKeepalivePolicyMinTime } + done := make(chan struct{}) t := &http2Server{ - ctx: context.Background(), + ctx: setConnection(context.Background(), rawConn), done: done, conn: conn, remoteAddr: conn.RemoteAddr(), localAddr: conn.LocalAddr(), - authInfo: config.AuthInfo, + authInfo: authInfo, framer: framer, readerDone: make(chan struct{}), writerDone: make(chan struct{}), @@ -254,12 +280,12 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, connBegin := &stats.ConnBegin{} t.stats.HandleConn(t.ctx, connBegin) } - if channelz.IsOn() { - t.channelzID = channelz.RegisterNormalSocket(t, config.ChannelzParentID, fmt.Sprintf("%s -> %s", t.remoteAddr, t.localAddr)) + t.channelzID, err = channelz.RegisterNormalSocket(t, config.ChannelzParentID, fmt.Sprintf("%s -> %s", t.remoteAddr, t.localAddr)) + if err != nil { + return nil, err } t.connectionID = atomic.AddUint64(&serverConnectionCounter, 1) - t.framer.writer.Flush() defer func() { @@ -273,10 +299,11 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, if _, err := io.ReadFull(t.conn, preface); err != nil { // In deployments where a gRPC server runs behind a cloud load balancer // which performs regular TCP level health checks, the connection is - // closed immediately by the latter. Skipping the error here will help - // reduce log clutter. + // closed immediately by the latter. Returning io.EOF here allows the + // grpc server implementation to recognize this scenario and suppress + // logging to reduce spam. if err == io.EOF { - return nil, nil + return nil, io.EOF } return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to receive the preface from client: %v", err) } @@ -316,6 +343,10 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, // operateHeader takes action on the decoded headers. func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func(*Stream), traceCtx func(context.Context, string) context.Context) (fatal bool) { + // Acquire max stream ID lock for entire duration + t.maxStreamMu.Lock() + defer t.maxStreamMu.Unlock() + streamID := frame.Header().StreamID // frame.Truncated is set to true when framer detects that the current header @@ -330,6 +361,15 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( return false } + if streamID%2 != 1 || streamID <= t.maxStreamID { + // illegal gRPC stream id. + if logger.V(logLevel) { + logger.Errorf("transport: http2Server.HandleStreams received an illegal stream id: %v", streamID) + } + return true + } + t.maxStreamID = streamID + buf := newRecvBuffer() s := &Stream{ id: streamID, @@ -337,7 +377,6 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( buf: buf, fc: &inFlow{limit: uint32(t.initialWindowSize)}, } - var ( // If a gRPC Response-Headers has already been received, then it means // that the peer is speaking gRPC and we are in gRPC mode. @@ -373,6 +412,13 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( if timeout, err = decodeTimeout(hf.Value); err != nil { headerError = true } + // "Transports must consider requests containing the Connection header + // as malformed." - A41 + case "connection": + if logger.V(logLevel) { + logger.Errorf("transport: http2Server.operateHeaders parsed a :connection header which makes a request malformed as per the HTTP/2 spec") + } + headerError = true default: if isReservedHeader(hf.Name) && !isWhitelistedHeader(hf.Name) { break @@ -387,6 +433,26 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( } } + // "If multiple Host headers or multiple :authority headers are present, the + // request must be rejected with an HTTP status code 400 as required by Host + // validation in RFC 7230 §5.4, gRPC status code INTERNAL, or RST_STREAM + // with HTTP/2 error code PROTOCOL_ERROR." - A41. Since this is a HTTP/2 + // error, this takes precedence over a client not speaking gRPC. + if len(mdata[":authority"]) > 1 || len(mdata["host"]) > 1 { + errMsg := fmt.Sprintf("num values of :authority: %v, num values of host: %v, both must only have 1 value as per HTTP/2 spec", len(mdata[":authority"]), len(mdata["host"])) + if logger.V(logLevel) { + logger.Errorf("transport: %v", errMsg) + } + t.controlBuf.put(&earlyAbortStream{ + httpStatus: 400, + streamID: streamID, + contentSubtype: s.contentSubtype, + status: status.New(codes.Internal, errMsg), + rst: !frame.StreamEnded(), + }) + return false + } + if !isGRPC || headerError { t.controlBuf.put(&cleanupStream{ streamID: streamID, @@ -397,6 +463,19 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( return false } + // "If :authority is missing, Host must be renamed to :authority." - A41 + if len(mdata[":authority"]) == 0 { + // No-op if host isn't present, no eventual :authority header is a valid + // RPC. + if host, ok := mdata["host"]; ok { + mdata[":authority"] = host + delete(mdata, "host") + } + } else { + // "If :authority is present, Host must be discarded" - A41 + delete(mdata, "host") + } + if frame.StreamEnded() { // s is just created by the caller. No lock needed. s.state = streamReadDone @@ -441,26 +520,18 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( s.cancel() return false } - if streamID%2 != 1 || streamID <= t.maxStreamID { - t.mu.Unlock() - // illegal gRPC stream id. - if logger.V(logLevel) { - logger.Errorf("transport: http2Server.HandleStreams received an illegal stream id: %v", streamID) - } - s.cancel() - return true - } - t.maxStreamID = streamID if httpMethod != http.MethodPost { t.mu.Unlock() + errMsg := fmt.Sprintf("http2Server.operateHeaders parsed a :method field: %v which should be POST", httpMethod) if logger.V(logLevel) { - logger.Infof("transport: http2Server.operateHeaders parsed a :method field: %v which should be POST", httpMethod) + logger.Infof("transport: %v", errMsg) } - t.controlBuf.put(&cleanupStream{ - streamID: streamID, - rst: true, - rstCode: http2.ErrCodeProtocol, - onWrite: func() {}, + t.controlBuf.put(&earlyAbortStream{ + httpStatus: 405, + streamID: streamID, + contentSubtype: s.contentSubtype, + status: status.New(codes.Internal, errMsg), + rst: !frame.StreamEnded(), }) s.cancel() return false @@ -477,9 +548,11 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( stat = status.New(codes.PermissionDenied, err.Error()) } t.controlBuf.put(&earlyAbortStream{ + httpStatus: 200, streamID: s.id, contentSubtype: s.contentSubtype, status: stat, + rst: !frame.StreamEnded(), }) return false } @@ -717,7 +790,7 @@ func (t *http2Server) handleData(f *http2.DataFrame) { s.write(recvMsg{buffer: buffer}) } } - if f.Header().Flags.Has(http2.FlagDataEndStream) { + if f.StreamEnded() { // Received the end of stream from the client. s.compareAndSwapState(streamActive, streamReadDone) s.write(recvMsg{err: io.EOF}) @@ -861,11 +934,25 @@ func (t *http2Server) checkForHeaderListSize(it interface{}) bool { return true } +func (t *http2Server) streamContextErr(s *Stream) error { + select { + case <-t.done: + return ErrConnClosing + default: + } + return ContextErr(s.ctx.Err()) +} + // WriteHeader sends the header metadata md back to the client. func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error { - if s.updateHeaderSent() || s.getState() == streamDone { + if s.updateHeaderSent() { return ErrIllegalHeaderWrite } + + if s.getState() == streamDone { + return t.streamContextErr(s) + } + s.hdrMu.Lock() if md.Len() > 0 { if s.header.Len() > 0 { @@ -876,7 +963,7 @@ func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error { } if err := t.writeHeaderLocked(s); err != nil { s.hdrMu.Unlock() - return err + return status.Convert(err).Err() } s.hdrMu.Unlock() return nil @@ -992,23 +1079,12 @@ func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { if !s.isHeaderSent() { // Headers haven't been written yet. if err := t.WriteHeader(s, nil); err != nil { - if _, ok := err.(ConnectionError); ok { - return err - } - // TODO(mmukhi, dfawley): Make sure this is the right code to return. - return status.Errorf(codes.Internal, "transport: %v", err) + return err } } else { // Writing headers checks for this condition. if s.getState() == streamDone { - // TODO(mmukhi, dfawley): Should the server write also return io.EOF? - s.cancel() - select { - case <-t.done: - return ErrConnClosing - default: - } - return ContextErr(s.ctx.Err()) + return t.streamContextErr(s) } } df := &dataFrame{ @@ -1018,12 +1094,7 @@ func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) e onEachWrite: t.setResetPingStrikes, } if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { - select { - case <-t.done: - return ErrConnClosing - default: - } - return ContextErr(s.ctx.Err()) + return t.streamContextErr(s) } return t.controlBuf.put(df) } @@ -1146,9 +1217,7 @@ func (t *http2Server) Close() { if err := t.conn.Close(); err != nil && logger.V(logLevel) { logger.Infof("transport: error closing conn during Close: %v", err) } - if channelz.IsOn() { - channelz.RemoveEntry(t.channelzID) - } + channelz.RemoveEntry(t.channelzID) // Cancel all active streams. for _, s := range streams { s.cancel() @@ -1161,10 +1230,6 @@ func (t *http2Server) Close() { // deleteStream deletes the stream s from transport's active streams. func (t *http2Server) deleteStream(s *Stream, eosReceived bool) { - // In case stream sending and receiving are invoked in separate - // goroutines (e.g., bi-directional streaming), cancel needs to be - // called to interrupt the potential blocking on other goroutines. - s.cancel() t.mu.Lock() if _, ok := t.activeStreams[s.id]; ok { @@ -1186,6 +1251,11 @@ func (t *http2Server) deleteStream(s *Stream, eosReceived bool) { // finishStream closes the stream and puts the trailing headerFrame into controlbuf. func (t *http2Server) finishStream(s *Stream, rst bool, rstCode http2.ErrCode, hdr *headerFrame, eosReceived bool) { + // In case stream sending and receiving are invoked in separate + // goroutines (e.g., bi-directional streaming), cancel needs to be + // called to interrupt the potential blocking on other goroutines. + s.cancel() + oldState := s.swapState(streamDone) if oldState == streamDone { // If the stream was already done, return. @@ -1205,6 +1275,11 @@ func (t *http2Server) finishStream(s *Stream, rst bool, rstCode http2.ErrCode, h // closeStream clears the footprint of a stream when the stream is not needed any more. func (t *http2Server) closeStream(s *Stream, rst bool, rstCode http2.ErrCode, eosReceived bool) { + // In case stream sending and receiving are invoked in separate + // goroutines (e.g., bi-directional streaming), cancel needs to be + // called to interrupt the potential blocking on other goroutines. + s.cancel() + s.swapState(streamDone) t.deleteStream(s, eosReceived) @@ -1235,20 +1310,23 @@ var goAwayPing = &ping{data: [8]byte{1, 6, 1, 8, 0, 3, 3, 9}} // Handles outgoing GoAway and returns true if loopy needs to put itself // in draining mode. func (t *http2Server) outgoingGoAwayHandler(g *goAway) (bool, error) { + t.maxStreamMu.Lock() t.mu.Lock() if t.state == closing { // TODO(mmukhi): This seems unnecessary. t.mu.Unlock() + t.maxStreamMu.Unlock() // The transport is closing. return false, ErrConnClosing } - sid := t.maxStreamID if !g.headsUp { // Stop accepting more streams now. t.state = draining + sid := t.maxStreamID if len(t.activeStreams) == 0 { g.closeConn = true } t.mu.Unlock() + t.maxStreamMu.Unlock() if err := t.framer.fr.WriteGoAway(sid, g.code, g.debugData); err != nil { return false, err } @@ -1261,6 +1339,7 @@ func (t *http2Server) outgoingGoAwayHandler(g *goAway) (bool, error) { return true, nil } t.mu.Unlock() + t.maxStreamMu.Unlock() // For a graceful close, send out a GoAway with stream ID of MaxUInt32, // Follow that with a ping and wait for the ack to come back or a timer // to expire. During this time accept new streams since they might have @@ -1345,3 +1424,18 @@ func getJitter(v time.Duration) time.Duration { j := grpcrand.Int63n(2*r) - r return time.Duration(j) } + +type connectionKey struct{} + +// GetConnection gets the connection from the context. +func GetConnection(ctx context.Context) net.Conn { + conn, _ := ctx.Value(connectionKey{}).(net.Conn) + return conn +} + +// SetConnection adds the connection to the context to be able to get +// information about the destination ip and port for an incoming RPC. This also +// allows any unary or streaming interceptors to see the connection. +func setConnection(ctx context.Context, conn net.Conn) context.Context { + return context.WithValue(ctx, connectionKey{}, conn) +} diff --git a/vendor/google.golang.org/grpc/internal/transport/http_util.go b/vendor/google.golang.org/grpc/internal/transport/http_util.go index 15d775fca3cc..d8247bcdf692 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http_util.go +++ b/vendor/google.golang.org/grpc/internal/transport/http_util.go @@ -173,26 +173,6 @@ func decodeGRPCStatusDetails(rawDetails string) (*status.Status, error) { return status.FromProto(st), nil } -// constructErrMsg constructs error message to be returned in HTTP fallback mode. -// Format: HTTP status code and its corresponding message + content-type error message. -func constructHTTPErrMsg(httpStatus *int, contentTypeErr string) string { - var errMsgs []string - - if httpStatus == nil { - errMsgs = append(errMsgs, "malformed header: missing HTTP status") - } else { - errMsgs = append(errMsgs, fmt.Sprintf("%s: HTTP status code %d", http.StatusText(*(httpStatus)), *httpStatus)) - } - - if contentTypeErr == "" { - errMsgs = append(errMsgs, "transport: missing content-type field") - } else { - errMsgs = append(errMsgs, contentTypeErr) - } - - return strings.Join(errMsgs, "; ") -} - type timeoutUnit uint8 const ( diff --git a/vendor/google.golang.org/grpc/internal/transport/networktype/networktype.go b/vendor/google.golang.org/grpc/internal/transport/networktype/networktype.go index 7bb53cff1011..c11b5278274f 100644 --- a/vendor/google.golang.org/grpc/internal/transport/networktype/networktype.go +++ b/vendor/google.golang.org/grpc/internal/transport/networktype/networktype.go @@ -31,7 +31,7 @@ const key = keyType("grpc.internal.transport.networktype") // Set returns a copy of the provided address with attributes containing networkType. func Set(address resolver.Address, networkType string) resolver.Address { - address.Attributes = address.Attributes.WithValues(key, networkType) + address.Attributes = address.Attributes.WithValue(key, networkType) return address } diff --git a/vendor/google.golang.org/grpc/internal/transport/proxy.go b/vendor/google.golang.org/grpc/internal/transport/proxy.go index a662bf39a6c8..415961987870 100644 --- a/vendor/google.golang.org/grpc/internal/transport/proxy.go +++ b/vendor/google.golang.org/grpc/internal/transport/proxy.go @@ -37,7 +37,7 @@ var ( httpProxyFromEnvironment = http.ProxyFromEnvironment ) -func mapAddress(ctx context.Context, address string) (*url.URL, error) { +func mapAddress(address string) (*url.URL, error) { req := &http.Request{ URL: &url.URL{ Scheme: "https", @@ -114,7 +114,7 @@ func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, backendAddr stri // connection. func proxyDial(ctx context.Context, addr string, grpcUA string) (conn net.Conn, err error) { newAddr := addr - proxyURL, err := mapAddress(ctx, addr) + proxyURL, err := mapAddress(addr) if err != nil { return nil, err } diff --git a/vendor/google.golang.org/grpc/internal/transport/transport.go b/vendor/google.golang.org/grpc/internal/transport/transport.go index 14198126457b..a9ce717f1605 100644 --- a/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -30,9 +30,11 @@ import ( "net" "sync" "sync/atomic" + "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/resolver" @@ -518,7 +520,8 @@ const ( // ServerConfig consists of all the configurations to establish a server transport. type ServerConfig struct { MaxStreams uint32 - AuthInfo credentials.AuthInfo + ConnectionTimeout time.Duration + Credentials credentials.TransportCredentials InTapHandle tap.ServerInHandle StatsHandler stats.Handler KeepaliveParams keepalive.ServerParameters @@ -527,7 +530,7 @@ type ServerConfig struct { InitialConnWindowSize int32 WriteBufferSize int ReadBufferSize int - ChannelzParentID int64 + ChannelzParentID *channelz.Identifier MaxHeaderListSize *uint32 HeaderTableSize *uint32 } @@ -561,7 +564,7 @@ type ConnectOptions struct { // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall. ReadBufferSize int // ChannelzParentID sets the addrConn id which initiate the creation of this client transport. - ChannelzParentID int64 + ChannelzParentID *channelz.Identifier // MaxHeaderListSize sets the max (uncompressed) size of header list that is prepared to be received. MaxHeaderListSize *uint32 // UseProxy specifies if a proxy should be used. @@ -739,6 +742,12 @@ func (e ConnectionError) Origin() error { return e.err } +// Unwrap returns the original error of this connection error or nil when the +// origin is nil. +func (e ConnectionError) Unwrap() error { + return e.err +} + var ( // ErrConnClosing indicates that the transport is closing. ErrConnClosing = connectionErrorf(true, nil, "transport is closing") diff --git a/vendor/google.golang.org/grpc/internal/xds_handshake_cluster.go b/vendor/google.golang.org/grpc/internal/xds_handshake_cluster.go index 3677c3f04f84..e8b492774d1a 100644 --- a/vendor/google.golang.org/grpc/internal/xds_handshake_cluster.go +++ b/vendor/google.golang.org/grpc/internal/xds_handshake_cluster.go @@ -28,7 +28,7 @@ type handshakeClusterNameKey struct{} // SetXDSHandshakeClusterName returns a copy of addr in which the Attributes field // is updated with the cluster name. func SetXDSHandshakeClusterName(addr resolver.Address, clusterName string) resolver.Address { - addr.Attributes = addr.Attributes.WithValues(handshakeClusterNameKey{}, clusterName) + addr.Attributes = addr.Attributes.WithValue(handshakeClusterNameKey{}, clusterName) return addr } diff --git a/vendor/google.golang.org/grpc/metadata/metadata.go b/vendor/google.golang.org/grpc/metadata/metadata.go index 8d9686375a13..8e0f6abe89d7 100644 --- a/vendor/google.golang.org/grpc/metadata/metadata.go +++ b/vendor/google.golang.org/grpc/metadata/metadata.go @@ -123,6 +123,13 @@ func (md MD) Append(k string, vals ...string) { md[k] = append(md[k], vals...) } +// Delete removes the values for a given key k which is converted to lowercase +// before removing it from md. +func (md MD) Delete(k string) { + k = strings.ToLower(k) + delete(md, k) +} + // Join joins any number of mds into a single MD. // // The order of values for each key is determined by the order in which the mds @@ -181,7 +188,9 @@ func FromIncomingContext(ctx context.Context) (MD, bool) { // map, and there's no guarantee that the MD attached to the context is // created using our helper functions. key := strings.ToLower(k) - out[key] = v + s := make([]string, len(v)) + copy(s, v) + out[key] = s } return out, true } @@ -219,7 +228,9 @@ func FromOutgoingContext(ctx context.Context) (MD, bool) { // map, and there's no guarantee that the MD attached to the context is // created using our helper functions. key := strings.ToLower(k) - out[key] = v + s := make([]string, len(v)) + copy(s, v) + out[key] = s } for _, added := range raw.added { if len(added)%2 == 1 { diff --git a/vendor/google.golang.org/grpc/picker_wrapper.go b/vendor/google.golang.org/grpc/picker_wrapper.go index a58174b6f436..843633c910a1 100644 --- a/vendor/google.golang.org/grpc/picker_wrapper.go +++ b/vendor/google.golang.org/grpc/picker_wrapper.go @@ -131,7 +131,7 @@ func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer. } if _, ok := status.FromError(err); ok { // Status error: end the RPC unconditionally with this status. - return nil, nil, err + return nil, nil, dropError{error: err} } // For all other errors, wait for ready RPCs should block and other // RPCs should fail with unavailable. @@ -144,10 +144,10 @@ func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer. acw, ok := pickResult.SubConn.(*acBalancerWrapper) if !ok { - logger.Error("subconn returned from pick is not *acBalancerWrapper") + logger.Errorf("subconn returned from pick is type %T, not *acBalancerWrapper", pickResult.SubConn) continue } - if t, ok := acw.getAddrConn().getReadyTransport(); ok { + if t := acw.getAddrConn().getReadyTransport(); t != nil { if channelz.IsOn() { return t, doneChannelzWrapper(acw, pickResult.Done), nil } @@ -175,3 +175,9 @@ func (pw *pickerWrapper) close() { pw.done = true close(pw.blockingCh) } + +// dropError is a wrapper error that indicates the LB policy wishes to drop the +// RPC and not retry it. +type dropError struct { + error +} diff --git a/vendor/google.golang.org/grpc/pickfirst.go b/vendor/google.golang.org/grpc/pickfirst.go index b858c2a5e63b..fb7a99e0a273 100644 --- a/vendor/google.golang.org/grpc/pickfirst.go +++ b/vendor/google.golang.org/grpc/pickfirst.go @@ -44,77 +44,107 @@ func (*pickfirstBuilder) Name() string { } type pickfirstBalancer struct { - state connectivity.State - cc balancer.ClientConn - sc balancer.SubConn + state connectivity.State + cc balancer.ClientConn + subConn balancer.SubConn } func (b *pickfirstBalancer) ResolverError(err error) { - switch b.state { - case connectivity.TransientFailure, connectivity.Idle, connectivity.Connecting: - // Set a failing picker if we don't have a good picker. - b.cc.UpdateState(balancer.State{ConnectivityState: connectivity.TransientFailure, - Picker: &picker{err: fmt.Errorf("name resolver error: %v", err)}, - }) - } if logger.V(2) { logger.Infof("pickfirstBalancer: ResolverError called with error %v", err) } + if b.subConn == nil { + b.state = connectivity.TransientFailure + } + + if b.state != connectivity.TransientFailure { + // The picker will not change since the balancer does not currently + // report an error. + return + } + b.cc.UpdateState(balancer.State{ + ConnectivityState: connectivity.TransientFailure, + Picker: &picker{err: fmt.Errorf("name resolver error: %v", err)}, + }) } -func (b *pickfirstBalancer) UpdateClientConnState(cs balancer.ClientConnState) error { - if len(cs.ResolverState.Addresses) == 0 { +func (b *pickfirstBalancer) UpdateClientConnState(state balancer.ClientConnState) error { + if len(state.ResolverState.Addresses) == 0 { + // The resolver reported an empty address list. Treat it like an error by + // calling b.ResolverError. + if b.subConn != nil { + // Remove the old subConn. All addresses were removed, so it is no longer + // valid. + b.cc.RemoveSubConn(b.subConn) + b.subConn = nil + } b.ResolverError(errors.New("produced zero addresses")) return balancer.ErrBadResolverState } - if b.sc == nil { - var err error - b.sc, err = b.cc.NewSubConn(cs.ResolverState.Addresses, balancer.NewSubConnOptions{}) - if err != nil { - if logger.V(2) { - logger.Errorf("pickfirstBalancer: failed to NewSubConn: %v", err) - } - b.state = connectivity.TransientFailure - b.cc.UpdateState(balancer.State{ConnectivityState: connectivity.TransientFailure, - Picker: &picker{err: fmt.Errorf("error creating connection: %v", err)}, - }) - return balancer.ErrBadResolverState + + if b.subConn != nil { + b.cc.UpdateAddresses(b.subConn, state.ResolverState.Addresses) + return nil + } + + subConn, err := b.cc.NewSubConn(state.ResolverState.Addresses, balancer.NewSubConnOptions{}) + if err != nil { + if logger.V(2) { + logger.Errorf("pickfirstBalancer: failed to NewSubConn: %v", err) } - b.state = connectivity.Idle - b.cc.UpdateState(balancer.State{ConnectivityState: connectivity.Idle, Picker: &picker{result: balancer.PickResult{SubConn: b.sc}}}) - b.sc.Connect() - } else { - b.cc.UpdateAddresses(b.sc, cs.ResolverState.Addresses) - b.sc.Connect() + b.state = connectivity.TransientFailure + b.cc.UpdateState(balancer.State{ + ConnectivityState: connectivity.TransientFailure, + Picker: &picker{err: fmt.Errorf("error creating connection: %v", err)}, + }) + return balancer.ErrBadResolverState } + b.subConn = subConn + b.state = connectivity.Idle + b.cc.UpdateState(balancer.State{ + ConnectivityState: connectivity.Idle, + Picker: &picker{result: balancer.PickResult{SubConn: b.subConn}}, + }) + b.subConn.Connect() return nil } -func (b *pickfirstBalancer) UpdateSubConnState(sc balancer.SubConn, s balancer.SubConnState) { +func (b *pickfirstBalancer) UpdateSubConnState(subConn balancer.SubConn, state balancer.SubConnState) { if logger.V(2) { - logger.Infof("pickfirstBalancer: UpdateSubConnState: %p, %v", sc, s) + logger.Infof("pickfirstBalancer: UpdateSubConnState: %p, %v", subConn, state) } - if b.sc != sc { + if b.subConn != subConn { if logger.V(2) { - logger.Infof("pickfirstBalancer: ignored state change because sc is not recognized") + logger.Infof("pickfirstBalancer: ignored state change because subConn is not recognized") } return } - b.state = s.ConnectivityState - if s.ConnectivityState == connectivity.Shutdown { - b.sc = nil + b.state = state.ConnectivityState + if state.ConnectivityState == connectivity.Shutdown { + b.subConn = nil return } - switch s.ConnectivityState { - case connectivity.Ready, connectivity.Idle: - b.cc.UpdateState(balancer.State{ConnectivityState: s.ConnectivityState, Picker: &picker{result: balancer.PickResult{SubConn: sc}}}) + switch state.ConnectivityState { + case connectivity.Ready: + b.cc.UpdateState(balancer.State{ + ConnectivityState: state.ConnectivityState, + Picker: &picker{result: balancer.PickResult{SubConn: subConn}}, + }) case connectivity.Connecting: - b.cc.UpdateState(balancer.State{ConnectivityState: s.ConnectivityState, Picker: &picker{err: balancer.ErrNoSubConnAvailable}}) + b.cc.UpdateState(balancer.State{ + ConnectivityState: state.ConnectivityState, + Picker: &picker{err: balancer.ErrNoSubConnAvailable}, + }) + case connectivity.Idle: + b.cc.UpdateState(balancer.State{ + ConnectivityState: state.ConnectivityState, + Picker: &idlePicker{subConn: subConn}, + }) case connectivity.TransientFailure: b.cc.UpdateState(balancer.State{ - ConnectivityState: s.ConnectivityState, - Picker: &picker{err: s.ConnectionError}, + ConnectivityState: state.ConnectivityState, + Picker: &picker{err: state.ConnectionError}, }) } } @@ -122,15 +152,32 @@ func (b *pickfirstBalancer) UpdateSubConnState(sc balancer.SubConn, s balancer.S func (b *pickfirstBalancer) Close() { } +func (b *pickfirstBalancer) ExitIdle() { + if b.subConn != nil && b.state == connectivity.Idle { + b.subConn.Connect() + } +} + type picker struct { result balancer.PickResult err error } -func (p *picker) Pick(info balancer.PickInfo) (balancer.PickResult, error) { +func (p *picker) Pick(balancer.PickInfo) (balancer.PickResult, error) { return p.result, p.err } +// idlePicker is used when the SubConn is IDLE and kicks the SubConn into +// CONNECTING when Pick is called. +type idlePicker struct { + subConn balancer.SubConn +} + +func (i *idlePicker) Pick(balancer.PickInfo) (balancer.PickResult, error) { + i.subConn.Connect() + return balancer.PickResult{}, balancer.ErrNoSubConnAvailable +} + func init() { balancer.Register(newPickfirstBuilder()) } diff --git a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go index 7d05c14ebd89..4e6a6b1a857b 100644 --- a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go +++ b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.1.0 +// - protoc-gen-go-grpc v1.2.0 // - protoc v3.14.0 // source: reflection/grpc_reflection_v1alpha/reflection.proto diff --git a/vendor/google.golang.org/grpc/reflection/serverreflection.go b/vendor/google.golang.org/grpc/reflection/serverreflection.go index 82a5ba7f2444..81344abd77da 100644 --- a/vendor/google.golang.org/grpc/reflection/serverreflection.go +++ b/vendor/google.golang.org/grpc/reflection/serverreflection.go @@ -37,21 +37,17 @@ To register server reflection on a gRPC server: package reflection // import "google.golang.org/grpc/reflection" import ( - "bytes" - "compress/gzip" - "fmt" "io" - "io/ioutil" - "reflect" "sort" - "sync" - "github.com/golang/protobuf/proto" - dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "google.golang.org/grpc" "google.golang.org/grpc/codes" rpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" ) // GRPCServer is the interface provided by a gRPC server. It is implemented by @@ -59,339 +55,174 @@ import ( // as a registry, for accumulating the services exposed by the server. type GRPCServer interface { grpc.ServiceRegistrar - GetServiceInfo() map[string]grpc.ServiceInfo + ServiceInfoProvider } var _ GRPCServer = (*grpc.Server)(nil) -type serverReflectionServer struct { - rpb.UnimplementedServerReflectionServer - s GRPCServer - - initSymbols sync.Once - serviceNames []string - symbols map[string]*dpb.FileDescriptorProto // map of fully-qualified names to files -} - // Register registers the server reflection service on the given gRPC server. func Register(s GRPCServer) { - rpb.RegisterServerReflectionServer(s, &serverReflectionServer{ - s: s, - }) + svr := NewServer(ServerOptions{Services: s}) + rpb.RegisterServerReflectionServer(s, svr) } -// protoMessage is used for type assertion on proto messages. -// Generated proto message implements function Descriptor(), but Descriptor() -// is not part of interface proto.Message. This interface is needed to -// call Descriptor(). -type protoMessage interface { - Descriptor() ([]byte, []int) -} - -func (s *serverReflectionServer) getSymbols() (svcNames []string, symbolIndex map[string]*dpb.FileDescriptorProto) { - s.initSymbols.Do(func() { - serviceInfo := s.s.GetServiceInfo() - - s.symbols = map[string]*dpb.FileDescriptorProto{} - s.serviceNames = make([]string, 0, len(serviceInfo)) - processed := map[string]struct{}{} - for svc, info := range serviceInfo { - s.serviceNames = append(s.serviceNames, svc) - fdenc, ok := parseMetadata(info.Metadata) - if !ok { - continue - } - fd, err := decodeFileDesc(fdenc) - if err != nil { - continue - } - s.processFile(fd, processed) - } - sort.Strings(s.serviceNames) - }) - - return s.serviceNames, s.symbols -} - -func (s *serverReflectionServer) processFile(fd *dpb.FileDescriptorProto, processed map[string]struct{}) { - filename := fd.GetName() - if _, ok := processed[filename]; ok { - return - } - processed[filename] = struct{}{} - - prefix := fd.GetPackage() - - for _, msg := range fd.MessageType { - s.processMessage(fd, prefix, msg) - } - for _, en := range fd.EnumType { - s.processEnum(fd, prefix, en) - } - for _, ext := range fd.Extension { - s.processField(fd, prefix, ext) - } - for _, svc := range fd.Service { - svcName := fqn(prefix, svc.GetName()) - s.symbols[svcName] = fd - for _, meth := range svc.Method { - name := fqn(svcName, meth.GetName()) - s.symbols[name] = fd - } - } - - for _, dep := range fd.Dependency { - fdenc := proto.FileDescriptor(dep) - fdDep, err := decodeFileDesc(fdenc) - if err != nil { - continue - } - s.processFile(fdDep, processed) - } -} - -func (s *serverReflectionServer) processMessage(fd *dpb.FileDescriptorProto, prefix string, msg *dpb.DescriptorProto) { - msgName := fqn(prefix, msg.GetName()) - s.symbols[msgName] = fd - - for _, nested := range msg.NestedType { - s.processMessage(fd, msgName, nested) - } - for _, en := range msg.EnumType { - s.processEnum(fd, msgName, en) - } - for _, ext := range msg.Extension { - s.processField(fd, msgName, ext) - } - for _, fld := range msg.Field { - s.processField(fd, msgName, fld) - } - for _, oneof := range msg.OneofDecl { - oneofName := fqn(msgName, oneof.GetName()) - s.symbols[oneofName] = fd - } -} - -func (s *serverReflectionServer) processEnum(fd *dpb.FileDescriptorProto, prefix string, en *dpb.EnumDescriptorProto) { - enName := fqn(prefix, en.GetName()) - s.symbols[enName] = fd - - for _, val := range en.Value { - valName := fqn(enName, val.GetName()) - s.symbols[valName] = fd - } -} - -func (s *serverReflectionServer) processField(fd *dpb.FileDescriptorProto, prefix string, fld *dpb.FieldDescriptorProto) { - fldName := fqn(prefix, fld.GetName()) - s.symbols[fldName] = fd -} - -func fqn(prefix, name string) string { - if prefix == "" { - return name - } - return prefix + "." + name -} - -// fileDescForType gets the file descriptor for the given type. -// The given type should be a proto message. -func (s *serverReflectionServer) fileDescForType(st reflect.Type) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(protoMessage) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - enc, _ := m.Descriptor() - - return decodeFileDesc(enc) -} - -// decodeFileDesc does decompression and unmarshalling on the given -// file descriptor byte slice. -func decodeFileDesc(enc []byte) (*dpb.FileDescriptorProto, error) { - raw, err := decompress(enc) - if err != nil { - return nil, fmt.Errorf("failed to decompress enc: %v", err) - } - - fd := new(dpb.FileDescriptorProto) - if err := proto.Unmarshal(raw, fd); err != nil { - return nil, fmt.Errorf("bad descriptor: %v", err) - } - return fd, nil +// ServiceInfoProvider is an interface used to retrieve metadata about the +// services to expose. +// +// The reflection service is only interested in the service names, but the +// signature is this way so that *grpc.Server implements it. So it is okay +// for a custom implementation to return zero values for the +// grpc.ServiceInfo values in the map. +// +// Experimental +// +// Notice: This type is EXPERIMENTAL and may be changed or removed in a +// later release. +type ServiceInfoProvider interface { + GetServiceInfo() map[string]grpc.ServiceInfo } -// decompress does gzip decompression. -func decompress(b []byte) ([]byte, error) { - r, err := gzip.NewReader(bytes.NewReader(b)) - if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) - } - out, err := ioutil.ReadAll(r) - if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) - } - return out, nil +// ExtensionResolver is the interface used to query details about extensions. +// This interface is satisfied by protoregistry.GlobalTypes. +// +// Experimental +// +// Notice: This type is EXPERIMENTAL and may be changed or removed in a +// later release. +type ExtensionResolver interface { + protoregistry.ExtensionTypeResolver + RangeExtensionsByMessage(message protoreflect.FullName, f func(protoreflect.ExtensionType) bool) } -func typeForName(name string) (reflect.Type, error) { - pt := proto.MessageType(name) - if pt == nil { - return nil, fmt.Errorf("unknown type: %q", name) - } - st := pt.Elem() - - return st, nil +// ServerOptions represents the options used to construct a reflection server. +// +// Experimental +// +// Notice: This type is EXPERIMENTAL and may be changed or removed in a +// later release. +type ServerOptions struct { + // The source of advertised RPC services. If not specified, the reflection + // server will report an empty list when asked to list services. + // + // This value will typically be a *grpc.Server. But the set of advertised + // services can be customized by wrapping a *grpc.Server or using an + // alternate implementation that returns a custom set of service names. + Services ServiceInfoProvider + // Optional resolver used to load descriptors. If not specified, + // protoregistry.GlobalFiles will be used. + DescriptorResolver protodesc.Resolver + // Optional resolver used to query for known extensions. If not specified, + // protoregistry.GlobalTypes will be used. + ExtensionResolver ExtensionResolver } -func fileDescContainingExtension(st reflect.Type, ext int32) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) +// NewServer returns a reflection server implementation using the given options. +// This can be used to customize behavior of the reflection service. Most usages +// should prefer to use Register instead. +// +// Experimental +// +// Notice: This function is EXPERIMENTAL and may be changed or removed in a +// later release. +func NewServer(opts ServerOptions) rpb.ServerReflectionServer { + if opts.DescriptorResolver == nil { + opts.DescriptorResolver = protoregistry.GlobalFiles + } + if opts.ExtensionResolver == nil { + opts.ExtensionResolver = protoregistry.GlobalTypes + } + return &serverReflectionServer{ + s: opts.Services, + descResolver: opts.DescriptorResolver, + extResolver: opts.ExtensionResolver, } - - var extDesc *proto.ExtensionDesc - for id, desc := range proto.RegisteredExtensions(m) { - if id == ext { - extDesc = desc - break - } - } - - if extDesc == nil { - return nil, fmt.Errorf("failed to find registered extension for extension number %v", ext) - } - - return decodeFileDesc(proto.FileDescriptor(extDesc.Filename)) } -func (s *serverReflectionServer) allExtensionNumbersForType(st reflect.Type) ([]int32, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - - exts := proto.RegisteredExtensions(m) - out := make([]int32, 0, len(exts)) - for id := range exts { - out = append(out, id) - } - return out, nil +type serverReflectionServer struct { + rpb.UnimplementedServerReflectionServer + s ServiceInfoProvider + descResolver protodesc.Resolver + extResolver ExtensionResolver } // fileDescWithDependencies returns a slice of serialized fileDescriptors in // wire format ([]byte). The fileDescriptors will include fd and all the // transitive dependencies of fd with names not in sentFileDescriptors. -func fileDescWithDependencies(fd *dpb.FileDescriptorProto, sentFileDescriptors map[string]bool) ([][]byte, error) { - r := [][]byte{} - queue := []*dpb.FileDescriptorProto{fd} +func (s *serverReflectionServer) fileDescWithDependencies(fd protoreflect.FileDescriptor, sentFileDescriptors map[string]bool) ([][]byte, error) { + var r [][]byte + queue := []protoreflect.FileDescriptor{fd} for len(queue) > 0 { currentfd := queue[0] queue = queue[1:] - if sent := sentFileDescriptors[currentfd.GetName()]; len(r) == 0 || !sent { - sentFileDescriptors[currentfd.GetName()] = true - currentfdEncoded, err := proto.Marshal(currentfd) + if sent := sentFileDescriptors[currentfd.Path()]; len(r) == 0 || !sent { + sentFileDescriptors[currentfd.Path()] = true + fdProto := protodesc.ToFileDescriptorProto(currentfd) + currentfdEncoded, err := proto.Marshal(fdProto) if err != nil { return nil, err } r = append(r, currentfdEncoded) } - for _, dep := range currentfd.Dependency { - fdenc := proto.FileDescriptor(dep) - fdDep, err := decodeFileDesc(fdenc) - if err != nil { - continue - } - queue = append(queue, fdDep) + for i := 0; i < currentfd.Imports().Len(); i++ { + queue = append(queue, currentfd.Imports().Get(i)) } } return r, nil } -// fileDescEncodingByFilename finds the file descriptor for given filename, -// finds all of its previously unsent transitive dependencies, does marshalling -// on them, and returns the marshalled result. -func (s *serverReflectionServer) fileDescEncodingByFilename(name string, sentFileDescriptors map[string]bool) ([][]byte, error) { - enc := proto.FileDescriptor(name) - if enc == nil { - return nil, fmt.Errorf("unknown file: %v", name) - } - fd, err := decodeFileDesc(enc) - if err != nil { - return nil, err - } - return fileDescWithDependencies(fd, sentFileDescriptors) -} - -// parseMetadata finds the file descriptor bytes specified meta. -// For SupportPackageIsVersion4, m is the name of the proto file, we -// call proto.FileDescriptor to get the byte slice. -// For SupportPackageIsVersion3, m is a byte slice itself. -func parseMetadata(meta interface{}) ([]byte, bool) { - // Check if meta is the file name. - if fileNameForMeta, ok := meta.(string); ok { - return proto.FileDescriptor(fileNameForMeta), true - } - - // Check if meta is the byte slice. - if enc, ok := meta.([]byte); ok { - return enc, true - } - - return nil, false -} - // fileDescEncodingContainingSymbol finds the file descriptor containing the // given symbol, finds all of its previously unsent transitive dependencies, // does marshalling on them, and returns the marshalled result. The given symbol // can be a type, a service or a method. func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string, sentFileDescriptors map[string]bool) ([][]byte, error) { - _, symbols := s.getSymbols() - fd := symbols[name] - if fd == nil { - // Check if it's a type name that was not present in the - // transitive dependencies of the registered services. - if st, err := typeForName(name); err == nil { - fd, err = s.fileDescForType(st) - if err != nil { - return nil, err - } - } - } - - if fd == nil { - return nil, fmt.Errorf("unknown symbol: %v", name) + d, err := s.descResolver.FindDescriptorByName(protoreflect.FullName(name)) + if err != nil { + return nil, err } - - return fileDescWithDependencies(fd, sentFileDescriptors) + return s.fileDescWithDependencies(d.ParentFile(), sentFileDescriptors) } // fileDescEncodingContainingExtension finds the file descriptor containing // given extension, finds all of its previously unsent transitive dependencies, // does marshalling on them, and returns the marshalled result. func (s *serverReflectionServer) fileDescEncodingContainingExtension(typeName string, extNum int32, sentFileDescriptors map[string]bool) ([][]byte, error) { - st, err := typeForName(typeName) - if err != nil { - return nil, err - } - fd, err := fileDescContainingExtension(st, extNum) + xt, err := s.extResolver.FindExtensionByNumber(protoreflect.FullName(typeName), protoreflect.FieldNumber(extNum)) if err != nil { return nil, err } - return fileDescWithDependencies(fd, sentFileDescriptors) + return s.fileDescWithDependencies(xt.TypeDescriptor().ParentFile(), sentFileDescriptors) } // allExtensionNumbersForTypeName returns all extension numbers for the given type. func (s *serverReflectionServer) allExtensionNumbersForTypeName(name string) ([]int32, error) { - st, err := typeForName(name) - if err != nil { - return nil, err + var numbers []int32 + s.extResolver.RangeExtensionsByMessage(protoreflect.FullName(name), func(xt protoreflect.ExtensionType) bool { + numbers = append(numbers, int32(xt.TypeDescriptor().Number())) + return true + }) + sort.Slice(numbers, func(i, j int) bool { + return numbers[i] < numbers[j] + }) + if len(numbers) == 0 { + // maybe return an error if given type name is not known + if _, err := s.descResolver.FindDescriptorByName(protoreflect.FullName(name)); err != nil { + return nil, err + } } - extNums, err := s.allExtensionNumbersForType(st) - if err != nil { - return nil, err + return numbers, nil +} + +// listServices returns the names of services this server exposes. +func (s *serverReflectionServer) listServices() []*rpb.ServiceResponse { + serviceInfo := s.s.GetServiceInfo() + resp := make([]*rpb.ServiceResponse, 0, len(serviceInfo)) + for svc := range serviceInfo { + resp = append(resp, &rpb.ServiceResponse{Name: svc}) } - return extNums, nil + sort.Slice(resp, func(i, j int) bool { + return resp[i].Name < resp[j].Name + }) + return resp } // ServerReflectionInfo is the reflection service handler. @@ -412,7 +243,11 @@ func (s *serverReflectionServer) ServerReflectionInfo(stream rpb.ServerReflectio } switch req := in.MessageRequest.(type) { case *rpb.ServerReflectionRequest_FileByFilename: - b, err := s.fileDescEncodingByFilename(req.FileByFilename, sentFileDescriptors) + var b [][]byte + fd, err := s.descResolver.FindFileByPath(req.FileByFilename) + if err == nil { + b, err = s.fileDescWithDependencies(fd, sentFileDescriptors) + } if err != nil { out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ ErrorResponse: &rpb.ErrorResponse{ @@ -473,16 +308,9 @@ func (s *serverReflectionServer) ServerReflectionInfo(stream rpb.ServerReflectio } } case *rpb.ServerReflectionRequest_ListServices: - svcNames, _ := s.getSymbols() - serviceResponses := make([]*rpb.ServiceResponse, len(svcNames)) - for i, n := range svcNames { - serviceResponses[i] = &rpb.ServiceResponse{ - Name: n, - } - } out.MessageResponse = &rpb.ServerReflectionResponse_ListServicesResponse{ ListServicesResponse: &rpb.ListServiceResponse{ - Service: serviceResponses, + Service: s.listServices(), }, } default: diff --git a/vendor/google.golang.org/grpc/regenerate.sh b/vendor/google.golang.org/grpc/regenerate.sh index dfd3226a1d96..978b89f37a4a 100644 --- a/vendor/google.golang.org/grpc/regenerate.sh +++ b/vendor/google.golang.org/grpc/regenerate.sh @@ -27,9 +27,9 @@ export PATH=${GOBIN}:${PATH} mkdir -p ${GOBIN} echo "remove existing generated files" -# grpc_testingv3/testv3.pb.go is not re-generated because it was -# intentionally generated by an older version of protoc-gen-go. -rm -f $(find . -name '*.pb.go' | grep -v 'grpc_testingv3/testv3.pb.go') +# grpc_testing_not_regenerate/*.pb.go is not re-generated, +# see grpc_testing_not_regenerate/README.md for details. +rm -f $(find . -name '*.pb.go' | grep -v 'grpc_testing_not_regenerate') echo "go install google.golang.org/protobuf/cmd/protoc-gen-go" (cd test/tools && go install google.golang.org/protobuf/cmd/protoc-gen-go) @@ -76,7 +76,21 @@ SOURCES=( # These options of the form 'Mfoo.proto=bar' instruct the codegen to use an # import path of 'bar' in the generated code when 'foo.proto' is imported in # one of the sources. -OPTS=Mgrpc/service_config/service_config.proto=/internal/proto/grpc_service_config,Mgrpc/core/stats.proto=google.golang.org/grpc/interop/grpc_testing/core +# +# Note that the protos listed here are all for testing purposes. All protos to +# be used externally should have a go_package option (and they don't need to be +# listed here). +OPTS=Mgrpc/service_config/service_config.proto=/internal/proto/grpc_service_config,\ +Mgrpc/core/stats.proto=google.golang.org/grpc/interop/grpc_testing/core,\ +Mgrpc/testing/benchmark_service.proto=google.golang.org/grpc/interop/grpc_testing,\ +Mgrpc/testing/stats.proto=google.golang.org/grpc/interop/grpc_testing,\ +Mgrpc/testing/report_qps_scenario_service.proto=google.golang.org/grpc/interop/grpc_testing,\ +Mgrpc/testing/messages.proto=google.golang.org/grpc/interop/grpc_testing,\ +Mgrpc/testing/worker_service.proto=google.golang.org/grpc/interop/grpc_testing,\ +Mgrpc/testing/control.proto=google.golang.org/grpc/interop/grpc_testing,\ +Mgrpc/testing/test.proto=google.golang.org/grpc/interop/grpc_testing,\ +Mgrpc/testing/payloads.proto=google.golang.org/grpc/interop/grpc_testing,\ +Mgrpc/testing/empty.proto=google.golang.org/grpc/interop/grpc_testing for src in ${SOURCES[@]}; do echo "protoc ${src}" @@ -85,7 +99,6 @@ for src in ${SOURCES[@]}; do -I${WORKDIR}/grpc-proto \ -I${WORKDIR}/googleapis \ -I${WORKDIR}/protobuf/src \ - -I${WORKDIR}/istio \ ${src} done @@ -96,18 +109,17 @@ for src in ${LEGACY_SOURCES[@]}; do -I${WORKDIR}/grpc-proto \ -I${WORKDIR}/googleapis \ -I${WORKDIR}/protobuf/src \ - -I${WORKDIR}/istio \ ${src} done # The go_package option in grpc/lookup/v1/rls.proto doesn't match the # current location. Move it into the right place. -mkdir -p ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1 -mv ${WORKDIR}/out/google.golang.org/grpc/lookup/grpc_lookup_v1/* ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1 +mkdir -p ${WORKDIR}/out/google.golang.org/grpc/internal/proto/grpc_lookup_v1 +mv ${WORKDIR}/out/google.golang.org/grpc/lookup/grpc_lookup_v1/* ${WORKDIR}/out/google.golang.org/grpc/internal/proto/grpc_lookup_v1 -# grpc_testingv3/testv3.pb.go is not re-generated because it was -# intentionally generated by an older version of protoc-gen-go. -rm ${WORKDIR}/out/google.golang.org/grpc/reflection/grpc_testingv3/*.pb.go +# grpc_testing_not_regenerate/*.pb.go are not re-generated, +# see grpc_testing_not_regenerate/README.md for details. +rm ${WORKDIR}/out/google.golang.org/grpc/reflection/grpc_testing_not_regenerate/*.pb.go # grpc/service_config/service_config.proto does not have a go_package option. mv ${WORKDIR}/out/grpc/service_config/service_config.pb.go internal/proto/grpc_service_config diff --git a/vendor/google.golang.org/grpc/resolver/map.go b/vendor/google.golang.org/grpc/resolver/map.go new file mode 100644 index 000000000000..e87ecd0eeb38 --- /dev/null +++ b/vendor/google.golang.org/grpc/resolver/map.go @@ -0,0 +1,109 @@ +/* + * + * Copyright 2021 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package resolver + +type addressMapEntry struct { + addr Address + value interface{} +} + +// AddressMap is a map of addresses to arbitrary values taking into account +// Attributes. BalancerAttributes are ignored, as are Metadata and Type. +// Multiple accesses may not be performed concurrently. Must be created via +// NewAddressMap; do not construct directly. +type AddressMap struct { + m map[string]addressMapEntryList +} + +type addressMapEntryList []*addressMapEntry + +// NewAddressMap creates a new AddressMap. +func NewAddressMap() *AddressMap { + return &AddressMap{m: make(map[string]addressMapEntryList)} +} + +// find returns the index of addr in the addressMapEntry slice, or -1 if not +// present. +func (l addressMapEntryList) find(addr Address) int { + if len(l) == 0 { + return -1 + } + for i, entry := range l { + if entry.addr.ServerName == addr.ServerName && + entry.addr.Attributes.Equal(addr.Attributes) { + return i + } + } + return -1 +} + +// Get returns the value for the address in the map, if present. +func (a *AddressMap) Get(addr Address) (value interface{}, ok bool) { + entryList := a.m[addr.Addr] + if entry := entryList.find(addr); entry != -1 { + return entryList[entry].value, true + } + return nil, false +} + +// Set updates or adds the value to the address in the map. +func (a *AddressMap) Set(addr Address, value interface{}) { + entryList := a.m[addr.Addr] + if entry := entryList.find(addr); entry != -1 { + a.m[addr.Addr][entry].value = value + return + } + a.m[addr.Addr] = append(a.m[addr.Addr], &addressMapEntry{addr: addr, value: value}) +} + +// Delete removes addr from the map. +func (a *AddressMap) Delete(addr Address) { + entryList := a.m[addr.Addr] + entry := entryList.find(addr) + if entry == -1 { + return + } + if len(entryList) == 1 { + entryList = nil + } else { + copy(entryList[entry:], entryList[entry+1:]) + entryList = entryList[:len(entryList)-1] + } + a.m[addr.Addr] = entryList +} + +// Len returns the number of entries in the map. +func (a *AddressMap) Len() int { + ret := 0 + for _, entryList := range a.m { + ret += len(entryList) + } + return ret +} + +// Keys returns a slice of all current map keys. +func (a *AddressMap) Keys() []Address { + ret := make([]Address, 0, a.Len()) + for _, entryList := range a.m { + for _, entry := range entryList { + ret = append(ret, entry.addr) + } + } + return ret +} diff --git a/vendor/google.golang.org/grpc/resolver/resolver.go b/vendor/google.golang.org/grpc/resolver/resolver.go index 6a9d234a597a..ca2e35a3596f 100644 --- a/vendor/google.golang.org/grpc/resolver/resolver.go +++ b/vendor/google.golang.org/grpc/resolver/resolver.go @@ -23,9 +23,11 @@ package resolver import ( "context" "net" + "net/url" "google.golang.org/grpc/attributes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/internal/pretty" "google.golang.org/grpc/serviceconfig" ) @@ -116,9 +118,14 @@ type Address struct { ServerName string // Attributes contains arbitrary data about this address intended for - // consumption by the load balancing policy. + // consumption by the SubConn. Attributes *attributes.Attributes + // BalancerAttributes contains arbitrary data about this address intended + // for consumption by the LB policy. These attribes do not affect SubConn + // creation, connection establishment, handshaking, etc. + BalancerAttributes *attributes.Attributes + // Type is the type of this address. // // Deprecated: use Attributes instead. @@ -131,6 +138,20 @@ type Address struct { Metadata interface{} } +// Equal returns whether a and o are identical. Metadata is compared directly, +// not with any recursive introspection. +func (a Address) Equal(o Address) bool { + return a.Addr == o.Addr && a.ServerName == o.ServerName && + a.Attributes.Equal(o.Attributes) && + a.BalancerAttributes.Equal(o.BalancerAttributes) && + a.Type == o.Type && a.Metadata == o.Metadata +} + +// String returns JSON formatted string representation of the address. +func (a Address) String() string { + return pretty.ToJSON(a) +} + // BuildOptions includes additional information for the builder to create // the resolver. type BuildOptions struct { @@ -204,25 +225,36 @@ type ClientConn interface { // Target represents a target for gRPC, as specified in: // https://github.com/grpc/grpc/blob/master/doc/naming.md. -// It is parsed from the target string that gets passed into Dial or DialContext by the user. And -// grpc passes it to the resolver and the balancer. +// It is parsed from the target string that gets passed into Dial or DialContext +// by the user. And gRPC passes it to the resolver and the balancer. // -// If the target follows the naming spec, and the parsed scheme is registered with grpc, we will -// parse the target string according to the spec. e.g. "dns://some_authority/foo.bar" will be parsed -// into &Target{Scheme: "dns", Authority: "some_authority", Endpoint: "foo.bar"} +// If the target follows the naming spec, and the parsed scheme is registered +// with gRPC, we will parse the target string according to the spec. If the +// target does not contain a scheme or if the parsed scheme is not registered +// (i.e. no corresponding resolver available to resolve the endpoint), we will +// apply the default scheme, and will attempt to reparse it. // -// If the target does not contain a scheme, we will apply the default scheme, and set the Target to -// be the full target string. e.g. "foo.bar" will be parsed into -// &Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "foo.bar"}. +// Examples: // -// If the parsed scheme is not registered (i.e. no corresponding resolver available to resolve the -// endpoint), we set the Scheme to be the default scheme, and set the Endpoint to be the full target -// string. e.g. target string "unknown_scheme://authority/endpoint" will be parsed into -// &Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "unknown_scheme://authority/endpoint"}. +// - "dns://some_authority/foo.bar" +// Target{Scheme: "dns", Authority: "some_authority", Endpoint: "foo.bar"} +// - "foo.bar" +// Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "foo.bar"} +// - "unknown_scheme://authority/endpoint" +// Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "unknown_scheme://authority/endpoint"} type Target struct { - Scheme string + // Deprecated: use URL.Scheme instead. + Scheme string + // Deprecated: use URL.Host instead. Authority string - Endpoint string + // Deprecated: use URL.Path or URL.Opaque instead. The latter is set when + // the former is empty. + Endpoint string + // URL contains the parsed dial target with an optional default scheme added + // to it if the original dial target contained no scheme or contained an + // unregistered scheme. Any query params specified in the original dial + // target can be accessed from here. + URL url.URL } // Builder creates a resolver that will be used to watch name resolution updates. diff --git a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go index 2c47cd54f07c..05a9d4e0bac0 100644 --- a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go +++ b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go @@ -19,7 +19,6 @@ package grpc import ( - "fmt" "strings" "sync" @@ -27,6 +26,7 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" + "google.golang.org/grpc/internal/pretty" "google.golang.org/grpc/resolver" "google.golang.org/grpc/serviceconfig" ) @@ -97,10 +97,7 @@ func (ccr *ccResolverWrapper) UpdateState(s resolver.State) error { if ccr.done.HasFired() { return nil } - channelz.Infof(logger, ccr.cc.channelzID, "ccResolverWrapper: sending update to cc: %v", s) - if channelz.IsOn() { - ccr.addChannelzTraceEvent(s) - } + ccr.addChannelzTraceEvent(s) ccr.curState = s if err := ccr.cc.updateResolverState(ccr.curState, nil); err == balancer.ErrBadResolverState { return balancer.ErrBadResolverState @@ -125,10 +122,7 @@ func (ccr *ccResolverWrapper) NewAddress(addrs []resolver.Address) { if ccr.done.HasFired() { return } - channelz.Infof(logger, ccr.cc.channelzID, "ccResolverWrapper: sending new addresses to cc: %v", addrs) - if channelz.IsOn() { - ccr.addChannelzTraceEvent(resolver.State{Addresses: addrs, ServiceConfig: ccr.curState.ServiceConfig}) - } + ccr.addChannelzTraceEvent(resolver.State{Addresses: addrs, ServiceConfig: ccr.curState.ServiceConfig}) ccr.curState.Addresses = addrs ccr.cc.updateResolverState(ccr.curState, nil) } @@ -141,7 +135,7 @@ func (ccr *ccResolverWrapper) NewServiceConfig(sc string) { if ccr.done.HasFired() { return } - channelz.Infof(logger, ccr.cc.channelzID, "ccResolverWrapper: got new service config: %v", sc) + channelz.Infof(logger, ccr.cc.channelzID, "ccResolverWrapper: got new service config: %s", sc) if ccr.cc.dopts.disableServiceConfig { channelz.Info(logger, ccr.cc.channelzID, "Service config lookups disabled; ignoring config") return @@ -151,9 +145,7 @@ func (ccr *ccResolverWrapper) NewServiceConfig(sc string) { channelz.Warningf(logger, ccr.cc.channelzID, "ccResolverWrapper: error parsing service config: %v", scpr.Err) return } - if channelz.IsOn() { - ccr.addChannelzTraceEvent(resolver.State{Addresses: ccr.curState.Addresses, ServiceConfig: scpr}) - } + ccr.addChannelzTraceEvent(resolver.State{Addresses: ccr.curState.Addresses, ServiceConfig: scpr}) ccr.curState.ServiceConfig = scpr ccr.cc.updateResolverState(ccr.curState, nil) } @@ -180,8 +172,5 @@ func (ccr *ccResolverWrapper) addChannelzTraceEvent(s resolver.State) { } else if len(ccr.curState.Addresses) == 0 && len(s.Addresses) > 0 { updates = append(updates, "resolver returned new addresses") } - channelz.AddTraceEvent(logger, ccr.cc.channelzID, 0, &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Resolver state updated: %+v (%v)", s, strings.Join(updates, "; ")), - Severity: channelz.CtInfo, - }) + channelz.Infof(logger, ccr.cc.channelzID, "Resolver state updated: %s (%v)", pretty.ToJSON(s), strings.Join(updates, "; ")) } diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index 1831a73e73d3..5d407b004b0e 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -712,13 +712,11 @@ func recvAndDecompress(p *parser, s *transport.Stream, dc Decompressor, maxRecei if err != nil { return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) } - } else { - size = len(d) - } - if size > maxReceiveMessageSize { - // TODO: Revisit the error code. Currently keep it consistent with java - // implementation. - return nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", size, maxReceiveMessageSize) + if size > maxReceiveMessageSize { + // TODO: Revisit the error code. Currently keep it consistent with java + // implementation. + return nil, status.Errorf(codes.ResourceExhausted, "grpc: received message after decompression larger than max (%d vs. %d)", size, maxReceiveMessageSize) + } } return d, nil } @@ -829,26 +827,28 @@ func Errorf(c codes.Code, format string, a ...interface{}) error { // toRPCErr converts an error into an error from the status package. func toRPCErr(err error) error { - if err == nil || err == io.EOF { + switch err { + case nil, io.EOF: return err - } - if err == io.ErrUnexpectedEOF { + case context.DeadlineExceeded: + return status.Error(codes.DeadlineExceeded, err.Error()) + case context.Canceled: + return status.Error(codes.Canceled, err.Error()) + case io.ErrUnexpectedEOF: return status.Error(codes.Internal, err.Error()) } - if _, ok := status.FromError(err); ok { - return err - } + switch e := err.(type) { case transport.ConnectionError: return status.Error(codes.Unavailable, e.Desc) - default: - switch err { - case context.DeadlineExceeded: - return status.Error(codes.DeadlineExceeded, err.Error()) - case context.Canceled: - return status.Error(codes.Canceled, err.Error()) - } + case *transport.NewStreamError: + return toRPCErr(e.Err) } + + if _, ok := status.FromError(err); ok { + return err + } + return status.Error(codes.Unknown, err.Error()) } diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index d90f3fcd3bf6..65de84b30074 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -134,7 +134,7 @@ type Server struct { channelzRemoveOnce sync.Once serveWG sync.WaitGroup // counts active Serve goroutines for GracefulStop - channelzID int64 // channelz unique identification number + channelzID *channelz.Identifier czData *channelzData serverWorkerChannels []chan *serverWorkerData @@ -584,9 +584,8 @@ func NewServer(opt ...ServerOption) *Server { s.initServerWorkers() } - if channelz.IsOn() { - s.channelzID = channelz.RegisterServer(&channelzServer{s}, "") - } + s.channelzID = channelz.RegisterServer(&channelzServer{s}, "") + channelz.Info(logger, s.channelzID, "Server created") return s } @@ -710,16 +709,9 @@ func (s *Server) GetServiceInfo() map[string]ServiceInfo { // the server being stopped. var ErrServerStopped = errors.New("grpc: the server has been stopped") -func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - if s.opts.creds == nil { - return rawConn, nil, nil - } - return s.opts.creds.ServerHandshake(rawConn) -} - type listenSocket struct { net.Listener - channelzID int64 + channelzID *channelz.Identifier } func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric { @@ -731,9 +723,8 @@ func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric { func (l *listenSocket) Close() error { err := l.Listener.Close() - if channelz.IsOn() { - channelz.RemoveEntry(l.channelzID) - } + channelz.RemoveEntry(l.channelzID) + channelz.Info(logger, l.channelzID, "ListenSocket deleted") return err } @@ -766,11 +757,6 @@ func (s *Server) Serve(lis net.Listener) error { ls := &listenSocket{Listener: lis} s.lis[ls] = true - if channelz.IsOn() { - ls.channelzID = channelz.RegisterListenSocket(ls, s.channelzID, lis.Addr().String()) - } - s.mu.Unlock() - defer func() { s.mu.Lock() if s.lis != nil && s.lis[ls] { @@ -780,8 +766,16 @@ func (s *Server) Serve(lis net.Listener) error { s.mu.Unlock() }() - var tempDelay time.Duration // how long to sleep on accept failure + var err error + ls.channelzID, err = channelz.RegisterListenSocket(ls, s.channelzID, lis.Addr().String()) + if err != nil { + s.mu.Unlock() + return err + } + s.mu.Unlock() + channelz.Info(logger, ls.channelzID, "ListenSocket created") + var tempDelay time.Duration // how long to sleep on accept failure for { rawConn, err := lis.Accept() if err != nil { @@ -839,34 +833,14 @@ func (s *Server) handleRawConn(lisAddr string, rawConn net.Conn) { return } rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout)) - conn, authInfo, err := s.useTransportAuthenticator(rawConn) - if err != nil { - // ErrConnDispatched means that the connection was dispatched away from - // gRPC; those connections should be left open. - if err != credentials.ErrConnDispatched { - // In deployments where a gRPC server runs behind a cloud load - // balancer which performs regular TCP level health checks, the - // connection is closed immediately by the latter. Skipping the - // error here will help reduce log clutter. - if err != io.EOF { - s.mu.Lock() - s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err) - s.mu.Unlock() - channelz.Warningf(logger, s.channelzID, "grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err) - } - rawConn.Close() - } - rawConn.SetDeadline(time.Time{}) - return - } // Finish handshaking (HTTP2) - st := s.newHTTP2Transport(conn, authInfo) + st := s.newHTTP2Transport(rawConn) + rawConn.SetDeadline(time.Time{}) if st == nil { return } - rawConn.SetDeadline(time.Time{}) if !s.addConn(lisAddr, st) { return } @@ -887,10 +861,11 @@ func (s *Server) drainServerTransports(addr string) { // newHTTP2Transport sets up a http/2 transport (using the // gRPC http2 server transport in transport/http2_server.go). -func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) transport.ServerTransport { +func (s *Server) newHTTP2Transport(c net.Conn) transport.ServerTransport { config := &transport.ServerConfig{ MaxStreams: s.opts.maxConcurrentStreams, - AuthInfo: authInfo, + ConnectionTimeout: s.opts.connectionTimeout, + Credentials: s.opts.creds, InTapHandle: s.opts.inTapHandle, StatsHandler: s.opts.statsHandler, KeepaliveParams: s.opts.keepaliveParams, @@ -908,8 +883,15 @@ func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) tr s.mu.Lock() s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err) s.mu.Unlock() - c.Close() - channelz.Warning(logger, s.channelzID, "grpc: Server.Serve failed to create ServerTransport: ", err) + // ErrConnDispatched means that the connection was dispatched away from + // gRPC; those connections should be left open. + if err != credentials.ErrConnDispatched { + // Don't log on ErrConnDispatched and io.EOF to prevent log spam. + if err != io.EOF { + channelz.Warning(logger, s.channelzID, "grpc: Server.Serve failed to create ServerTransport: ", err) + } + c.Close() + } return nil } @@ -1115,22 +1097,29 @@ func chainUnaryServerInterceptors(s *Server) { } else if len(interceptors) == 1 { chainedInt = interceptors[0] } else { - chainedInt = func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (interface{}, error) { - return interceptors[0](ctx, req, info, getChainUnaryHandler(interceptors, 0, info, handler)) - } + chainedInt = chainUnaryInterceptors(interceptors) } s.opts.unaryInt = chainedInt } -// getChainUnaryHandler recursively generate the chained UnaryHandler -func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info *UnaryServerInfo, finalHandler UnaryHandler) UnaryHandler { - if curr == len(interceptors)-1 { - return finalHandler - } - - return func(ctx context.Context, req interface{}) (interface{}, error) { - return interceptors[curr+1](ctx, req, info, getChainUnaryHandler(interceptors, curr+1, info, finalHandler)) +func chainUnaryInterceptors(interceptors []UnaryServerInterceptor) UnaryServerInterceptor { + return func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (interface{}, error) { + // the struct ensures the variables are allocated together, rather than separately, since we + // know they should be garbage collected together. This saves 1 allocation and decreases + // time/call by about 10% on the microbenchmark. + var state struct { + i int + next UnaryHandler + } + state.next = func(ctx context.Context, req interface{}) (interface{}, error) { + if state.i == len(interceptors)-1 { + return interceptors[state.i](ctx, req, info, handler) + } + state.i++ + return interceptors[state.i-1](ctx, req, info, state.next) + } + return state.next(ctx, req) } } @@ -1144,7 +1133,9 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. if sh != nil { beginTime := time.Now() statsBegin = &stats.Begin{ - BeginTime: beginTime, + BeginTime: beginTime, + IsClientStream: false, + IsServerStream: false, } sh.HandleRPC(stream.Context(), statsBegin) } @@ -1293,9 +1284,10 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. if appErr != nil { appStatus, ok := status.FromError(appErr) if !ok { - // Convert appErr if it is not a grpc status error. - appErr = status.Error(codes.Unknown, appErr.Error()) - appStatus, _ = status.FromError(appErr) + // Convert non-status application error to a status error with code + // Unknown, but handle context errors specifically. + appStatus = status.FromContextError(appErr) + appErr = appStatus.Err() } if trInfo != nil { trInfo.tr.LazyLog(stringer(appStatus.Message()), true) @@ -1396,22 +1388,29 @@ func chainStreamServerInterceptors(s *Server) { } else if len(interceptors) == 1 { chainedInt = interceptors[0] } else { - chainedInt = func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error { - return interceptors[0](srv, ss, info, getChainStreamHandler(interceptors, 0, info, handler)) - } + chainedInt = chainStreamInterceptors(interceptors) } s.opts.streamInt = chainedInt } -// getChainStreamHandler recursively generate the chained StreamHandler -func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, info *StreamServerInfo, finalHandler StreamHandler) StreamHandler { - if curr == len(interceptors)-1 { - return finalHandler - } - - return func(srv interface{}, ss ServerStream) error { - return interceptors[curr+1](srv, ss, info, getChainStreamHandler(interceptors, curr+1, info, finalHandler)) +func chainStreamInterceptors(interceptors []StreamServerInterceptor) StreamServerInterceptor { + return func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error { + // the struct ensures the variables are allocated together, rather than separately, since we + // know they should be garbage collected together. This saves 1 allocation and decreases + // time/call by about 10% on the microbenchmark. + var state struct { + i int + next StreamHandler + } + state.next = func(srv interface{}, ss ServerStream) error { + if state.i == len(interceptors)-1 { + return interceptors[state.i](srv, ss, info, handler) + } + state.i++ + return interceptors[state.i-1](srv, ss, info, state.next) + } + return state.next(srv, ss) } } @@ -1424,7 +1423,9 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp if sh != nil { beginTime := time.Now() statsBegin = &stats.Begin{ - BeginTime: beginTime, + BeginTime: beginTime, + IsClientStream: sd.ClientStreams, + IsServerStream: sd.ServerStreams, } sh.HandleRPC(stream.Context(), statsBegin) } @@ -1550,7 +1551,9 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp if appErr != nil { appStatus, ok := status.FromError(appErr) if !ok { - appStatus = status.New(codes.Unknown, appErr.Error()) + // Convert non-status application error to a status error with code + // Unknown, but handle context errors specifically. + appStatus = status.FromContextError(appErr) appErr = appStatus.Err() } if trInfo != nil { @@ -1707,11 +1710,7 @@ func (s *Server) Stop() { s.done.Fire() }() - s.channelzRemoveOnce.Do(func() { - if channelz.IsOn() { - channelz.RemoveEntry(s.channelzID) - } - }) + s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) }) s.mu.Lock() listeners := s.lis @@ -1749,11 +1748,7 @@ func (s *Server) GracefulStop() { s.quit.Fire() defer s.done.Fire() - s.channelzRemoveOnce.Do(func() { - if channelz.IsOn() { - channelz.RemoveEntry(s.channelzID) - } - }) + s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) }) s.mu.Lock() if s.conns == nil { s.mu.Unlock() @@ -1806,12 +1801,26 @@ func (s *Server) getCodec(contentSubtype string) baseCodec { return codec } -// SetHeader sets the header metadata. -// When called multiple times, all the provided metadata will be merged. -// All the metadata will be sent out when one of the following happens: -// - grpc.SendHeader() is called; -// - The first response is sent out; -// - An RPC status is sent out (error or success). +// SetHeader sets the header metadata to be sent from the server to the client. +// The context provided must be the context passed to the server's handler. +// +// Streaming RPCs should prefer the SetHeader method of the ServerStream. +// +// When called multiple times, all the provided metadata will be merged. All +// the metadata will be sent out when one of the following happens: +// +// - grpc.SendHeader is called, or for streaming handlers, stream.SendHeader. +// - The first response message is sent. For unary handlers, this occurs when +// the handler returns; for streaming handlers, this can happen when stream's +// SendMsg method is called. +// - An RPC status is sent out (error or success). This occurs when the handler +// returns. +// +// SetHeader will fail if called after any of the events above. +// +// The error returned is compatible with the status package. However, the +// status code will often not match the RPC status as seen by the client +// application, and therefore, should not be relied upon for this purpose. func SetHeader(ctx context.Context, md metadata.MD) error { if md.Len() == 0 { return nil @@ -1823,8 +1832,14 @@ func SetHeader(ctx context.Context, md metadata.MD) error { return stream.SetHeader(md) } -// SendHeader sends header metadata. It may be called at most once. -// The provided md and headers set by SetHeader() will be sent. +// SendHeader sends header metadata. It may be called at most once, and may not +// be called after any event that causes headers to be sent (see SetHeader for +// a complete list). The provided md and headers set by SetHeader() will be +// sent. +// +// The error returned is compatible with the status package. However, the +// status code will often not match the RPC status as seen by the client +// application, and therefore, should not be relied upon for this purpose. func SendHeader(ctx context.Context, md metadata.MD) error { stream := ServerTransportStreamFromContext(ctx) if stream == nil { @@ -1838,6 +1853,10 @@ func SendHeader(ctx context.Context, md metadata.MD) error { // SetTrailer sets the trailer metadata that will be sent when an RPC returns. // When called more than once, all the provided metadata will be merged. +// +// The error returned is compatible with the status package. However, the +// status code will often not match the RPC status as seen by the client +// application, and therefore, should not be relied upon for this purpose. func SetTrailer(ctx context.Context, md metadata.MD) error { if md.Len() == 0 { return nil diff --git a/vendor/google.golang.org/grpc/service_config.go b/vendor/google.golang.org/grpc/service_config.go index 22c4240cf7e8..b01c548bb9a9 100644 --- a/vendor/google.golang.org/grpc/service_config.go +++ b/vendor/google.golang.org/grpc/service_config.go @@ -218,7 +218,7 @@ type jsonSC struct { } func init() { - internal.ParseServiceConfigForTesting = parseServiceConfig + internal.ParseServiceConfig = parseServiceConfig } func parseServiceConfig(js string) *serviceconfig.ParseResult { if len(js) == 0 { @@ -381,6 +381,9 @@ func init() { // // If any of them is NOT *ServiceConfig, return false. func equalServiceConfig(a, b serviceconfig.Config) bool { + if a == nil && b == nil { + return true + } aa, ok := a.(*ServiceConfig) if !ok { return false diff --git a/vendor/google.golang.org/grpc/stats/stats.go b/vendor/google.golang.org/grpc/stats/stats.go index 63e476ee7ff8..0285dcc6a268 100644 --- a/vendor/google.golang.org/grpc/stats/stats.go +++ b/vendor/google.golang.org/grpc/stats/stats.go @@ -36,15 +36,22 @@ type RPCStats interface { IsClient() bool } -// Begin contains stats when an RPC begins. +// Begin contains stats when an RPC attempt begins. // FailFast is only valid if this Begin is from client side. type Begin struct { // Client is true if this Begin is from client side. Client bool - // BeginTime is the time when the RPC begins. + // BeginTime is the time when the RPC attempt begins. BeginTime time.Time // FailFast indicates if this RPC is failfast. FailFast bool + // IsClientStream indicates whether the RPC is a client streaming RPC. + IsClientStream bool + // IsServerStream indicates whether the RPC is a server streaming RPC. + IsServerStream bool + // IsTransparentRetryAttempt indicates whether this attempt was initiated + // due to transparently retrying a previous attempt. + IsTransparentRetryAttempt bool } // IsClient indicates if the stats information is from client side. diff --git a/vendor/google.golang.org/grpc/status/status.go b/vendor/google.golang.org/grpc/status/status.go index 54d187186b8f..6d163b6e3842 100644 --- a/vendor/google.golang.org/grpc/status/status.go +++ b/vendor/google.golang.org/grpc/status/status.go @@ -29,6 +29,7 @@ package status import ( "context" + "errors" "fmt" spb "google.golang.org/genproto/googleapis/rpc/status" @@ -73,11 +74,16 @@ func FromProto(s *spb.Status) *Status { return status.FromProto(s) } -// FromError returns a Status representing err if it was produced by this -// package or has a method `GRPCStatus() *Status`. -// If err is nil, a Status is returned with codes.OK and no message. -// Otherwise, ok is false and a Status is returned with codes.Unknown and -// the original error message. +// FromError returns a Status representation of err. +// +// - If err was produced by this package or implements the method `GRPCStatus() +// *Status`, the appropriate Status is returned. +// +// - If err is nil, a Status is returned with codes.OK and no message. +// +// - Otherwise, err is an error not compatible with this package. In this +// case, a Status is returned with codes.Unknown and err's Error() message, +// and ok is false. func FromError(err error) (s *Status, ok bool) { if err == nil { return nil, true @@ -112,18 +118,18 @@ func Code(err error) codes.Code { return codes.Unknown } -// FromContextError converts a context error into a Status. It returns a -// Status with codes.OK if err is nil, or a Status with codes.Unknown if err is -// non-nil and not a context error. +// FromContextError converts a context error or wrapped context error into a +// Status. It returns a Status with codes.OK if err is nil, or a Status with +// codes.Unknown if err is non-nil and not a context error. func FromContextError(err error) *Status { - switch err { - case nil: + if err == nil { return nil - case context.DeadlineExceeded: + } + if errors.Is(err, context.DeadlineExceeded) { return New(codes.DeadlineExceeded, err.Error()) - case context.Canceled: + } + if errors.Is(err, context.Canceled) { return New(codes.Canceled, err.Error()) - default: - return New(codes.Unknown, err.Error()) } + return New(codes.Unknown, err.Error()) } diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index 1f3e70d2c440..236fc17ec3c4 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -36,6 +36,7 @@ import ( "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcrand" "google.golang.org/grpc/internal/grpcutil" + imetadata "google.golang.org/grpc/internal/metadata" iresolver "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/serviceconfig" "google.golang.org/grpc/internal/transport" @@ -46,10 +47,12 @@ import ( ) // StreamHandler defines the handler called by gRPC server to complete the -// execution of a streaming RPC. If a StreamHandler returns an error, it -// should be produced by the status package, or else gRPC will use -// codes.Unknown as the status code and err.Error() as the status message -// of the RPC. +// execution of a streaming RPC. +// +// If a StreamHandler returns an error, it should either be produced by the +// status package, or be one of the context errors. Otherwise, gRPC will use +// codes.Unknown as the status code and err.Error() as the status message of the +// RPC. type StreamHandler func(srv interface{}, stream ServerStream) error // StreamDesc represents a streaming RPC service's method specification. Used @@ -164,6 +167,11 @@ func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth } func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { + if md, _, ok := metadata.FromOutgoingContextRaw(ctx); ok { + if err := imetadata.Validate(md); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + } if channelz.IsOn() { cc.incrCallsStarted() defer func() { @@ -274,33 +282,6 @@ func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *Client if c.creds != nil { callHdr.Creds = c.creds } - var trInfo *traceInfo - if EnableTracing { - trInfo = &traceInfo{ - tr: trace.New("grpc.Sent."+methodFamily(method), method), - firstLine: firstLine{ - client: true, - }, - } - if deadline, ok := ctx.Deadline(); ok { - trInfo.firstLine.deadline = time.Until(deadline) - } - trInfo.tr.LazyLog(&trInfo.firstLine, false) - ctx = trace.NewContext(ctx, trInfo.tr) - } - ctx = newContextWithRPCInfo(ctx, c.failFast, c.codec, cp, comp) - sh := cc.dopts.copts.StatsHandler - var beginTime time.Time - if sh != nil { - ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast}) - beginTime = time.Now() - begin := &stats.Begin{ - Client: true, - BeginTime: beginTime, - FailFast: c.failFast, - } - sh.HandleRPC(ctx, begin) - } cs := &clientStream{ callHdr: callHdr, @@ -314,7 +295,6 @@ func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *Client cp: cp, comp: comp, cancel: cancel, - beginTime: beginTime, firstAttempt: true, onCommit: onCommit, } @@ -323,16 +303,28 @@ func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *Client } cs.binlog = binarylog.GetMethodLogger(method) - // Only this initial attempt has stats/tracing. - // TODO(dfawley): move to newAttempt when per-attempt stats are implemented. - if err := cs.newAttemptLocked(sh, trInfo); err != nil { + cs.attempt, err = cs.newAttemptLocked(false /* isTransparent */) + if err != nil { cs.finish(err) return nil, err } - op := func(a *csAttempt) error { return a.newStream() } + // Pick the transport to use and create a new stream on the transport. + // Assign cs.attempt upon success. + op := func(a *csAttempt) error { + if err := a.getTransport(); err != nil { + return err + } + if err := a.newStream(); err != nil { + return err + } + // Because this operation is always called either here (while creating + // the clientStream) or by the retry code while locked when replaying + // the operation, it is safe to access cs.attempt directly. + cs.attempt = a + return nil + } if err := cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) }); err != nil { - cs.finish(err) return nil, err } @@ -371,63 +363,104 @@ func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *Client return cs, nil } -// newAttemptLocked creates a new attempt with a transport. -// If it succeeds, then it replaces clientStream's attempt with this new attempt. -func (cs *clientStream) newAttemptLocked(sh stats.Handler, trInfo *traceInfo) (retErr error) { - newAttempt := &csAttempt{ - cs: cs, - dc: cs.cc.dopts.dc, - statsHandler: sh, - trInfo: trInfo, +// newAttemptLocked creates a new csAttempt without a transport or stream. +func (cs *clientStream) newAttemptLocked(isTransparent bool) (*csAttempt, error) { + if err := cs.ctx.Err(); err != nil { + return nil, toRPCErr(err) } - defer func() { - if retErr != nil { - // This attempt is not set in the clientStream, so it's finish won't - // be called. Call it here for stats and trace in case they are not - // nil. - newAttempt.finish(retErr) + if err := cs.cc.ctx.Err(); err != nil { + return nil, ErrClientConnClosing + } + + ctx := newContextWithRPCInfo(cs.ctx, cs.callInfo.failFast, cs.callInfo.codec, cs.cp, cs.comp) + method := cs.callHdr.Method + sh := cs.cc.dopts.copts.StatsHandler + var beginTime time.Time + if sh != nil { + ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: cs.callInfo.failFast}) + beginTime = time.Now() + begin := &stats.Begin{ + Client: true, + BeginTime: beginTime, + FailFast: cs.callInfo.failFast, + IsClientStream: cs.desc.ClientStreams, + IsServerStream: cs.desc.ServerStreams, + IsTransparentRetryAttempt: isTransparent, } - }() + sh.HandleRPC(ctx, begin) + } - if err := cs.ctx.Err(); err != nil { - return toRPCErr(err) + var trInfo *traceInfo + if EnableTracing { + trInfo = &traceInfo{ + tr: trace.New("grpc.Sent."+methodFamily(method), method), + firstLine: firstLine{ + client: true, + }, + } + if deadline, ok := ctx.Deadline(); ok { + trInfo.firstLine.deadline = time.Until(deadline) + } + trInfo.tr.LazyLog(&trInfo.firstLine, false) + ctx = trace.NewContext(ctx, trInfo.tr) } - ctx := cs.ctx if cs.cc.parsedTarget.Scheme == "xds" { // Add extra metadata (metadata that will be added by transport) to context // so the balancer can see them. - ctx = grpcutil.WithExtraMetadata(cs.ctx, metadata.Pairs( + ctx = grpcutil.WithExtraMetadata(ctx, metadata.Pairs( "content-type", grpcutil.ContentType(cs.callHdr.ContentSubtype), )) } - t, done, err := cs.cc.getTransport(ctx, cs.callInfo.failFast, cs.callHdr.Method) + + return &csAttempt{ + ctx: ctx, + beginTime: beginTime, + cs: cs, + dc: cs.cc.dopts.dc, + statsHandler: sh, + trInfo: trInfo, + }, nil +} + +func (a *csAttempt) getTransport() error { + cs := a.cs + + var err error + a.t, a.done, err = cs.cc.getTransport(a.ctx, cs.callInfo.failFast, cs.callHdr.Method) if err != nil { + if de, ok := err.(dropError); ok { + err = de.error + a.drop = true + } return err } - if trInfo != nil { - trInfo.firstLine.SetRemoteAddr(t.RemoteAddr()) + if a.trInfo != nil { + a.trInfo.firstLine.SetRemoteAddr(a.t.RemoteAddr()) } - newAttempt.t = t - newAttempt.done = done - cs.attempt = newAttempt return nil } func (a *csAttempt) newStream() error { cs := a.cs cs.callHdr.PreviousAttempts = cs.numRetries - s, err := a.t.NewStream(cs.ctx, cs.callHdr) + s, err := a.t.NewStream(a.ctx, cs.callHdr) if err != nil { - if _, ok := err.(transport.PerformedIOError); ok { - // Return without converting to an RPC error so retry code can - // inspect. + nse, ok := err.(*transport.NewStreamError) + if !ok { + // Unexpected. return err } - return toRPCErr(err) + + if nse.AllowTransparentRetry { + a.allowTransparentRetry = true + } + + // Unwrap and convert error. + return toRPCErr(nse.Err) } - cs.attempt.s = s - cs.attempt.p = &parser{r: s} + a.s = s + a.p = &parser{r: s} return nil } @@ -445,8 +478,7 @@ type clientStream struct { cancel context.CancelFunc // cancels all attempts - sentLast bool // sent an end stream - beginTime time.Time + sentLast bool // sent an end stream methodConfig *MethodConfig @@ -454,7 +486,7 @@ type clientStream struct { retryThrottler *retryThrottler // The throttler active when the RPC began. - binlog *binarylog.MethodLogger // Binary logger, can be nil. + binlog binarylog.MethodLogger // Binary logger, can be nil. // serverHeaderBinlogged is a boolean for whether server header has been // logged. Server header will be logged when the first time one of those // happens: stream.Header(), stream.Recv(). @@ -486,6 +518,7 @@ type clientStream struct { // csAttempt implements a single transport stream attempt within a // clientStream. type csAttempt struct { + ctx context.Context cs *clientStream t transport.ClientTransport s *transport.Stream @@ -504,6 +537,12 @@ type csAttempt struct { trInfo *traceInfo statsHandler stats.Handler + beginTime time.Time + + // set for newStream errors that may be transparently retried + allowTransparentRetry bool + // set for pick errors that are returned as a status + drop bool } func (cs *clientStream) commitAttemptLocked() { @@ -521,85 +560,76 @@ func (cs *clientStream) commitAttempt() { } // shouldRetry returns nil if the RPC should be retried; otherwise it returns -// the error that should be returned by the operation. -func (cs *clientStream) shouldRetry(err error) error { - unprocessed := false - if cs.attempt.s == nil { - pioErr, ok := err.(transport.PerformedIOError) - if ok { - // Unwrap error. - err = toRPCErr(pioErr.Err) - } else { - unprocessed = true - } - if !ok && !cs.callInfo.failFast { - // In the event of a non-IO operation error from NewStream, we - // never attempted to write anything to the wire, so we can retry - // indefinitely for non-fail-fast RPCs. - return nil - } +// the error that should be returned by the operation. If the RPC should be +// retried, the bool indicates whether it is being retried transparently. +func (a *csAttempt) shouldRetry(err error) (bool, error) { + cs := a.cs + + if cs.finished || cs.committed || a.drop { + // RPC is finished or committed or was dropped by the picker; cannot retry. + return false, err } - if cs.finished || cs.committed { - // RPC is finished or committed; cannot retry. - return err + if a.s == nil && a.allowTransparentRetry { + return true, nil } // Wait for the trailers. - if cs.attempt.s != nil { - <-cs.attempt.s.Done() - unprocessed = cs.attempt.s.Unprocessed() + unprocessed := false + if a.s != nil { + <-a.s.Done() + unprocessed = a.s.Unprocessed() } if cs.firstAttempt && unprocessed { // First attempt, stream unprocessed: transparently retry. - return nil + return true, nil } if cs.cc.dopts.disableRetry { - return err + return false, err } pushback := 0 hasPushback := false - if cs.attempt.s != nil { - if !cs.attempt.s.TrailersOnly() { - return err + if a.s != nil { + if !a.s.TrailersOnly() { + return false, err } // TODO(retry): Move down if the spec changes to not check server pushback // before considering this a failure for throttling. - sps := cs.attempt.s.Trailer()["grpc-retry-pushback-ms"] + sps := a.s.Trailer()["grpc-retry-pushback-ms"] if len(sps) == 1 { var e error if pushback, e = strconv.Atoi(sps[0]); e != nil || pushback < 0 { channelz.Infof(logger, cs.cc.channelzID, "Server retry pushback specified to abort (%q).", sps[0]) cs.retryThrottler.throttle() // This counts as a failure for throttling. - return err + return false, err } hasPushback = true } else if len(sps) > 1 { channelz.Warningf(logger, cs.cc.channelzID, "Server retry pushback specified multiple values (%q); not retrying.", sps) cs.retryThrottler.throttle() // This counts as a failure for throttling. - return err + return false, err } } var code codes.Code - if cs.attempt.s != nil { - code = cs.attempt.s.Status().Code() + if a.s != nil { + code = a.s.Status().Code() } else { - code = status.Convert(err).Code() + code = status.Code(err) } rp := cs.methodConfig.RetryPolicy if rp == nil || !rp.RetryableStatusCodes[code] { - return err + return false, err } // Note: the ordering here is important; we count this as a failure // only if the code matched a retryable code. if cs.retryThrottler.throttle() { - return err + return false, err } if cs.numRetries+1 >= rp.MaxAttempts { - return err + return false, err } var dur time.Duration @@ -622,26 +652,32 @@ func (cs *clientStream) shouldRetry(err error) error { select { case <-t.C: cs.numRetries++ - return nil + return false, nil case <-cs.ctx.Done(): t.Stop() - return status.FromContextError(cs.ctx.Err()).Err() + return false, status.FromContextError(cs.ctx.Err()).Err() } } // Returns nil if a retry was performed and succeeded; error otherwise. -func (cs *clientStream) retryLocked(lastErr error) error { +func (cs *clientStream) retryLocked(attempt *csAttempt, lastErr error) error { for { - cs.attempt.finish(lastErr) - if err := cs.shouldRetry(lastErr); err != nil { + attempt.finish(toRPCErr(lastErr)) + isTransparent, err := attempt.shouldRetry(lastErr) + if err != nil { cs.commitAttemptLocked() return err } cs.firstAttempt = false - if err := cs.newAttemptLocked(nil, nil); err != nil { + attempt, err = cs.newAttemptLocked(isTransparent) + if err != nil { + // Only returns error if the clientconn is closed or the context of + // the stream is canceled. return err } - if lastErr = cs.replayBufferLocked(); lastErr == nil { + // Note that the first op in the replay buffer always sets cs.attempt + // if it is able to pick a transport and create a stream. + if lastErr = cs.replayBufferLocked(attempt); lastErr == nil { return nil } } @@ -651,7 +687,10 @@ func (cs *clientStream) Context() context.Context { cs.commitAttempt() // No need to lock before using attempt, since we know it is committed and // cannot change. - return cs.attempt.s.Context() + if cs.attempt.s != nil { + return cs.attempt.s.Context() + } + return cs.ctx } func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) error { @@ -659,7 +698,11 @@ func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) for { if cs.committed { cs.mu.Unlock() - return op(cs.attempt) + // toRPCErr is used in case the error from the attempt comes from + // NewClientStream, which intentionally doesn't return a status + // error to allow for further inspection; all other errors should + // already be status errors. + return toRPCErr(op(cs.attempt)) } a := cs.attempt cs.mu.Unlock() @@ -677,7 +720,7 @@ func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) cs.mu.Unlock() return err } - if err := cs.retryLocked(err); err != nil { + if err := cs.retryLocked(a, err); err != nil { cs.mu.Unlock() return err } @@ -708,7 +751,7 @@ func (cs *clientStream) Header() (metadata.MD, error) { cs.binlog.Log(logEntry) cs.serverHeaderBinlogged = true } - return m, err + return m, nil } func (cs *clientStream) Trailer() metadata.MD { @@ -726,10 +769,9 @@ func (cs *clientStream) Trailer() metadata.MD { return cs.attempt.s.Trailer() } -func (cs *clientStream) replayBufferLocked() error { - a := cs.attempt +func (cs *clientStream) replayBufferLocked(attempt *csAttempt) error { for _, f := range cs.buffer { - if err := f(a); err != nil { + if err := f(attempt); err != nil { return err } } @@ -777,22 +819,17 @@ func (cs *clientStream) SendMsg(m interface{}) (err error) { if len(payload) > *cs.callInfo.maxSendMessageSize { return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), *cs.callInfo.maxSendMessageSize) } - msgBytes := data // Store the pointer before setting to nil. For binary logging. op := func(a *csAttempt) error { - err := a.sendMsg(m, hdr, payload, data) - // nil out the message and uncomp when replaying; they are only needed for - // stats which is disabled for subsequent attempts. - m, data = nil, nil - return err + return a.sendMsg(m, hdr, payload, data) } err = cs.withRetry(op, func() { cs.bufferForRetryLocked(len(hdr)+len(payload), op) }) if cs.binlog != nil && err == nil { cs.binlog.Log(&binarylog.ClientMessage{ OnClientSide: true, - Message: msgBytes, + Message: data, }) } - return + return err } func (cs *clientStream) RecvMsg(m interface{}) error { @@ -924,7 +961,7 @@ func (a *csAttempt) sendMsg(m interface{}, hdr, payld, data []byte) error { return io.EOF } if a.statsHandler != nil { - a.statsHandler.HandleRPC(cs.ctx, outPayload(true, m, data, payld, time.Now())) + a.statsHandler.HandleRPC(a.ctx, outPayload(true, m, data, payld, time.Now())) } if channelz.IsOn() { a.t.IncrMsgSent() @@ -972,7 +1009,7 @@ func (a *csAttempt) recvMsg(m interface{}, payInfo *payloadInfo) (err error) { a.mu.Unlock() } if a.statsHandler != nil { - a.statsHandler.HandleRPC(cs.ctx, &stats.InPayload{ + a.statsHandler.HandleRPC(a.ctx, &stats.InPayload{ Client: true, RecvTime: time.Now(), Payload: m, @@ -1034,12 +1071,12 @@ func (a *csAttempt) finish(err error) { if a.statsHandler != nil { end := &stats.End{ Client: true, - BeginTime: a.cs.beginTime, + BeginTime: a.beginTime, EndTime: time.Now(), Trailer: tr, Error: err, } - a.statsHandler.HandleRPC(a.cs.ctx, end) + a.statsHandler.HandleRPC(a.ctx, end) } if a.trInfo != nil && a.trInfo.tr != nil { if err == nil { @@ -1344,8 +1381,10 @@ func (as *addrConnStream) finish(err error) { // ServerStream defines the server-side behavior of a streaming RPC. // -// All errors returned from ServerStream methods are compatible with the -// status package. +// Errors returned from ServerStream methods are compatible with the status +// package. However, the status code will often not match the RPC status as +// seen by the client application, and therefore, should not be relied upon for +// this purpose. type ServerStream interface { // SetHeader sets the header metadata. It may be called multiple times. // When call multiple times, all the provided metadata will be merged. @@ -1408,7 +1447,7 @@ type serverStream struct { statsHandler stats.Handler - binlog *binarylog.MethodLogger + binlog binarylog.MethodLogger // serverHeaderBinlogged indicates whether server header has been logged. It // will happen when one of the following two happens: stream.SendHeader(), // stream.Send(). @@ -1428,11 +1467,20 @@ func (ss *serverStream) SetHeader(md metadata.MD) error { if md.Len() == 0 { return nil } + err := imetadata.Validate(md) + if err != nil { + return status.Error(codes.Internal, err.Error()) + } return ss.s.SetHeader(md) } func (ss *serverStream) SendHeader(md metadata.MD) error { - err := ss.t.WriteHeader(ss.s, md) + err := imetadata.Validate(md) + if err != nil { + return status.Error(codes.Internal, err.Error()) + } + + err = ss.t.WriteHeader(ss.s, md) if ss.binlog != nil && !ss.serverHeaderBinlogged { h, _ := ss.s.Header() ss.binlog.Log(&binarylog.ServerHeader{ @@ -1447,6 +1495,9 @@ func (ss *serverStream) SetTrailer(md metadata.MD) { if md.Len() == 0 { return } + if err := imetadata.Validate(md); err != nil { + logger.Errorf("stream: failed to validate md when setting trailer, err: %v", err) + } ss.s.SetTrailer(md) } diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go index 3dd146afb18d..5bc03f9b3612 100644 --- a/vendor/google.golang.org/grpc/version.go +++ b/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.39.0" +const Version = "1.47.0" diff --git a/vendor/google.golang.org/grpc/vet.sh b/vendor/google.golang.org/grpc/vet.sh index 5eaa8b05d6d3..ceb436c6ce47 100644 --- a/vendor/google.golang.org/grpc/vet.sh +++ b/vendor/google.golang.org/grpc/vet.sh @@ -89,10 +89,6 @@ not git grep "\(import \|^\s*\)\"github.com/golang/protobuf/ptypes/" -- "*.go" # - Ensure all xds proto imports are renamed to *pb or *grpc. git grep '"github.com/envoyproxy/go-control-plane/envoy' -- '*.go' ':(exclude)*.pb.go' | not grep -v 'pb "\|grpc "' -# - Check imports that are illegal in appengine (until Go 1.11). -# TODO: Remove when we drop Go 1.10 support -go list -f {{.Dir}} ./... | xargs go run test/go_vet/vet.go - misspell -error . # - Check that generated proto files are up to date. @@ -111,7 +107,7 @@ for MOD_FILE in $(find . -name 'go.mod'); do go vet -all ./... | fail_on_output gofmt -s -d -l . 2>&1 | fail_on_output goimports -l . 2>&1 | not grep -vE "\.pb\.go" - golint ./... 2>&1 | not grep -vE "/testv3\.pb\.go:" + golint ./... 2>&1 | not grep -vE "/grpc_testing_not_regenerate/.*\.pb\.go:" go mod tidy git status --porcelain 2>&1 | fail_on_output || \ diff --git a/vendor/google.golang.org/protobuf/encoding/protojson/decode.go b/vendor/google.golang.org/protobuf/encoding/protojson/decode.go new file mode 100644 index 000000000000..07da5db3450e --- /dev/null +++ b/vendor/google.golang.org/protobuf/encoding/protojson/decode.go @@ -0,0 +1,665 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protojson + +import ( + "encoding/base64" + "fmt" + "math" + "strconv" + "strings" + + "google.golang.org/protobuf/internal/encoding/json" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/internal/set" + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +// Unmarshal reads the given []byte into the given proto.Message. +// The provided message must be mutable (e.g., a non-nil pointer to a message). +func Unmarshal(b []byte, m proto.Message) error { + return UnmarshalOptions{}.Unmarshal(b, m) +} + +// UnmarshalOptions is a configurable JSON format parser. +type UnmarshalOptions struct { + pragma.NoUnkeyedLiterals + + // If AllowPartial is set, input for messages that will result in missing + // required fields will not return an error. + AllowPartial bool + + // If DiscardUnknown is set, unknown fields are ignored. + DiscardUnknown bool + + // Resolver is used for looking up types when unmarshaling + // google.protobuf.Any messages or extension fields. + // If nil, this defaults to using protoregistry.GlobalTypes. + Resolver interface { + protoregistry.MessageTypeResolver + protoregistry.ExtensionTypeResolver + } +} + +// Unmarshal reads the given []byte and populates the given proto.Message +// using options in the UnmarshalOptions object. +// It will clear the message first before setting the fields. +// If it returns an error, the given message may be partially set. +// The provided message must be mutable (e.g., a non-nil pointer to a message). +func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error { + return o.unmarshal(b, m) +} + +// unmarshal is a centralized function that all unmarshal operations go through. +// For profiling purposes, avoid changing the name of this function or +// introducing other code paths for unmarshal that do not go through this. +func (o UnmarshalOptions) unmarshal(b []byte, m proto.Message) error { + proto.Reset(m) + + if o.Resolver == nil { + o.Resolver = protoregistry.GlobalTypes + } + + dec := decoder{json.NewDecoder(b), o} + if err := dec.unmarshalMessage(m.ProtoReflect(), false); err != nil { + return err + } + + // Check for EOF. + tok, err := dec.Read() + if err != nil { + return err + } + if tok.Kind() != json.EOF { + return dec.unexpectedTokenError(tok) + } + + if o.AllowPartial { + return nil + } + return proto.CheckInitialized(m) +} + +type decoder struct { + *json.Decoder + opts UnmarshalOptions +} + +// newError returns an error object with position info. +func (d decoder) newError(pos int, f string, x ...interface{}) error { + line, column := d.Position(pos) + head := fmt.Sprintf("(line %d:%d): ", line, column) + return errors.New(head+f, x...) +} + +// unexpectedTokenError returns a syntax error for the given unexpected token. +func (d decoder) unexpectedTokenError(tok json.Token) error { + return d.syntaxError(tok.Pos(), "unexpected token %s", tok.RawString()) +} + +// syntaxError returns a syntax error for given position. +func (d decoder) syntaxError(pos int, f string, x ...interface{}) error { + line, column := d.Position(pos) + head := fmt.Sprintf("syntax error (line %d:%d): ", line, column) + return errors.New(head+f, x...) +} + +// unmarshalMessage unmarshals a message into the given protoreflect.Message. +func (d decoder) unmarshalMessage(m pref.Message, skipTypeURL bool) error { + if unmarshal := wellKnownTypeUnmarshaler(m.Descriptor().FullName()); unmarshal != nil { + return unmarshal(d, m) + } + + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.ObjectOpen { + return d.unexpectedTokenError(tok) + } + + messageDesc := m.Descriptor() + if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { + return errors.New("no support for proto1 MessageSets") + } + + var seenNums set.Ints + var seenOneofs set.Ints + fieldDescs := messageDesc.Fields() + for { + // Read field name. + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + default: + return d.unexpectedTokenError(tok) + case json.ObjectClose: + return nil + case json.Name: + // Continue below. + } + + name := tok.Name() + // Unmarshaling a non-custom embedded message in Any will contain the + // JSON field "@type" which should be skipped because it is not a field + // of the embedded message, but simply an artifact of the Any format. + if skipTypeURL && name == "@type" { + d.Read() + continue + } + + // Get the FieldDescriptor. + var fd pref.FieldDescriptor + if strings.HasPrefix(name, "[") && strings.HasSuffix(name, "]") { + // Only extension names are in [name] format. + extName := pref.FullName(name[1 : len(name)-1]) + extType, err := d.opts.Resolver.FindExtensionByName(extName) + if err != nil && err != protoregistry.NotFound { + return d.newError(tok.Pos(), "unable to resolve %s: %v", tok.RawString(), err) + } + if extType != nil { + fd = extType.TypeDescriptor() + if !messageDesc.ExtensionRanges().Has(fd.Number()) || fd.ContainingMessage().FullName() != messageDesc.FullName() { + return d.newError(tok.Pos(), "message %v cannot be extended by %v", messageDesc.FullName(), fd.FullName()) + } + } + } else { + // The name can either be the JSON name or the proto field name. + fd = fieldDescs.ByJSONName(name) + if fd == nil { + fd = fieldDescs.ByTextName(name) + } + } + if flags.ProtoLegacy { + if fd != nil && fd.IsWeak() && fd.Message().IsPlaceholder() { + fd = nil // reset since the weak reference is not linked in + } + } + + if fd == nil { + // Field is unknown. + if d.opts.DiscardUnknown { + if err := d.skipJSONValue(); err != nil { + return err + } + continue + } + return d.newError(tok.Pos(), "unknown field %v", tok.RawString()) + } + + // Do not allow duplicate fields. + num := uint64(fd.Number()) + if seenNums.Has(num) { + return d.newError(tok.Pos(), "duplicate field %v", tok.RawString()) + } + seenNums.Set(num) + + // No need to set values for JSON null unless the field type is + // google.protobuf.Value or google.protobuf.NullValue. + if tok, _ := d.Peek(); tok.Kind() == json.Null && !isKnownValue(fd) && !isNullValue(fd) { + d.Read() + continue + } + + switch { + case fd.IsList(): + list := m.Mutable(fd).List() + if err := d.unmarshalList(list, fd); err != nil { + return err + } + case fd.IsMap(): + mmap := m.Mutable(fd).Map() + if err := d.unmarshalMap(mmap, fd); err != nil { + return err + } + default: + // If field is a oneof, check if it has already been set. + if od := fd.ContainingOneof(); od != nil { + idx := uint64(od.Index()) + if seenOneofs.Has(idx) { + return d.newError(tok.Pos(), "error parsing %s, oneof %v is already set", tok.RawString(), od.FullName()) + } + seenOneofs.Set(idx) + } + + // Required or optional fields. + if err := d.unmarshalSingular(m, fd); err != nil { + return err + } + } + } +} + +func isKnownValue(fd pref.FieldDescriptor) bool { + md := fd.Message() + return md != nil && md.FullName() == genid.Value_message_fullname +} + +func isNullValue(fd pref.FieldDescriptor) bool { + ed := fd.Enum() + return ed != nil && ed.FullName() == genid.NullValue_enum_fullname +} + +// unmarshalSingular unmarshals to the non-repeated field specified +// by the given FieldDescriptor. +func (d decoder) unmarshalSingular(m pref.Message, fd pref.FieldDescriptor) error { + var val pref.Value + var err error + switch fd.Kind() { + case pref.MessageKind, pref.GroupKind: + val = m.NewField(fd) + err = d.unmarshalMessage(val.Message(), false) + default: + val, err = d.unmarshalScalar(fd) + } + + if err != nil { + return err + } + m.Set(fd, val) + return nil +} + +// unmarshalScalar unmarshals to a scalar/enum protoreflect.Value specified by +// the given FieldDescriptor. +func (d decoder) unmarshalScalar(fd pref.FieldDescriptor) (pref.Value, error) { + const b32 int = 32 + const b64 int = 64 + + tok, err := d.Read() + if err != nil { + return pref.Value{}, err + } + + kind := fd.Kind() + switch kind { + case pref.BoolKind: + if tok.Kind() == json.Bool { + return pref.ValueOfBool(tok.Bool()), nil + } + + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + if v, ok := unmarshalInt(tok, b32); ok { + return v, nil + } + + case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind: + if v, ok := unmarshalInt(tok, b64); ok { + return v, nil + } + + case pref.Uint32Kind, pref.Fixed32Kind: + if v, ok := unmarshalUint(tok, b32); ok { + return v, nil + } + + case pref.Uint64Kind, pref.Fixed64Kind: + if v, ok := unmarshalUint(tok, b64); ok { + return v, nil + } + + case pref.FloatKind: + if v, ok := unmarshalFloat(tok, b32); ok { + return v, nil + } + + case pref.DoubleKind: + if v, ok := unmarshalFloat(tok, b64); ok { + return v, nil + } + + case pref.StringKind: + if tok.Kind() == json.String { + return pref.ValueOfString(tok.ParsedString()), nil + } + + case pref.BytesKind: + if v, ok := unmarshalBytes(tok); ok { + return v, nil + } + + case pref.EnumKind: + if v, ok := unmarshalEnum(tok, fd); ok { + return v, nil + } + + default: + panic(fmt.Sprintf("unmarshalScalar: invalid scalar kind %v", kind)) + } + + return pref.Value{}, d.newError(tok.Pos(), "invalid value for %v type: %v", kind, tok.RawString()) +} + +func unmarshalInt(tok json.Token, bitSize int) (pref.Value, bool) { + switch tok.Kind() { + case json.Number: + return getInt(tok, bitSize) + + case json.String: + // Decode number from string. + s := strings.TrimSpace(tok.ParsedString()) + if len(s) != len(tok.ParsedString()) { + return pref.Value{}, false + } + dec := json.NewDecoder([]byte(s)) + tok, err := dec.Read() + if err != nil { + return pref.Value{}, false + } + return getInt(tok, bitSize) + } + return pref.Value{}, false +} + +func getInt(tok json.Token, bitSize int) (pref.Value, bool) { + n, ok := tok.Int(bitSize) + if !ok { + return pref.Value{}, false + } + if bitSize == 32 { + return pref.ValueOfInt32(int32(n)), true + } + return pref.ValueOfInt64(n), true +} + +func unmarshalUint(tok json.Token, bitSize int) (pref.Value, bool) { + switch tok.Kind() { + case json.Number: + return getUint(tok, bitSize) + + case json.String: + // Decode number from string. + s := strings.TrimSpace(tok.ParsedString()) + if len(s) != len(tok.ParsedString()) { + return pref.Value{}, false + } + dec := json.NewDecoder([]byte(s)) + tok, err := dec.Read() + if err != nil { + return pref.Value{}, false + } + return getUint(tok, bitSize) + } + return pref.Value{}, false +} + +func getUint(tok json.Token, bitSize int) (pref.Value, bool) { + n, ok := tok.Uint(bitSize) + if !ok { + return pref.Value{}, false + } + if bitSize == 32 { + return pref.ValueOfUint32(uint32(n)), true + } + return pref.ValueOfUint64(n), true +} + +func unmarshalFloat(tok json.Token, bitSize int) (pref.Value, bool) { + switch tok.Kind() { + case json.Number: + return getFloat(tok, bitSize) + + case json.String: + s := tok.ParsedString() + switch s { + case "NaN": + if bitSize == 32 { + return pref.ValueOfFloat32(float32(math.NaN())), true + } + return pref.ValueOfFloat64(math.NaN()), true + case "Infinity": + if bitSize == 32 { + return pref.ValueOfFloat32(float32(math.Inf(+1))), true + } + return pref.ValueOfFloat64(math.Inf(+1)), true + case "-Infinity": + if bitSize == 32 { + return pref.ValueOfFloat32(float32(math.Inf(-1))), true + } + return pref.ValueOfFloat64(math.Inf(-1)), true + } + + // Decode number from string. + if len(s) != len(strings.TrimSpace(s)) { + return pref.Value{}, false + } + dec := json.NewDecoder([]byte(s)) + tok, err := dec.Read() + if err != nil { + return pref.Value{}, false + } + return getFloat(tok, bitSize) + } + return pref.Value{}, false +} + +func getFloat(tok json.Token, bitSize int) (pref.Value, bool) { + n, ok := tok.Float(bitSize) + if !ok { + return pref.Value{}, false + } + if bitSize == 32 { + return pref.ValueOfFloat32(float32(n)), true + } + return pref.ValueOfFloat64(n), true +} + +func unmarshalBytes(tok json.Token) (pref.Value, bool) { + if tok.Kind() != json.String { + return pref.Value{}, false + } + + s := tok.ParsedString() + enc := base64.StdEncoding + if strings.ContainsAny(s, "-_") { + enc = base64.URLEncoding + } + if len(s)%4 != 0 { + enc = enc.WithPadding(base64.NoPadding) + } + b, err := enc.DecodeString(s) + if err != nil { + return pref.Value{}, false + } + return pref.ValueOfBytes(b), true +} + +func unmarshalEnum(tok json.Token, fd pref.FieldDescriptor) (pref.Value, bool) { + switch tok.Kind() { + case json.String: + // Lookup EnumNumber based on name. + s := tok.ParsedString() + if enumVal := fd.Enum().Values().ByName(pref.Name(s)); enumVal != nil { + return pref.ValueOfEnum(enumVal.Number()), true + } + + case json.Number: + if n, ok := tok.Int(32); ok { + return pref.ValueOfEnum(pref.EnumNumber(n)), true + } + + case json.Null: + // This is only valid for google.protobuf.NullValue. + if isNullValue(fd) { + return pref.ValueOfEnum(0), true + } + } + + return pref.Value{}, false +} + +func (d decoder) unmarshalList(list pref.List, fd pref.FieldDescriptor) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.ArrayOpen { + return d.unexpectedTokenError(tok) + } + + switch fd.Kind() { + case pref.MessageKind, pref.GroupKind: + for { + tok, err := d.Peek() + if err != nil { + return err + } + + if tok.Kind() == json.ArrayClose { + d.Read() + return nil + } + + val := list.NewElement() + if err := d.unmarshalMessage(val.Message(), false); err != nil { + return err + } + list.Append(val) + } + default: + for { + tok, err := d.Peek() + if err != nil { + return err + } + + if tok.Kind() == json.ArrayClose { + d.Read() + return nil + } + + val, err := d.unmarshalScalar(fd) + if err != nil { + return err + } + list.Append(val) + } + } + + return nil +} + +func (d decoder) unmarshalMap(mmap pref.Map, fd pref.FieldDescriptor) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.ObjectOpen { + return d.unexpectedTokenError(tok) + } + + // Determine ahead whether map entry is a scalar type or a message type in + // order to call the appropriate unmarshalMapValue func inside the for loop + // below. + var unmarshalMapValue func() (pref.Value, error) + switch fd.MapValue().Kind() { + case pref.MessageKind, pref.GroupKind: + unmarshalMapValue = func() (pref.Value, error) { + val := mmap.NewValue() + if err := d.unmarshalMessage(val.Message(), false); err != nil { + return pref.Value{}, err + } + return val, nil + } + default: + unmarshalMapValue = func() (pref.Value, error) { + return d.unmarshalScalar(fd.MapValue()) + } + } + +Loop: + for { + // Read field name. + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + default: + return d.unexpectedTokenError(tok) + case json.ObjectClose: + break Loop + case json.Name: + // Continue. + } + + // Unmarshal field name. + pkey, err := d.unmarshalMapKey(tok, fd.MapKey()) + if err != nil { + return err + } + + // Check for duplicate field name. + if mmap.Has(pkey) { + return d.newError(tok.Pos(), "duplicate map key %v", tok.RawString()) + } + + // Read and unmarshal field value. + pval, err := unmarshalMapValue() + if err != nil { + return err + } + + mmap.Set(pkey, pval) + } + + return nil +} + +// unmarshalMapKey converts given token of Name kind into a protoreflect.MapKey. +// A map key type is any integral or string type. +func (d decoder) unmarshalMapKey(tok json.Token, fd pref.FieldDescriptor) (pref.MapKey, error) { + const b32 = 32 + const b64 = 64 + const base10 = 10 + + name := tok.Name() + kind := fd.Kind() + switch kind { + case pref.StringKind: + return pref.ValueOfString(name).MapKey(), nil + + case pref.BoolKind: + switch name { + case "true": + return pref.ValueOfBool(true).MapKey(), nil + case "false": + return pref.ValueOfBool(false).MapKey(), nil + } + + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + if n, err := strconv.ParseInt(name, base10, b32); err == nil { + return pref.ValueOfInt32(int32(n)).MapKey(), nil + } + + case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind: + if n, err := strconv.ParseInt(name, base10, b64); err == nil { + return pref.ValueOfInt64(int64(n)).MapKey(), nil + } + + case pref.Uint32Kind, pref.Fixed32Kind: + if n, err := strconv.ParseUint(name, base10, b32); err == nil { + return pref.ValueOfUint32(uint32(n)).MapKey(), nil + } + + case pref.Uint64Kind, pref.Fixed64Kind: + if n, err := strconv.ParseUint(name, base10, b64); err == nil { + return pref.ValueOfUint64(uint64(n)).MapKey(), nil + } + + default: + panic(fmt.Sprintf("invalid kind for map key: %v", kind)) + } + + return pref.MapKey{}, d.newError(tok.Pos(), "invalid value for %v key: %s", kind, tok.RawString()) +} diff --git a/vendor/google.golang.org/protobuf/encoding/protojson/doc.go b/vendor/google.golang.org/protobuf/encoding/protojson/doc.go new file mode 100644 index 000000000000..00ea2fecfb79 --- /dev/null +++ b/vendor/google.golang.org/protobuf/encoding/protojson/doc.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package protojson marshals and unmarshals protocol buffer messages as JSON +// format. It follows the guide at +// https://developers.google.com/protocol-buffers/docs/proto3#json. +// +// This package produces a different output than the standard "encoding/json" +// package, which does not operate correctly on protocol buffer messages. +package protojson diff --git a/vendor/google.golang.org/protobuf/encoding/protojson/encode.go b/vendor/google.golang.org/protobuf/encoding/protojson/encode.go new file mode 100644 index 000000000000..ba971f07810c --- /dev/null +++ b/vendor/google.golang.org/protobuf/encoding/protojson/encode.go @@ -0,0 +1,344 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protojson + +import ( + "encoding/base64" + "fmt" + + "google.golang.org/protobuf/internal/encoding/json" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/order" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + pref "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +const defaultIndent = " " + +// Format formats the message as a multiline string. +// This function is only intended for human consumption and ignores errors. +// Do not depend on the output being stable. It may change over time across +// different versions of the program. +func Format(m proto.Message) string { + return MarshalOptions{Multiline: true}.Format(m) +} + +// Marshal writes the given proto.Message in JSON format using default options. +// Do not depend on the output being stable. It may change over time across +// different versions of the program. +func Marshal(m proto.Message) ([]byte, error) { + return MarshalOptions{}.Marshal(m) +} + +// MarshalOptions is a configurable JSON format marshaler. +type MarshalOptions struct { + pragma.NoUnkeyedLiterals + + // Multiline specifies whether the marshaler should format the output in + // indented-form with every textual element on a new line. + // If Indent is an empty string, then an arbitrary indent is chosen. + Multiline bool + + // Indent specifies the set of indentation characters to use in a multiline + // formatted output such that every entry is preceded by Indent and + // terminated by a newline. If non-empty, then Multiline is treated as true. + // Indent can only be composed of space or tab characters. + Indent string + + // AllowPartial allows messages that have missing required fields to marshal + // without returning an error. If AllowPartial is false (the default), + // Marshal will return error if there are any missing required fields. + AllowPartial bool + + // UseProtoNames uses proto field name instead of lowerCamelCase name in JSON + // field names. + UseProtoNames bool + + // UseEnumNumbers emits enum values as numbers. + UseEnumNumbers bool + + // EmitUnpopulated specifies whether to emit unpopulated fields. It does not + // emit unpopulated oneof fields or unpopulated extension fields. + // The JSON value emitted for unpopulated fields are as follows: + // ╔═══════╤════════════════════════════╗ + // ║ JSON │ Protobuf field ║ + // ╠═══════╪════════════════════════════╣ + // ║ false │ proto3 boolean fields ║ + // ║ 0 │ proto3 numeric fields ║ + // ║ "" │ proto3 string/bytes fields ║ + // ║ null │ proto2 scalar fields ║ + // ║ null │ message fields ║ + // ║ [] │ list fields ║ + // ║ {} │ map fields ║ + // ╚═══════╧════════════════════════════╝ + EmitUnpopulated bool + + // Resolver is used for looking up types when expanding google.protobuf.Any + // messages. If nil, this defaults to using protoregistry.GlobalTypes. + Resolver interface { + protoregistry.ExtensionTypeResolver + protoregistry.MessageTypeResolver + } +} + +// Format formats the message as a string. +// This method is only intended for human consumption and ignores errors. +// Do not depend on the output being stable. It may change over time across +// different versions of the program. +func (o MarshalOptions) Format(m proto.Message) string { + if m == nil || !m.ProtoReflect().IsValid() { + return "" // invalid syntax, but okay since this is for debugging + } + o.AllowPartial = true + b, _ := o.Marshal(m) + return string(b) +} + +// Marshal marshals the given proto.Message in the JSON format using options in +// MarshalOptions. Do not depend on the output being stable. It may change over +// time across different versions of the program. +func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) { + return o.marshal(m) +} + +// marshal is a centralized function that all marshal operations go through. +// For profiling purposes, avoid changing the name of this function or +// introducing other code paths for marshal that do not go through this. +func (o MarshalOptions) marshal(m proto.Message) ([]byte, error) { + if o.Multiline && o.Indent == "" { + o.Indent = defaultIndent + } + if o.Resolver == nil { + o.Resolver = protoregistry.GlobalTypes + } + + internalEnc, err := json.NewEncoder(o.Indent) + if err != nil { + return nil, err + } + + // Treat nil message interface as an empty message, + // in which case the output in an empty JSON object. + if m == nil { + return []byte("{}"), nil + } + + enc := encoder{internalEnc, o} + if err := enc.marshalMessage(m.ProtoReflect(), ""); err != nil { + return nil, err + } + if o.AllowPartial { + return enc.Bytes(), nil + } + return enc.Bytes(), proto.CheckInitialized(m) +} + +type encoder struct { + *json.Encoder + opts MarshalOptions +} + +// typeFieldDesc is a synthetic field descriptor used for the "@type" field. +var typeFieldDesc = func() protoreflect.FieldDescriptor { + var fd filedesc.Field + fd.L0.FullName = "@type" + fd.L0.Index = -1 + fd.L1.Cardinality = protoreflect.Optional + fd.L1.Kind = protoreflect.StringKind + return &fd +}() + +// typeURLFieldRanger wraps a protoreflect.Message and modifies its Range method +// to additionally iterate over a synthetic field for the type URL. +type typeURLFieldRanger struct { + order.FieldRanger + typeURL string +} + +func (m typeURLFieldRanger) Range(f func(pref.FieldDescriptor, pref.Value) bool) { + if !f(typeFieldDesc, pref.ValueOfString(m.typeURL)) { + return + } + m.FieldRanger.Range(f) +} + +// unpopulatedFieldRanger wraps a protoreflect.Message and modifies its Range +// method to additionally iterate over unpopulated fields. +type unpopulatedFieldRanger struct{ pref.Message } + +func (m unpopulatedFieldRanger) Range(f func(pref.FieldDescriptor, pref.Value) bool) { + fds := m.Descriptor().Fields() + for i := 0; i < fds.Len(); i++ { + fd := fds.Get(i) + if m.Has(fd) || fd.ContainingOneof() != nil { + continue // ignore populated fields and fields within a oneofs + } + + v := m.Get(fd) + isProto2Scalar := fd.Syntax() == pref.Proto2 && fd.Default().IsValid() + isSingularMessage := fd.Cardinality() != pref.Repeated && fd.Message() != nil + if isProto2Scalar || isSingularMessage { + v = pref.Value{} // use invalid value to emit null + } + if !f(fd, v) { + return + } + } + m.Message.Range(f) +} + +// marshalMessage marshals the fields in the given protoreflect.Message. +// If the typeURL is non-empty, then a synthetic "@type" field is injected +// containing the URL as the value. +func (e encoder) marshalMessage(m pref.Message, typeURL string) error { + if !flags.ProtoLegacy && messageset.IsMessageSet(m.Descriptor()) { + return errors.New("no support for proto1 MessageSets") + } + + if marshal := wellKnownTypeMarshaler(m.Descriptor().FullName()); marshal != nil { + return marshal(e, m) + } + + e.StartObject() + defer e.EndObject() + + var fields order.FieldRanger = m + if e.opts.EmitUnpopulated { + fields = unpopulatedFieldRanger{m} + } + if typeURL != "" { + fields = typeURLFieldRanger{fields, typeURL} + } + + var err error + order.RangeFields(fields, order.IndexNameFieldOrder, func(fd pref.FieldDescriptor, v pref.Value) bool { + name := fd.JSONName() + if e.opts.UseProtoNames { + name = fd.TextName() + } + + if err = e.WriteName(name); err != nil { + return false + } + if err = e.marshalValue(v, fd); err != nil { + return false + } + return true + }) + return err +} + +// marshalValue marshals the given protoreflect.Value. +func (e encoder) marshalValue(val pref.Value, fd pref.FieldDescriptor) error { + switch { + case fd.IsList(): + return e.marshalList(val.List(), fd) + case fd.IsMap(): + return e.marshalMap(val.Map(), fd) + default: + return e.marshalSingular(val, fd) + } +} + +// marshalSingular marshals the given non-repeated field value. This includes +// all scalar types, enums, messages, and groups. +func (e encoder) marshalSingular(val pref.Value, fd pref.FieldDescriptor) error { + if !val.IsValid() { + e.WriteNull() + return nil + } + + switch kind := fd.Kind(); kind { + case pref.BoolKind: + e.WriteBool(val.Bool()) + + case pref.StringKind: + if e.WriteString(val.String()) != nil { + return errors.InvalidUTF8(string(fd.FullName())) + } + + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + e.WriteInt(val.Int()) + + case pref.Uint32Kind, pref.Fixed32Kind: + e.WriteUint(val.Uint()) + + case pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind, + pref.Sfixed64Kind, pref.Fixed64Kind: + // 64-bit integers are written out as JSON string. + e.WriteString(val.String()) + + case pref.FloatKind: + // Encoder.WriteFloat handles the special numbers NaN and infinites. + e.WriteFloat(val.Float(), 32) + + case pref.DoubleKind: + // Encoder.WriteFloat handles the special numbers NaN and infinites. + e.WriteFloat(val.Float(), 64) + + case pref.BytesKind: + e.WriteString(base64.StdEncoding.EncodeToString(val.Bytes())) + + case pref.EnumKind: + if fd.Enum().FullName() == genid.NullValue_enum_fullname { + e.WriteNull() + } else { + desc := fd.Enum().Values().ByNumber(val.Enum()) + if e.opts.UseEnumNumbers || desc == nil { + e.WriteInt(int64(val.Enum())) + } else { + e.WriteString(string(desc.Name())) + } + } + + case pref.MessageKind, pref.GroupKind: + if err := e.marshalMessage(val.Message(), ""); err != nil { + return err + } + + default: + panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind)) + } + return nil +} + +// marshalList marshals the given protoreflect.List. +func (e encoder) marshalList(list pref.List, fd pref.FieldDescriptor) error { + e.StartArray() + defer e.EndArray() + + for i := 0; i < list.Len(); i++ { + item := list.Get(i) + if err := e.marshalSingular(item, fd); err != nil { + return err + } + } + return nil +} + +// marshalMap marshals given protoreflect.Map. +func (e encoder) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) error { + e.StartObject() + defer e.EndObject() + + var err error + order.RangeEntries(mmap, order.GenericKeyOrder, func(k pref.MapKey, v pref.Value) bool { + if err = e.WriteName(k.String()); err != nil { + return false + } + if err = e.marshalSingular(v, fd.MapValue()); err != nil { + return false + } + return true + }) + return err +} diff --git a/vendor/google.golang.org/protobuf/encoding/protojson/well_known_types.go b/vendor/google.golang.org/protobuf/encoding/protojson/well_known_types.go new file mode 100644 index 000000000000..72924a9050cf --- /dev/null +++ b/vendor/google.golang.org/protobuf/encoding/protojson/well_known_types.go @@ -0,0 +1,889 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protojson + +import ( + "bytes" + "fmt" + "math" + "strconv" + "strings" + "time" + + "google.golang.org/protobuf/internal/encoding/json" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type marshalFunc func(encoder, pref.Message) error + +// wellKnownTypeMarshaler returns a marshal function if the message type +// has specialized serialization behavior. It returns nil otherwise. +func wellKnownTypeMarshaler(name pref.FullName) marshalFunc { + if name.Parent() == genid.GoogleProtobuf_package { + switch name.Name() { + case genid.Any_message_name: + return encoder.marshalAny + case genid.Timestamp_message_name: + return encoder.marshalTimestamp + case genid.Duration_message_name: + return encoder.marshalDuration + case genid.BoolValue_message_name, + genid.Int32Value_message_name, + genid.Int64Value_message_name, + genid.UInt32Value_message_name, + genid.UInt64Value_message_name, + genid.FloatValue_message_name, + genid.DoubleValue_message_name, + genid.StringValue_message_name, + genid.BytesValue_message_name: + return encoder.marshalWrapperType + case genid.Struct_message_name: + return encoder.marshalStruct + case genid.ListValue_message_name: + return encoder.marshalListValue + case genid.Value_message_name: + return encoder.marshalKnownValue + case genid.FieldMask_message_name: + return encoder.marshalFieldMask + case genid.Empty_message_name: + return encoder.marshalEmpty + } + } + return nil +} + +type unmarshalFunc func(decoder, pref.Message) error + +// wellKnownTypeUnmarshaler returns a unmarshal function if the message type +// has specialized serialization behavior. It returns nil otherwise. +func wellKnownTypeUnmarshaler(name pref.FullName) unmarshalFunc { + if name.Parent() == genid.GoogleProtobuf_package { + switch name.Name() { + case genid.Any_message_name: + return decoder.unmarshalAny + case genid.Timestamp_message_name: + return decoder.unmarshalTimestamp + case genid.Duration_message_name: + return decoder.unmarshalDuration + case genid.BoolValue_message_name, + genid.Int32Value_message_name, + genid.Int64Value_message_name, + genid.UInt32Value_message_name, + genid.UInt64Value_message_name, + genid.FloatValue_message_name, + genid.DoubleValue_message_name, + genid.StringValue_message_name, + genid.BytesValue_message_name: + return decoder.unmarshalWrapperType + case genid.Struct_message_name: + return decoder.unmarshalStruct + case genid.ListValue_message_name: + return decoder.unmarshalListValue + case genid.Value_message_name: + return decoder.unmarshalKnownValue + case genid.FieldMask_message_name: + return decoder.unmarshalFieldMask + case genid.Empty_message_name: + return decoder.unmarshalEmpty + } + } + return nil +} + +// The JSON representation of an Any message uses the regular representation of +// the deserialized, embedded message, with an additional field `@type` which +// contains the type URL. If the embedded message type is well-known and has a +// custom JSON representation, that representation will be embedded adding a +// field `value` which holds the custom JSON in addition to the `@type` field. + +func (e encoder) marshalAny(m pref.Message) error { + fds := m.Descriptor().Fields() + fdType := fds.ByNumber(genid.Any_TypeUrl_field_number) + fdValue := fds.ByNumber(genid.Any_Value_field_number) + + if !m.Has(fdType) { + if !m.Has(fdValue) { + // If message is empty, marshal out empty JSON object. + e.StartObject() + e.EndObject() + return nil + } else { + // Return error if type_url field is not set, but value is set. + return errors.New("%s: %v is not set", genid.Any_message_fullname, genid.Any_TypeUrl_field_name) + } + } + + typeVal := m.Get(fdType) + valueVal := m.Get(fdValue) + + // Resolve the type in order to unmarshal value field. + typeURL := typeVal.String() + emt, err := e.opts.Resolver.FindMessageByURL(typeURL) + if err != nil { + return errors.New("%s: unable to resolve %q: %v", genid.Any_message_fullname, typeURL, err) + } + + em := emt.New() + err = proto.UnmarshalOptions{ + AllowPartial: true, // never check required fields inside an Any + Resolver: e.opts.Resolver, + }.Unmarshal(valueVal.Bytes(), em.Interface()) + if err != nil { + return errors.New("%s: unable to unmarshal %q: %v", genid.Any_message_fullname, typeURL, err) + } + + // If type of value has custom JSON encoding, marshal out a field "value" + // with corresponding custom JSON encoding of the embedded message as a + // field. + if marshal := wellKnownTypeMarshaler(emt.Descriptor().FullName()); marshal != nil { + e.StartObject() + defer e.EndObject() + + // Marshal out @type field. + e.WriteName("@type") + if err := e.WriteString(typeURL); err != nil { + return err + } + + e.WriteName("value") + return marshal(e, em) + } + + // Else, marshal out the embedded message's fields in this Any object. + if err := e.marshalMessage(em, typeURL); err != nil { + return err + } + + return nil +} + +func (d decoder) unmarshalAny(m pref.Message) error { + // Peek to check for json.ObjectOpen to avoid advancing a read. + start, err := d.Peek() + if err != nil { + return err + } + if start.Kind() != json.ObjectOpen { + return d.unexpectedTokenError(start) + } + + // Use another decoder to parse the unread bytes for @type field. This + // avoids advancing a read from current decoder because the current JSON + // object may contain the fields of the embedded type. + dec := decoder{d.Clone(), UnmarshalOptions{}} + tok, err := findTypeURL(dec) + switch err { + case errEmptyObject: + // An empty JSON object translates to an empty Any message. + d.Read() // Read json.ObjectOpen. + d.Read() // Read json.ObjectClose. + return nil + + case errMissingType: + if d.opts.DiscardUnknown { + // Treat all fields as unknowns, similar to an empty object. + return d.skipJSONValue() + } + // Use start.Pos() for line position. + return d.newError(start.Pos(), err.Error()) + + default: + if err != nil { + return err + } + } + + typeURL := tok.ParsedString() + emt, err := d.opts.Resolver.FindMessageByURL(typeURL) + if err != nil { + return d.newError(tok.Pos(), "unable to resolve %v: %q", tok.RawString(), err) + } + + // Create new message for the embedded message type and unmarshal into it. + em := emt.New() + if unmarshal := wellKnownTypeUnmarshaler(emt.Descriptor().FullName()); unmarshal != nil { + // If embedded message is a custom type, + // unmarshal the JSON "value" field into it. + if err := d.unmarshalAnyValue(unmarshal, em); err != nil { + return err + } + } else { + // Else unmarshal the current JSON object into it. + if err := d.unmarshalMessage(em, true); err != nil { + return err + } + } + // Serialize the embedded message and assign the resulting bytes to the + // proto value field. + b, err := proto.MarshalOptions{ + AllowPartial: true, // No need to check required fields inside an Any. + Deterministic: true, + }.Marshal(em.Interface()) + if err != nil { + return d.newError(start.Pos(), "error in marshaling Any.value field: %v", err) + } + + fds := m.Descriptor().Fields() + fdType := fds.ByNumber(genid.Any_TypeUrl_field_number) + fdValue := fds.ByNumber(genid.Any_Value_field_number) + + m.Set(fdType, pref.ValueOfString(typeURL)) + m.Set(fdValue, pref.ValueOfBytes(b)) + return nil +} + +var errEmptyObject = fmt.Errorf(`empty object`) +var errMissingType = fmt.Errorf(`missing "@type" field`) + +// findTypeURL returns the token for the "@type" field value from the given +// JSON bytes. It is expected that the given bytes start with json.ObjectOpen. +// It returns errEmptyObject if the JSON object is empty or errMissingType if +// @type field does not exist. It returns other error if the @type field is not +// valid or other decoding issues. +func findTypeURL(d decoder) (json.Token, error) { + var typeURL string + var typeTok json.Token + numFields := 0 + // Skip start object. + d.Read() + +Loop: + for { + tok, err := d.Read() + if err != nil { + return json.Token{}, err + } + + switch tok.Kind() { + case json.ObjectClose: + if typeURL == "" { + // Did not find @type field. + if numFields > 0 { + return json.Token{}, errMissingType + } + return json.Token{}, errEmptyObject + } + break Loop + + case json.Name: + numFields++ + if tok.Name() != "@type" { + // Skip value. + if err := d.skipJSONValue(); err != nil { + return json.Token{}, err + } + continue + } + + // Return error if this was previously set already. + if typeURL != "" { + return json.Token{}, d.newError(tok.Pos(), `duplicate "@type" field`) + } + // Read field value. + tok, err := d.Read() + if err != nil { + return json.Token{}, err + } + if tok.Kind() != json.String { + return json.Token{}, d.newError(tok.Pos(), `@type field value is not a string: %v`, tok.RawString()) + } + typeURL = tok.ParsedString() + if typeURL == "" { + return json.Token{}, d.newError(tok.Pos(), `@type field contains empty value`) + } + typeTok = tok + } + } + + return typeTok, nil +} + +// skipJSONValue parses a JSON value (null, boolean, string, number, object and +// array) in order to advance the read to the next JSON value. It relies on +// the decoder returning an error if the types are not in valid sequence. +func (d decoder) skipJSONValue() error { + tok, err := d.Read() + if err != nil { + return err + } + // Only need to continue reading for objects and arrays. + switch tok.Kind() { + case json.ObjectOpen: + for { + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case json.ObjectClose: + return nil + case json.Name: + // Skip object field value. + if err := d.skipJSONValue(); err != nil { + return err + } + } + } + + case json.ArrayOpen: + for { + tok, err := d.Peek() + if err != nil { + return err + } + switch tok.Kind() { + case json.ArrayClose: + d.Read() + return nil + default: + // Skip array item. + if err := d.skipJSONValue(); err != nil { + return err + } + } + } + } + return nil +} + +// unmarshalAnyValue unmarshals the given custom-type message from the JSON +// object's "value" field. +func (d decoder) unmarshalAnyValue(unmarshal unmarshalFunc, m pref.Message) error { + // Skip ObjectOpen, and start reading the fields. + d.Read() + + var found bool // Used for detecting duplicate "value". + for { + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case json.ObjectClose: + if !found { + return d.newError(tok.Pos(), `missing "value" field`) + } + return nil + + case json.Name: + switch tok.Name() { + case "@type": + // Skip the value as this was previously parsed already. + d.Read() + + case "value": + if found { + return d.newError(tok.Pos(), `duplicate "value" field`) + } + // Unmarshal the field value into the given message. + if err := unmarshal(d, m); err != nil { + return err + } + found = true + + default: + if d.opts.DiscardUnknown { + if err := d.skipJSONValue(); err != nil { + return err + } + continue + } + return d.newError(tok.Pos(), "unknown field %v", tok.RawString()) + } + } + } +} + +// Wrapper types are encoded as JSON primitives like string, number or boolean. + +func (e encoder) marshalWrapperType(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.WrapperValue_Value_field_number) + val := m.Get(fd) + return e.marshalSingular(val, fd) +} + +func (d decoder) unmarshalWrapperType(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.WrapperValue_Value_field_number) + val, err := d.unmarshalScalar(fd) + if err != nil { + return err + } + m.Set(fd, val) + return nil +} + +// The JSON representation for Empty is an empty JSON object. + +func (e encoder) marshalEmpty(pref.Message) error { + e.StartObject() + e.EndObject() + return nil +} + +func (d decoder) unmarshalEmpty(pref.Message) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.ObjectOpen { + return d.unexpectedTokenError(tok) + } + + for { + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case json.ObjectClose: + return nil + + case json.Name: + if d.opts.DiscardUnknown { + if err := d.skipJSONValue(); err != nil { + return err + } + continue + } + return d.newError(tok.Pos(), "unknown field %v", tok.RawString()) + + default: + return d.unexpectedTokenError(tok) + } + } +} + +// The JSON representation for Struct is a JSON object that contains the encoded +// Struct.fields map and follows the serialization rules for a map. + +func (e encoder) marshalStruct(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.Struct_Fields_field_number) + return e.marshalMap(m.Get(fd).Map(), fd) +} + +func (d decoder) unmarshalStruct(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.Struct_Fields_field_number) + return d.unmarshalMap(m.Mutable(fd).Map(), fd) +} + +// The JSON representation for ListValue is JSON array that contains the encoded +// ListValue.values repeated field and follows the serialization rules for a +// repeated field. + +func (e encoder) marshalListValue(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.ListValue_Values_field_number) + return e.marshalList(m.Get(fd).List(), fd) +} + +func (d decoder) unmarshalListValue(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.ListValue_Values_field_number) + return d.unmarshalList(m.Mutable(fd).List(), fd) +} + +// The JSON representation for a Value is dependent on the oneof field that is +// set. Each of the field in the oneof has its own custom serialization rule. A +// Value message needs to be a oneof field set, else it is an error. + +func (e encoder) marshalKnownValue(m pref.Message) error { + od := m.Descriptor().Oneofs().ByName(genid.Value_Kind_oneof_name) + fd := m.WhichOneof(od) + if fd == nil { + return errors.New("%s: none of the oneof fields is set", genid.Value_message_fullname) + } + if fd.Number() == genid.Value_NumberValue_field_number { + if v := m.Get(fd).Float(); math.IsNaN(v) || math.IsInf(v, 0) { + return errors.New("%s: invalid %v value", genid.Value_NumberValue_field_fullname, v) + } + } + return e.marshalSingular(m.Get(fd), fd) +} + +func (d decoder) unmarshalKnownValue(m pref.Message) error { + tok, err := d.Peek() + if err != nil { + return err + } + + var fd pref.FieldDescriptor + var val pref.Value + switch tok.Kind() { + case json.Null: + d.Read() + fd = m.Descriptor().Fields().ByNumber(genid.Value_NullValue_field_number) + val = pref.ValueOfEnum(0) + + case json.Bool: + tok, err := d.Read() + if err != nil { + return err + } + fd = m.Descriptor().Fields().ByNumber(genid.Value_BoolValue_field_number) + val = pref.ValueOfBool(tok.Bool()) + + case json.Number: + tok, err := d.Read() + if err != nil { + return err + } + fd = m.Descriptor().Fields().ByNumber(genid.Value_NumberValue_field_number) + var ok bool + val, ok = unmarshalFloat(tok, 64) + if !ok { + return d.newError(tok.Pos(), "invalid %v: %v", genid.Value_message_fullname, tok.RawString()) + } + + case json.String: + // A JSON string may have been encoded from the number_value field, + // e.g. "NaN", "Infinity", etc. Parsing a proto double type also allows + // for it to be in JSON string form. Given this custom encoding spec, + // however, there is no way to identify that and hence a JSON string is + // always assigned to the string_value field, which means that certain + // encoding cannot be parsed back to the same field. + tok, err := d.Read() + if err != nil { + return err + } + fd = m.Descriptor().Fields().ByNumber(genid.Value_StringValue_field_number) + val = pref.ValueOfString(tok.ParsedString()) + + case json.ObjectOpen: + fd = m.Descriptor().Fields().ByNumber(genid.Value_StructValue_field_number) + val = m.NewField(fd) + if err := d.unmarshalStruct(val.Message()); err != nil { + return err + } + + case json.ArrayOpen: + fd = m.Descriptor().Fields().ByNumber(genid.Value_ListValue_field_number) + val = m.NewField(fd) + if err := d.unmarshalListValue(val.Message()); err != nil { + return err + } + + default: + return d.newError(tok.Pos(), "invalid %v: %v", genid.Value_message_fullname, tok.RawString()) + } + + m.Set(fd, val) + return nil +} + +// The JSON representation for a Duration is a JSON string that ends in the +// suffix "s" (indicating seconds) and is preceded by the number of seconds, +// with nanoseconds expressed as fractional seconds. +// +// Durations less than one second are represented with a 0 seconds field and a +// positive or negative nanos field. For durations of one second or more, a +// non-zero value for the nanos field must be of the same sign as the seconds +// field. +// +// Duration.seconds must be from -315,576,000,000 to +315,576,000,000 inclusive. +// Duration.nanos must be from -999,999,999 to +999,999,999 inclusive. + +const ( + secondsInNanos = 999999999 + maxSecondsInDuration = 315576000000 +) + +func (e encoder) marshalDuration(m pref.Message) error { + fds := m.Descriptor().Fields() + fdSeconds := fds.ByNumber(genid.Duration_Seconds_field_number) + fdNanos := fds.ByNumber(genid.Duration_Nanos_field_number) + + secsVal := m.Get(fdSeconds) + nanosVal := m.Get(fdNanos) + secs := secsVal.Int() + nanos := nanosVal.Int() + if secs < -maxSecondsInDuration || secs > maxSecondsInDuration { + return errors.New("%s: seconds out of range %v", genid.Duration_message_fullname, secs) + } + if nanos < -secondsInNanos || nanos > secondsInNanos { + return errors.New("%s: nanos out of range %v", genid.Duration_message_fullname, nanos) + } + if (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0) { + return errors.New("%s: signs of seconds and nanos do not match", genid.Duration_message_fullname) + } + // Generated output always contains 0, 3, 6, or 9 fractional digits, + // depending on required precision, followed by the suffix "s". + var sign string + if secs < 0 || nanos < 0 { + sign, secs, nanos = "-", -1*secs, -1*nanos + } + x := fmt.Sprintf("%s%d.%09d", sign, secs, nanos) + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + e.WriteString(x + "s") + return nil +} + +func (d decoder) unmarshalDuration(m pref.Message) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.String { + return d.unexpectedTokenError(tok) + } + + secs, nanos, ok := parseDuration(tok.ParsedString()) + if !ok { + return d.newError(tok.Pos(), "invalid %v value %v", genid.Duration_message_fullname, tok.RawString()) + } + // Validate seconds. No need to validate nanos because parseDuration would + // have covered that already. + if secs < -maxSecondsInDuration || secs > maxSecondsInDuration { + return d.newError(tok.Pos(), "%v value out of range: %v", genid.Duration_message_fullname, tok.RawString()) + } + + fds := m.Descriptor().Fields() + fdSeconds := fds.ByNumber(genid.Duration_Seconds_field_number) + fdNanos := fds.ByNumber(genid.Duration_Nanos_field_number) + + m.Set(fdSeconds, pref.ValueOfInt64(secs)) + m.Set(fdNanos, pref.ValueOfInt32(nanos)) + return nil +} + +// parseDuration parses the given input string for seconds and nanoseconds value +// for the Duration JSON format. The format is a decimal number with a suffix +// 's'. It can have optional plus/minus sign. There needs to be at least an +// integer or fractional part. Fractional part is limited to 9 digits only for +// nanoseconds precision, regardless of whether there are trailing zero digits. +// Example values are 1s, 0.1s, 1.s, .1s, +1s, -1s, -.1s. +func parseDuration(input string) (int64, int32, bool) { + b := []byte(input) + size := len(b) + if size < 2 { + return 0, 0, false + } + if b[size-1] != 's' { + return 0, 0, false + } + b = b[:size-1] + + // Read optional plus/minus symbol. + var neg bool + switch b[0] { + case '-': + neg = true + b = b[1:] + case '+': + b = b[1:] + } + if len(b) == 0 { + return 0, 0, false + } + + // Read the integer part. + var intp []byte + switch { + case b[0] == '0': + b = b[1:] + + case '1' <= b[0] && b[0] <= '9': + intp = b[0:] + b = b[1:] + n := 1 + for len(b) > 0 && '0' <= b[0] && b[0] <= '9' { + n++ + b = b[1:] + } + intp = intp[:n] + + case b[0] == '.': + // Continue below. + + default: + return 0, 0, false + } + + hasFrac := false + var frac [9]byte + if len(b) > 0 { + if b[0] != '.' { + return 0, 0, false + } + // Read the fractional part. + b = b[1:] + n := 0 + for len(b) > 0 && n < 9 && '0' <= b[0] && b[0] <= '9' { + frac[n] = b[0] + n++ + b = b[1:] + } + // It is not valid if there are more bytes left. + if len(b) > 0 { + return 0, 0, false + } + // Pad fractional part with 0s. + for i := n; i < 9; i++ { + frac[i] = '0' + } + hasFrac = true + } + + var secs int64 + if len(intp) > 0 { + var err error + secs, err = strconv.ParseInt(string(intp), 10, 64) + if err != nil { + return 0, 0, false + } + } + + var nanos int64 + if hasFrac { + nanob := bytes.TrimLeft(frac[:], "0") + if len(nanob) > 0 { + var err error + nanos, err = strconv.ParseInt(string(nanob), 10, 32) + if err != nil { + return 0, 0, false + } + } + } + + if neg { + if secs > 0 { + secs = -secs + } + if nanos > 0 { + nanos = -nanos + } + } + return secs, int32(nanos), true +} + +// The JSON representation for a Timestamp is a JSON string in the RFC 3339 +// format, i.e. "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" where +// {year} is always expressed using four digits while {month}, {day}, {hour}, +// {min}, and {sec} are zero-padded to two digits each. The fractional seconds, +// which can go up to 9 digits, up to 1 nanosecond resolution, is optional. The +// "Z" suffix indicates the timezone ("UTC"); the timezone is required. Encoding +// should always use UTC (as indicated by "Z") and a decoder should be able to +// accept both UTC and other timezones (as indicated by an offset). +// +// Timestamp.seconds must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z +// inclusive. +// Timestamp.nanos must be from 0 to 999,999,999 inclusive. + +const ( + maxTimestampSeconds = 253402300799 + minTimestampSeconds = -62135596800 +) + +func (e encoder) marshalTimestamp(m pref.Message) error { + fds := m.Descriptor().Fields() + fdSeconds := fds.ByNumber(genid.Timestamp_Seconds_field_number) + fdNanos := fds.ByNumber(genid.Timestamp_Nanos_field_number) + + secsVal := m.Get(fdSeconds) + nanosVal := m.Get(fdNanos) + secs := secsVal.Int() + nanos := nanosVal.Int() + if secs < minTimestampSeconds || secs > maxTimestampSeconds { + return errors.New("%s: seconds out of range %v", genid.Timestamp_message_fullname, secs) + } + if nanos < 0 || nanos > secondsInNanos { + return errors.New("%s: nanos out of range %v", genid.Timestamp_message_fullname, nanos) + } + // Uses RFC 3339, where generated output will be Z-normalized and uses 0, 3, + // 6 or 9 fractional digits. + t := time.Unix(secs, nanos).UTC() + x := t.Format("2006-01-02T15:04:05.000000000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, "000") + x = strings.TrimSuffix(x, ".000") + e.WriteString(x + "Z") + return nil +} + +func (d decoder) unmarshalTimestamp(m pref.Message) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.String { + return d.unexpectedTokenError(tok) + } + + t, err := time.Parse(time.RFC3339Nano, tok.ParsedString()) + if err != nil { + return d.newError(tok.Pos(), "invalid %v value %v", genid.Timestamp_message_fullname, tok.RawString()) + } + // Validate seconds. No need to validate nanos because time.Parse would have + // covered that already. + secs := t.Unix() + if secs < minTimestampSeconds || secs > maxTimestampSeconds { + return d.newError(tok.Pos(), "%v value out of range: %v", genid.Timestamp_message_fullname, tok.RawString()) + } + + fds := m.Descriptor().Fields() + fdSeconds := fds.ByNumber(genid.Timestamp_Seconds_field_number) + fdNanos := fds.ByNumber(genid.Timestamp_Nanos_field_number) + + m.Set(fdSeconds, pref.ValueOfInt64(secs)) + m.Set(fdNanos, pref.ValueOfInt32(int32(t.Nanosecond()))) + return nil +} + +// The JSON representation for a FieldMask is a JSON string where paths are +// separated by a comma. Fields name in each path are converted to/from +// lower-camel naming conventions. Encoding should fail if the path name would +// end up differently after a round-trip. + +func (e encoder) marshalFieldMask(m pref.Message) error { + fd := m.Descriptor().Fields().ByNumber(genid.FieldMask_Paths_field_number) + list := m.Get(fd).List() + paths := make([]string, 0, list.Len()) + + for i := 0; i < list.Len(); i++ { + s := list.Get(i).String() + if !pref.FullName(s).IsValid() { + return errors.New("%s contains invalid path: %q", genid.FieldMask_Paths_field_fullname, s) + } + // Return error if conversion to camelCase is not reversible. + cc := strs.JSONCamelCase(s) + if s != strs.JSONSnakeCase(cc) { + return errors.New("%s contains irreversible value %q", genid.FieldMask_Paths_field_fullname, s) + } + paths = append(paths, cc) + } + + e.WriteString(strings.Join(paths, ",")) + return nil +} + +func (d decoder) unmarshalFieldMask(m pref.Message) error { + tok, err := d.Read() + if err != nil { + return err + } + if tok.Kind() != json.String { + return d.unexpectedTokenError(tok) + } + str := strings.TrimSpace(tok.ParsedString()) + if str == "" { + return nil + } + paths := strings.Split(str, ",") + + fd := m.Descriptor().Fields().ByNumber(genid.FieldMask_Paths_field_number) + list := m.Mutable(fd).List() + + for _, s0 := range paths { + s := strs.JSONSnakeCase(s0) + if strings.Contains(s0, "_") || !pref.FullName(s).IsValid() { + return d.newError(tok.Pos(), "%v contains invalid path: %q", genid.FieldMask_Paths_field_fullname, s0) + } + list.Append(pref.ValueOfString(s)) + } + return nil +} diff --git a/vendor/google.golang.org/protobuf/encoding/protowire/wire.go b/vendor/google.golang.org/protobuf/encoding/protowire/wire.go index a427f8b7043b..9c61112f58d1 100644 --- a/vendor/google.golang.org/protobuf/encoding/protowire/wire.go +++ b/vendor/google.golang.org/protobuf/encoding/protowire/wire.go @@ -21,10 +21,11 @@ import ( type Number int32 const ( - MinValidNumber Number = 1 - FirstReservedNumber Number = 19000 - LastReservedNumber Number = 19999 - MaxValidNumber Number = 1<<29 - 1 + MinValidNumber Number = 1 + FirstReservedNumber Number = 19000 + LastReservedNumber Number = 19999 + MaxValidNumber Number = 1<<29 - 1 + DefaultRecursionLimit = 10000 ) // IsValid reports whether the field number is semantically valid. @@ -55,6 +56,7 @@ const ( errCodeOverflow errCodeReserved errCodeEndGroup + errCodeRecursionDepth ) var ( @@ -112,6 +114,10 @@ func ConsumeField(b []byte) (Number, Type, int) { // When parsing a group, the length includes the end group marker and // the end group is verified to match the starting field number. func ConsumeFieldValue(num Number, typ Type, b []byte) (n int) { + return consumeFieldValueD(num, typ, b, DefaultRecursionLimit) +} + +func consumeFieldValueD(num Number, typ Type, b []byte, depth int) (n int) { switch typ { case VarintType: _, n = ConsumeVarint(b) @@ -126,6 +132,9 @@ func ConsumeFieldValue(num Number, typ Type, b []byte) (n int) { _, n = ConsumeBytes(b) return n case StartGroupType: + if depth < 0 { + return errCodeRecursionDepth + } n0 := len(b) for { num2, typ2, n := ConsumeTag(b) @@ -140,7 +149,7 @@ func ConsumeFieldValue(num Number, typ Type, b []byte) (n int) { return n0 - len(b) } - n = ConsumeFieldValue(num2, typ2, b) + n = consumeFieldValueD(num2, typ2, b, depth-1) if n < 0 { return n // forward error code } diff --git a/vendor/google.golang.org/protobuf/internal/encoding/json/decode.go b/vendor/google.golang.org/protobuf/internal/encoding/json/decode.go new file mode 100644 index 000000000000..b13fd29e81e6 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/json/decode.go @@ -0,0 +1,340 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "bytes" + "fmt" + "io" + "regexp" + "unicode/utf8" + + "google.golang.org/protobuf/internal/errors" +) + +// call specifies which Decoder method was invoked. +type call uint8 + +const ( + readCall call = iota + peekCall +) + +const unexpectedFmt = "unexpected token %s" + +// ErrUnexpectedEOF means that EOF was encountered in the middle of the input. +var ErrUnexpectedEOF = errors.New("%v", io.ErrUnexpectedEOF) + +// Decoder is a token-based JSON decoder. +type Decoder struct { + // lastCall is last method called, either readCall or peekCall. + // Initial value is readCall. + lastCall call + + // lastToken contains the last read token. + lastToken Token + + // lastErr contains the last read error. + lastErr error + + // openStack is a stack containing ObjectOpen and ArrayOpen values. The + // top of stack represents the object or the array the current value is + // directly located in. + openStack []Kind + + // orig is used in reporting line and column. + orig []byte + // in contains the unconsumed input. + in []byte +} + +// NewDecoder returns a Decoder to read the given []byte. +func NewDecoder(b []byte) *Decoder { + return &Decoder{orig: b, in: b} +} + +// Peek looks ahead and returns the next token kind without advancing a read. +func (d *Decoder) Peek() (Token, error) { + defer func() { d.lastCall = peekCall }() + if d.lastCall == readCall { + d.lastToken, d.lastErr = d.Read() + } + return d.lastToken, d.lastErr +} + +// Read returns the next JSON token. +// It will return an error if there is no valid token. +func (d *Decoder) Read() (Token, error) { + const scalar = Null | Bool | Number | String + + defer func() { d.lastCall = readCall }() + if d.lastCall == peekCall { + return d.lastToken, d.lastErr + } + + tok, err := d.parseNext() + if err != nil { + return Token{}, err + } + + switch tok.kind { + case EOF: + if len(d.openStack) != 0 || + d.lastToken.kind&scalar|ObjectClose|ArrayClose == 0 { + return Token{}, ErrUnexpectedEOF + } + + case Null: + if !d.isValueNext() { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + + case Bool, Number: + if !d.isValueNext() { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + + case String: + if d.isValueNext() { + break + } + // This string token should only be for a field name. + if d.lastToken.kind&(ObjectOpen|comma) == 0 { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + if len(d.in) == 0 { + return Token{}, ErrUnexpectedEOF + } + if c := d.in[0]; c != ':' { + return Token{}, d.newSyntaxError(d.currPos(), `unexpected character %s, missing ":" after field name`, string(c)) + } + tok.kind = Name + d.consume(1) + + case ObjectOpen, ArrayOpen: + if !d.isValueNext() { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + d.openStack = append(d.openStack, tok.kind) + + case ObjectClose: + if len(d.openStack) == 0 || + d.lastToken.kind == comma || + d.openStack[len(d.openStack)-1] != ObjectOpen { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + d.openStack = d.openStack[:len(d.openStack)-1] + + case ArrayClose: + if len(d.openStack) == 0 || + d.lastToken.kind == comma || + d.openStack[len(d.openStack)-1] != ArrayOpen { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + d.openStack = d.openStack[:len(d.openStack)-1] + + case comma: + if len(d.openStack) == 0 || + d.lastToken.kind&(scalar|ObjectClose|ArrayClose) == 0 { + return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) + } + } + + // Update d.lastToken only after validating token to be in the right sequence. + d.lastToken = tok + + if d.lastToken.kind == comma { + return d.Read() + } + return tok, nil +} + +// Any sequence that looks like a non-delimiter (for error reporting). +var errRegexp = regexp.MustCompile(`^([-+._a-zA-Z0-9]{1,32}|.)`) + +// parseNext parses for the next JSON token. It returns a Token object for +// different types, except for Name. It does not handle whether the next token +// is in a valid sequence or not. +func (d *Decoder) parseNext() (Token, error) { + // Trim leading spaces. + d.consume(0) + + in := d.in + if len(in) == 0 { + return d.consumeToken(EOF, 0), nil + } + + switch in[0] { + case 'n': + if n := matchWithDelim("null", in); n != 0 { + return d.consumeToken(Null, n), nil + } + + case 't': + if n := matchWithDelim("true", in); n != 0 { + return d.consumeBoolToken(true, n), nil + } + + case 'f': + if n := matchWithDelim("false", in); n != 0 { + return d.consumeBoolToken(false, n), nil + } + + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + if n, ok := parseNumber(in); ok { + return d.consumeToken(Number, n), nil + } + + case '"': + s, n, err := d.parseString(in) + if err != nil { + return Token{}, err + } + return d.consumeStringToken(s, n), nil + + case '{': + return d.consumeToken(ObjectOpen, 1), nil + + case '}': + return d.consumeToken(ObjectClose, 1), nil + + case '[': + return d.consumeToken(ArrayOpen, 1), nil + + case ']': + return d.consumeToken(ArrayClose, 1), nil + + case ',': + return d.consumeToken(comma, 1), nil + } + return Token{}, d.newSyntaxError(d.currPos(), "invalid value %s", errRegexp.Find(in)) +} + +// newSyntaxError returns an error with line and column information useful for +// syntax errors. +func (d *Decoder) newSyntaxError(pos int, f string, x ...interface{}) error { + e := errors.New(f, x...) + line, column := d.Position(pos) + return errors.New("syntax error (line %d:%d): %v", line, column, e) +} + +// Position returns line and column number of given index of the original input. +// It will panic if index is out of range. +func (d *Decoder) Position(idx int) (line int, column int) { + b := d.orig[:idx] + line = bytes.Count(b, []byte("\n")) + 1 + if i := bytes.LastIndexByte(b, '\n'); i >= 0 { + b = b[i+1:] + } + column = utf8.RuneCount(b) + 1 // ignore multi-rune characters + return line, column +} + +// currPos returns the current index position of d.in from d.orig. +func (d *Decoder) currPos() int { + return len(d.orig) - len(d.in) +} + +// matchWithDelim matches s with the input b and verifies that the match +// terminates with a delimiter of some form (e.g., r"[^-+_.a-zA-Z0-9]"). +// As a special case, EOF is considered a delimiter. It returns the length of s +// if there is a match, else 0. +func matchWithDelim(s string, b []byte) int { + if !bytes.HasPrefix(b, []byte(s)) { + return 0 + } + + n := len(s) + if n < len(b) && isNotDelim(b[n]) { + return 0 + } + return n +} + +// isNotDelim returns true if given byte is a not delimiter character. +func isNotDelim(c byte) bool { + return (c == '-' || c == '+' || c == '.' || c == '_' || + ('a' <= c && c <= 'z') || + ('A' <= c && c <= 'Z') || + ('0' <= c && c <= '9')) +} + +// consume consumes n bytes of input and any subsequent whitespace. +func (d *Decoder) consume(n int) { + d.in = d.in[n:] + for len(d.in) > 0 { + switch d.in[0] { + case ' ', '\n', '\r', '\t': + d.in = d.in[1:] + default: + return + } + } +} + +// isValueNext returns true if next type should be a JSON value: Null, +// Number, String or Bool. +func (d *Decoder) isValueNext() bool { + if len(d.openStack) == 0 { + return d.lastToken.kind == 0 + } + + start := d.openStack[len(d.openStack)-1] + switch start { + case ObjectOpen: + return d.lastToken.kind&Name != 0 + case ArrayOpen: + return d.lastToken.kind&(ArrayOpen|comma) != 0 + } + panic(fmt.Sprintf( + "unreachable logic in Decoder.isValueNext, lastToken.kind: %v, openStack: %v", + d.lastToken.kind, start)) +} + +// consumeToken constructs a Token for given Kind with raw value derived from +// current d.in and given size, and consumes the given size-lenght of it. +func (d *Decoder) consumeToken(kind Kind, size int) Token { + tok := Token{ + kind: kind, + raw: d.in[:size], + pos: len(d.orig) - len(d.in), + } + d.consume(size) + return tok +} + +// consumeBoolToken constructs a Token for a Bool kind with raw value derived from +// current d.in and given size. +func (d *Decoder) consumeBoolToken(b bool, size int) Token { + tok := Token{ + kind: Bool, + raw: d.in[:size], + pos: len(d.orig) - len(d.in), + boo: b, + } + d.consume(size) + return tok +} + +// consumeStringToken constructs a Token for a String kind with raw value derived +// from current d.in and given size. +func (d *Decoder) consumeStringToken(s string, size int) Token { + tok := Token{ + kind: String, + raw: d.in[:size], + pos: len(d.orig) - len(d.in), + str: s, + } + d.consume(size) + return tok +} + +// Clone returns a copy of the Decoder for use in reading ahead the next JSON +// object, array or other values without affecting current Decoder. +func (d *Decoder) Clone() *Decoder { + ret := *d + ret.openStack = append([]Kind(nil), ret.openStack...) + return &ret +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/json/decode_number.go b/vendor/google.golang.org/protobuf/internal/encoding/json/decode_number.go new file mode 100644 index 000000000000..2999d7133202 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/json/decode_number.go @@ -0,0 +1,254 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "bytes" + "strconv" +) + +// parseNumber reads the given []byte for a valid JSON number. If it is valid, +// it returns the number of bytes. Parsing logic follows the definition in +// https://tools.ietf.org/html/rfc7159#section-6, and is based off +// encoding/json.isValidNumber function. +func parseNumber(input []byte) (int, bool) { + var n int + + s := input + if len(s) == 0 { + return 0, false + } + + // Optional - + if s[0] == '-' { + s = s[1:] + n++ + if len(s) == 0 { + return 0, false + } + } + + // Digits + switch { + case s[0] == '0': + s = s[1:] + n++ + + case '1' <= s[0] && s[0] <= '9': + s = s[1:] + n++ + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + + default: + return 0, false + } + + // . followed by 1 or more digits. + if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { + s = s[2:] + n += 2 + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + } + + // e or E followed by an optional - or + and + // 1 or more digits. + if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { + s = s[1:] + n++ + if s[0] == '+' || s[0] == '-' { + s = s[1:] + n++ + if len(s) == 0 { + return 0, false + } + } + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + } + + // Check that next byte is a delimiter or it is at the end. + if n < len(input) && isNotDelim(input[n]) { + return 0, false + } + + return n, true +} + +// numberParts is the result of parsing out a valid JSON number. It contains +// the parts of a number. The parts are used for integer conversion. +type numberParts struct { + neg bool + intp []byte + frac []byte + exp []byte +} + +// parseNumber constructs numberParts from given []byte. The logic here is +// similar to consumeNumber above with the difference of having to construct +// numberParts. The slice fields in numberParts are subslices of the input. +func parseNumberParts(input []byte) (numberParts, bool) { + var neg bool + var intp []byte + var frac []byte + var exp []byte + + s := input + if len(s) == 0 { + return numberParts{}, false + } + + // Optional - + if s[0] == '-' { + neg = true + s = s[1:] + if len(s) == 0 { + return numberParts{}, false + } + } + + // Digits + switch { + case s[0] == '0': + // Skip first 0 and no need to store. + s = s[1:] + + case '1' <= s[0] && s[0] <= '9': + intp = s + n := 1 + s = s[1:] + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + intp = intp[:n] + + default: + return numberParts{}, false + } + + // . followed by 1 or more digits. + if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { + frac = s[1:] + n := 1 + s = s[2:] + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + frac = frac[:n] + } + + // e or E followed by an optional - or + and + // 1 or more digits. + if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { + s = s[1:] + exp = s + n := 0 + if s[0] == '+' || s[0] == '-' { + s = s[1:] + n++ + if len(s) == 0 { + return numberParts{}, false + } + } + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + exp = exp[:n] + } + + return numberParts{ + neg: neg, + intp: intp, + frac: bytes.TrimRight(frac, "0"), // Remove unnecessary 0s to the right. + exp: exp, + }, true +} + +// normalizeToIntString returns an integer string in normal form without the +// E-notation for given numberParts. It will return false if it is not an +// integer or if the exponent exceeds than max/min int value. +func normalizeToIntString(n numberParts) (string, bool) { + intpSize := len(n.intp) + fracSize := len(n.frac) + + if intpSize == 0 && fracSize == 0 { + return "0", true + } + + var exp int + if len(n.exp) > 0 { + i, err := strconv.ParseInt(string(n.exp), 10, 32) + if err != nil { + return "", false + } + exp = int(i) + } + + var num []byte + if exp >= 0 { + // For positive E, shift fraction digits into integer part and also pad + // with zeroes as needed. + + // If there are more digits in fraction than the E value, then the + // number is not an integer. + if fracSize > exp { + return "", false + } + + // Make sure resulting digits are within max value limit to avoid + // unnecessarily constructing a large byte slice that may simply fail + // later on. + const maxDigits = 20 // Max uint64 value has 20 decimal digits. + if intpSize+exp > maxDigits { + return "", false + } + + // Set cap to make a copy of integer part when appended. + num = n.intp[:len(n.intp):len(n.intp)] + num = append(num, n.frac...) + for i := 0; i < exp-fracSize; i++ { + num = append(num, '0') + } + } else { + // For negative E, shift digits in integer part out. + + // If there are fractions, then the number is not an integer. + if fracSize > 0 { + return "", false + } + + // index is where the decimal point will be after adjusting for negative + // exponent. + index := intpSize + exp + if index < 0 { + return "", false + } + + num = n.intp + // If any of the digits being shifted to the right of the decimal point + // is non-zero, then the number is not an integer. + for i := index; i < intpSize; i++ { + if num[i] != '0' { + return "", false + } + } + num = num[:index] + } + + if n.neg { + return "-" + string(num), true + } + return string(num), true +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/json/decode_string.go b/vendor/google.golang.org/protobuf/internal/encoding/json/decode_string.go new file mode 100644 index 000000000000..f7fea7d8dd4b --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/json/decode_string.go @@ -0,0 +1,91 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "strconv" + "unicode" + "unicode/utf16" + "unicode/utf8" + + "google.golang.org/protobuf/internal/strs" +) + +func (d *Decoder) parseString(in []byte) (string, int, error) { + in0 := in + if len(in) == 0 { + return "", 0, ErrUnexpectedEOF + } + if in[0] != '"' { + return "", 0, d.newSyntaxError(d.currPos(), "invalid character %q at start of string", in[0]) + } + in = in[1:] + i := indexNeedEscapeInBytes(in) + in, out := in[i:], in[:i:i] // set cap to prevent mutations + for len(in) > 0 { + switch r, n := utf8.DecodeRune(in); { + case r == utf8.RuneError && n == 1: + return "", 0, d.newSyntaxError(d.currPos(), "invalid UTF-8 in string") + case r < ' ': + return "", 0, d.newSyntaxError(d.currPos(), "invalid character %q in string", r) + case r == '"': + in = in[1:] + n := len(in0) - len(in) + return string(out), n, nil + case r == '\\': + if len(in) < 2 { + return "", 0, ErrUnexpectedEOF + } + switch r := in[1]; r { + case '"', '\\', '/': + in, out = in[2:], append(out, r) + case 'b': + in, out = in[2:], append(out, '\b') + case 'f': + in, out = in[2:], append(out, '\f') + case 'n': + in, out = in[2:], append(out, '\n') + case 'r': + in, out = in[2:], append(out, '\r') + case 't': + in, out = in[2:], append(out, '\t') + case 'u': + if len(in) < 6 { + return "", 0, ErrUnexpectedEOF + } + v, err := strconv.ParseUint(string(in[2:6]), 16, 16) + if err != nil { + return "", 0, d.newSyntaxError(d.currPos(), "invalid escape code %q in string", in[:6]) + } + in = in[6:] + + r := rune(v) + if utf16.IsSurrogate(r) { + if len(in) < 6 { + return "", 0, ErrUnexpectedEOF + } + v, err := strconv.ParseUint(string(in[2:6]), 16, 16) + r = utf16.DecodeRune(r, rune(v)) + if in[0] != '\\' || in[1] != 'u' || + r == unicode.ReplacementChar || err != nil { + return "", 0, d.newSyntaxError(d.currPos(), "invalid escape code %q in string", in[:6]) + } + in = in[6:] + } + out = append(out, string(r)...) + default: + return "", 0, d.newSyntaxError(d.currPos(), "invalid escape code %q in string", in[:2]) + } + default: + i := indexNeedEscapeInBytes(in[n:]) + in, out = in[n+i:], append(out, in[:n+i]...) + } + } + return "", 0, ErrUnexpectedEOF +} + +// indexNeedEscapeInBytes returns the index of the character that needs +// escaping. If no characters need escaping, this returns the input length. +func indexNeedEscapeInBytes(b []byte) int { return indexNeedEscapeInString(strs.UnsafeString(b)) } diff --git a/vendor/google.golang.org/protobuf/internal/encoding/json/decode_token.go b/vendor/google.golang.org/protobuf/internal/encoding/json/decode_token.go new file mode 100644 index 000000000000..50578d6593c1 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/json/decode_token.go @@ -0,0 +1,192 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "bytes" + "fmt" + "strconv" +) + +// Kind represents a token kind expressible in the JSON format. +type Kind uint16 + +const ( + Invalid Kind = (1 << iota) / 2 + EOF + Null + Bool + Number + String + Name + ObjectOpen + ObjectClose + ArrayOpen + ArrayClose + + // comma is only for parsing in between tokens and + // does not need to be exported. + comma +) + +func (k Kind) String() string { + switch k { + case EOF: + return "eof" + case Null: + return "null" + case Bool: + return "bool" + case Number: + return "number" + case String: + return "string" + case ObjectOpen: + return "{" + case ObjectClose: + return "}" + case Name: + return "name" + case ArrayOpen: + return "[" + case ArrayClose: + return "]" + case comma: + return "," + } + return "" +} + +// Token provides a parsed token kind and value. +// +// Values are provided by the difference accessor methods. The accessor methods +// Name, Bool, and ParsedString will panic if called on the wrong kind. There +// are different accessor methods for the Number kind for converting to the +// appropriate Go numeric type and those methods have the ok return value. +type Token struct { + // Token kind. + kind Kind + // pos provides the position of the token in the original input. + pos int + // raw bytes of the serialized token. + // This is a subslice into the original input. + raw []byte + // boo is parsed boolean value. + boo bool + // str is parsed string value. + str string +} + +// Kind returns the token kind. +func (t Token) Kind() Kind { + return t.kind +} + +// RawString returns the read value in string. +func (t Token) RawString() string { + return string(t.raw) +} + +// Pos returns the token position from the input. +func (t Token) Pos() int { + return t.pos +} + +// Name returns the object name if token is Name, else it panics. +func (t Token) Name() string { + if t.kind == Name { + return t.str + } + panic(fmt.Sprintf("Token is not a Name: %v", t.RawString())) +} + +// Bool returns the bool value if token kind is Bool, else it panics. +func (t Token) Bool() bool { + if t.kind == Bool { + return t.boo + } + panic(fmt.Sprintf("Token is not a Bool: %v", t.RawString())) +} + +// ParsedString returns the string value for a JSON string token or the read +// value in string if token is not a string. +func (t Token) ParsedString() string { + if t.kind == String { + return t.str + } + panic(fmt.Sprintf("Token is not a String: %v", t.RawString())) +} + +// Float returns the floating-point number if token kind is Number. +// +// The floating-point precision is specified by the bitSize parameter: 32 for +// float32 or 64 for float64. If bitSize=32, the result still has type float64, +// but it will be convertible to float32 without changing its value. It will +// return false if the number exceeds the floating point limits for given +// bitSize. +func (t Token) Float(bitSize int) (float64, bool) { + if t.kind != Number { + return 0, false + } + f, err := strconv.ParseFloat(t.RawString(), bitSize) + if err != nil { + return 0, false + } + return f, true +} + +// Int returns the signed integer number if token is Number. +// +// The given bitSize specifies the integer type that the result must fit into. +// It returns false if the number is not an integer value or if the result +// exceeds the limits for given bitSize. +func (t Token) Int(bitSize int) (int64, bool) { + s, ok := t.getIntStr() + if !ok { + return 0, false + } + n, err := strconv.ParseInt(s, 10, bitSize) + if err != nil { + return 0, false + } + return n, true +} + +// Uint returns the signed integer number if token is Number. +// +// The given bitSize specifies the unsigned integer type that the result must +// fit into. It returns false if the number is not an unsigned integer value +// or if the result exceeds the limits for given bitSize. +func (t Token) Uint(bitSize int) (uint64, bool) { + s, ok := t.getIntStr() + if !ok { + return 0, false + } + n, err := strconv.ParseUint(s, 10, bitSize) + if err != nil { + return 0, false + } + return n, true +} + +func (t Token) getIntStr() (string, bool) { + if t.kind != Number { + return "", false + } + parts, ok := parseNumberParts(t.raw) + if !ok { + return "", false + } + return normalizeToIntString(parts) +} + +// TokenEquals returns true if given Tokens are equal, else false. +func TokenEquals(x, y Token) bool { + return x.kind == y.kind && + x.pos == y.pos && + bytes.Equal(x.raw, y.raw) && + x.boo == y.boo && + x.str == y.str +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/json/encode.go b/vendor/google.golang.org/protobuf/internal/encoding/json/encode.go new file mode 100644 index 000000000000..fbdf34873420 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/json/encode.go @@ -0,0 +1,276 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json + +import ( + "math" + "math/bits" + "strconv" + "strings" + "unicode/utf8" + + "google.golang.org/protobuf/internal/detrand" + "google.golang.org/protobuf/internal/errors" +) + +// kind represents an encoding type. +type kind uint8 + +const ( + _ kind = (1 << iota) / 2 + name + scalar + objectOpen + objectClose + arrayOpen + arrayClose +) + +// Encoder provides methods to write out JSON constructs and values. The user is +// responsible for producing valid sequences of JSON constructs and values. +type Encoder struct { + indent string + lastKind kind + indents []byte + out []byte +} + +// NewEncoder returns an Encoder. +// +// If indent is a non-empty string, it causes every entry for an Array or Object +// to be preceded by the indent and trailed by a newline. +func NewEncoder(indent string) (*Encoder, error) { + e := &Encoder{} + if len(indent) > 0 { + if strings.Trim(indent, " \t") != "" { + return nil, errors.New("indent may only be composed of space or tab characters") + } + e.indent = indent + } + return e, nil +} + +// Bytes returns the content of the written bytes. +func (e *Encoder) Bytes() []byte { + return e.out +} + +// WriteNull writes out the null value. +func (e *Encoder) WriteNull() { + e.prepareNext(scalar) + e.out = append(e.out, "null"...) +} + +// WriteBool writes out the given boolean value. +func (e *Encoder) WriteBool(b bool) { + e.prepareNext(scalar) + if b { + e.out = append(e.out, "true"...) + } else { + e.out = append(e.out, "false"...) + } +} + +// WriteString writes out the given string in JSON string value. Returns error +// if input string contains invalid UTF-8. +func (e *Encoder) WriteString(s string) error { + e.prepareNext(scalar) + var err error + if e.out, err = appendString(e.out, s); err != nil { + return err + } + return nil +} + +// Sentinel error used for indicating invalid UTF-8. +var errInvalidUTF8 = errors.New("invalid UTF-8") + +func appendString(out []byte, in string) ([]byte, error) { + out = append(out, '"') + i := indexNeedEscapeInString(in) + in, out = in[i:], append(out, in[:i]...) + for len(in) > 0 { + switch r, n := utf8.DecodeRuneInString(in); { + case r == utf8.RuneError && n == 1: + return out, errInvalidUTF8 + case r < ' ' || r == '"' || r == '\\': + out = append(out, '\\') + switch r { + case '"', '\\': + out = append(out, byte(r)) + case '\b': + out = append(out, 'b') + case '\f': + out = append(out, 'f') + case '\n': + out = append(out, 'n') + case '\r': + out = append(out, 'r') + case '\t': + out = append(out, 't') + default: + out = append(out, 'u') + out = append(out, "0000"[1+(bits.Len32(uint32(r))-1)/4:]...) + out = strconv.AppendUint(out, uint64(r), 16) + } + in = in[n:] + default: + i := indexNeedEscapeInString(in[n:]) + in, out = in[n+i:], append(out, in[:n+i]...) + } + } + out = append(out, '"') + return out, nil +} + +// indexNeedEscapeInString returns the index of the character that needs +// escaping. If no characters need escaping, this returns the input length. +func indexNeedEscapeInString(s string) int { + for i, r := range s { + if r < ' ' || r == '\\' || r == '"' || r == utf8.RuneError { + return i + } + } + return len(s) +} + +// WriteFloat writes out the given float and bitSize in JSON number value. +func (e *Encoder) WriteFloat(n float64, bitSize int) { + e.prepareNext(scalar) + e.out = appendFloat(e.out, n, bitSize) +} + +// appendFloat formats given float in bitSize, and appends to the given []byte. +func appendFloat(out []byte, n float64, bitSize int) []byte { + switch { + case math.IsNaN(n): + return append(out, `"NaN"`...) + case math.IsInf(n, +1): + return append(out, `"Infinity"`...) + case math.IsInf(n, -1): + return append(out, `"-Infinity"`...) + } + + // JSON number formatting logic based on encoding/json. + // See floatEncoder.encode for reference. + fmt := byte('f') + if abs := math.Abs(n); abs != 0 { + if bitSize == 64 && (abs < 1e-6 || abs >= 1e21) || + bitSize == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { + fmt = 'e' + } + } + out = strconv.AppendFloat(out, n, fmt, -1, bitSize) + if fmt == 'e' { + n := len(out) + if n >= 4 && out[n-4] == 'e' && out[n-3] == '-' && out[n-2] == '0' { + out[n-2] = out[n-1] + out = out[:n-1] + } + } + return out +} + +// WriteInt writes out the given signed integer in JSON number value. +func (e *Encoder) WriteInt(n int64) { + e.prepareNext(scalar) + e.out = append(e.out, strconv.FormatInt(n, 10)...) +} + +// WriteUint writes out the given unsigned integer in JSON number value. +func (e *Encoder) WriteUint(n uint64) { + e.prepareNext(scalar) + e.out = append(e.out, strconv.FormatUint(n, 10)...) +} + +// StartObject writes out the '{' symbol. +func (e *Encoder) StartObject() { + e.prepareNext(objectOpen) + e.out = append(e.out, '{') +} + +// EndObject writes out the '}' symbol. +func (e *Encoder) EndObject() { + e.prepareNext(objectClose) + e.out = append(e.out, '}') +} + +// WriteName writes out the given string in JSON string value and the name +// separator ':'. Returns error if input string contains invalid UTF-8, which +// should not be likely as protobuf field names should be valid. +func (e *Encoder) WriteName(s string) error { + e.prepareNext(name) + var err error + // Append to output regardless of error. + e.out, err = appendString(e.out, s) + e.out = append(e.out, ':') + return err +} + +// StartArray writes out the '[' symbol. +func (e *Encoder) StartArray() { + e.prepareNext(arrayOpen) + e.out = append(e.out, '[') +} + +// EndArray writes out the ']' symbol. +func (e *Encoder) EndArray() { + e.prepareNext(arrayClose) + e.out = append(e.out, ']') +} + +// prepareNext adds possible comma and indentation for the next value based +// on last type and indent option. It also updates lastKind to next. +func (e *Encoder) prepareNext(next kind) { + defer func() { + // Set lastKind to next. + e.lastKind = next + }() + + if len(e.indent) == 0 { + // Need to add comma on the following condition. + if e.lastKind&(scalar|objectClose|arrayClose) != 0 && + next&(name|scalar|objectOpen|arrayOpen) != 0 { + e.out = append(e.out, ',') + // For single-line output, add a random extra space after each + // comma to make output unstable. + if detrand.Bool() { + e.out = append(e.out, ' ') + } + } + return + } + + switch { + case e.lastKind&(objectOpen|arrayOpen) != 0: + // If next type is NOT closing, add indent and newline. + if next&(objectClose|arrayClose) == 0 { + e.indents = append(e.indents, e.indent...) + e.out = append(e.out, '\n') + e.out = append(e.out, e.indents...) + } + + case e.lastKind&(scalar|objectClose|arrayClose) != 0: + switch { + // If next type is either a value or name, add comma and newline. + case next&(name|scalar|objectOpen|arrayOpen) != 0: + e.out = append(e.out, ',', '\n') + + // If next type is a closing object or array, adjust indentation. + case next&(objectClose|arrayClose) != 0: + e.indents = e.indents[:len(e.indents)-len(e.indent)] + e.out = append(e.out, '\n') + } + e.out = append(e.out, e.indents...) + + case e.lastKind&name != 0: + e.out = append(e.out, ' ') + // For multi-line output, add a random extra space after key: to make + // output unstable. + if detrand.Bool() { + e.out = append(e.out, ' ') + } + } +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go b/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go index eb10ea10261a..37803773fa39 100644 --- a/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go +++ b/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go @@ -381,7 +381,7 @@ func (d *Decoder) currentOpenKind() (Kind, byte) { case '[': return ListOpen, ']' } - panic(fmt.Sprintf("Decoder: openStack contains invalid byte %s", string(openCh))) + panic(fmt.Sprintf("Decoder: openStack contains invalid byte %c", openCh)) } func (d *Decoder) pushOpenStack(ch byte) { diff --git a/vendor/google.golang.org/protobuf/internal/errors/is_go112.go b/vendor/google.golang.org/protobuf/internal/errors/is_go112.go index f90e909b37ab..fbcd349207dd 100644 --- a/vendor/google.golang.org/protobuf/internal/errors/is_go112.go +++ b/vendor/google.golang.org/protobuf/internal/errors/is_go112.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !go1.13 // +build !go1.13 package errors diff --git a/vendor/google.golang.org/protobuf/internal/errors/is_go113.go b/vendor/google.golang.org/protobuf/internal/errors/is_go113.go index dc05f4191c01..5e72f1cde9e1 100644 --- a/vendor/google.golang.org/protobuf/internal/errors/is_go113.go +++ b/vendor/google.golang.org/protobuf/internal/errors/is_go113.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build go1.13 // +build go1.13 package errors diff --git a/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go b/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go index a72995f02d9e..bda8e8cf3fce 100644 --- a/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go +++ b/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !protolegacy // +build !protolegacy package flags diff --git a/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go b/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go index 772e2f0e4d69..6d8d9bd6b01a 100644 --- a/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go +++ b/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build protolegacy // +build protolegacy package flags diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go b/vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go index 2706bb67f5d8..4b15493f2f43 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !go1.12 // +build !go1.12 package impl diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go b/vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go index 1533ef600cd8..0b31b66eaf84 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build go1.12 // +build go1.12 package impl diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_reflect.go b/vendor/google.golang.org/protobuf/internal/impl/codec_reflect.go index 90705e3aea74..145c577bd6b2 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/codec_reflect.go +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_reflect.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build purego || appengine // +build purego appengine package impl diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go b/vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go index e118af1e20cd..757642e23c9e 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !purego && !appengine // +build !purego,!appengine package impl diff --git a/vendor/google.golang.org/protobuf/internal/impl/decode.go b/vendor/google.golang.org/protobuf/internal/impl/decode.go index 949dc49a65b3..c65b0325c17e 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/decode.go +++ b/vendor/google.golang.org/protobuf/internal/impl/decode.go @@ -18,6 +18,7 @@ import ( ) var errDecode = errors.New("cannot parse invalid wire-format data") +var errRecursionDepth = errors.New("exceeded maximum recursion depth") type unmarshalOptions struct { flags protoiface.UnmarshalInputFlags @@ -25,6 +26,7 @@ type unmarshalOptions struct { FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) } + depth int } func (o unmarshalOptions) Options() proto.UnmarshalOptions { @@ -44,6 +46,7 @@ func (o unmarshalOptions) IsDefault() bool { var lazyUnmarshalOptions = unmarshalOptions{ resolver: preg.GlobalTypes, + depth: protowire.DefaultRecursionLimit, } type unmarshalOutput struct { @@ -62,6 +65,7 @@ func (mi *MessageInfo) unmarshal(in piface.UnmarshalInput) (piface.UnmarshalOutp out, err := mi.unmarshalPointer(in.Buf, p, 0, unmarshalOptions{ flags: in.Flags, resolver: in.Resolver, + depth: in.Depth, }) var flags piface.UnmarshalOutputFlags if out.initialized { @@ -82,6 +86,10 @@ var errUnknown = errors.New("unknown") func (mi *MessageInfo) unmarshalPointer(b []byte, p pointer, groupTag protowire.Number, opts unmarshalOptions) (out unmarshalOutput, err error) { mi.init() + opts.depth-- + if opts.depth < 0 { + return out, errRecursionDepth + } if flags.ProtoLegacy && mi.isMessageSet { return unmarshalMessageSet(mi, b, p, opts) } diff --git a/vendor/google.golang.org/protobuf/internal/impl/pointer_reflect.go b/vendor/google.golang.org/protobuf/internal/impl/pointer_reflect.go index 9e3ed821efb3..4c491bdf4825 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/pointer_reflect.go +++ b/vendor/google.golang.org/protobuf/internal/impl/pointer_reflect.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build purego || appengine // +build purego appengine package impl diff --git a/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go b/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go index 9ecf23a85bb7..ee0e0573e395 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go +++ b/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !purego && !appengine // +build !purego,!appengine package impl diff --git a/vendor/google.golang.org/protobuf/internal/strs/strings_pure.go b/vendor/google.golang.org/protobuf/internal/strs/strings_pure.go index 85e074c977dc..a1f6f333860e 100644 --- a/vendor/google.golang.org/protobuf/internal/strs/strings_pure.go +++ b/vendor/google.golang.org/protobuf/internal/strs/strings_pure.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build purego || appengine // +build purego appengine package strs diff --git a/vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go b/vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go index 2160c7019145..56a8a4ed3c9d 100644 --- a/vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go +++ b/vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !purego && !appengine // +build !purego,!appengine package strs diff --git a/vendor/google.golang.org/protobuf/internal/version/version.go b/vendor/google.golang.org/protobuf/internal/version/version.go index 14e774fb2ec7..3d40d5249e96 100644 --- a/vendor/google.golang.org/protobuf/internal/version/version.go +++ b/vendor/google.golang.org/protobuf/internal/version/version.go @@ -52,8 +52,8 @@ import ( // 10. Send out the CL for review and submit it. const ( Major = 1 - Minor = 27 - Patch = 1 + Minor = 28 + Patch = 0 PreRelease = "" ) diff --git a/vendor/google.golang.org/protobuf/proto/decode.go b/vendor/google.golang.org/protobuf/proto/decode.go index 49f9b8c88cfd..11bf7173be92 100644 --- a/vendor/google.golang.org/protobuf/proto/decode.go +++ b/vendor/google.golang.org/protobuf/proto/decode.go @@ -42,18 +42,25 @@ type UnmarshalOptions struct { FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) } + + // RecursionLimit limits how deeply messages may be nested. + // If zero, a default limit is applied. + RecursionLimit int } // Unmarshal parses the wire-format message in b and places the result in m. // The provided message must be mutable (e.g., a non-nil pointer to a message). func Unmarshal(b []byte, m Message) error { - _, err := UnmarshalOptions{}.unmarshal(b, m.ProtoReflect()) + _, err := UnmarshalOptions{RecursionLimit: protowire.DefaultRecursionLimit}.unmarshal(b, m.ProtoReflect()) return err } // Unmarshal parses the wire-format message in b and places the result in m. // The provided message must be mutable (e.g., a non-nil pointer to a message). func (o UnmarshalOptions) Unmarshal(b []byte, m Message) error { + if o.RecursionLimit == 0 { + o.RecursionLimit = protowire.DefaultRecursionLimit + } _, err := o.unmarshal(b, m.ProtoReflect()) return err } @@ -63,6 +70,9 @@ func (o UnmarshalOptions) Unmarshal(b []byte, m Message) error { // This method permits fine-grained control over the unmarshaler. // Most users should use Unmarshal instead. func (o UnmarshalOptions) UnmarshalState(in protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + if o.RecursionLimit == 0 { + o.RecursionLimit = protowire.DefaultRecursionLimit + } return o.unmarshal(in.Buf, in.Message) } @@ -86,12 +96,17 @@ func (o UnmarshalOptions) unmarshal(b []byte, m protoreflect.Message) (out proto Message: m, Buf: b, Resolver: o.Resolver, + Depth: o.RecursionLimit, } if o.DiscardUnknown { in.Flags |= protoiface.UnmarshalDiscardUnknown } out, err = methods.Unmarshal(in) } else { + o.RecursionLimit-- + if o.RecursionLimit < 0 { + return out, errors.New("exceeded max recursion depth") + } err = o.unmarshalMessageSlow(b, m) } if err != nil { diff --git a/vendor/google.golang.org/protobuf/proto/proto_methods.go b/vendor/google.golang.org/protobuf/proto/proto_methods.go index d8dd604f6b67..465e057b3238 100644 --- a/vendor/google.golang.org/protobuf/proto/proto_methods.go +++ b/vendor/google.golang.org/protobuf/proto/proto_methods.go @@ -3,6 +3,7 @@ // license that can be found in the LICENSE file. // The protoreflect build tag disables use of fast-path methods. +//go:build !protoreflect // +build !protoreflect package proto diff --git a/vendor/google.golang.org/protobuf/proto/proto_reflect.go b/vendor/google.golang.org/protobuf/proto/proto_reflect.go index b103d43205c4..494d6ceef9e6 100644 --- a/vendor/google.golang.org/protobuf/proto/proto_reflect.go +++ b/vendor/google.golang.org/protobuf/proto/proto_reflect.go @@ -3,6 +3,7 @@ // license that can be found in the LICENSE file. // The protoreflect build tag disables use of fast-path methods. +//go:build protoreflect // +build protoreflect package proto diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go index 6be5d16e9f37..d5d5af6ebedb 100644 --- a/vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go @@ -53,6 +53,7 @@ type ( FindExtensionByName(field FullName) (ExtensionType, error) FindExtensionByNumber(message FullName, field FieldNumber) (ExtensionType, error) } + Depth int } unmarshalOutput = struct { pragma.NoUnkeyedLiterals diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go index 918e685e1d57..7ced876f4e89 100644 --- a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build purego || appengine // +build purego appengine package protoreflect diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go index 5a3414724193..eb7764c307c0 100644 --- a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go @@ -41,6 +41,31 @@ import ( // Converting to/from a Value and a concrete Go value panics on type mismatch. // For example, ValueOf("hello").Int() panics because this attempts to // retrieve an int64 from a string. +// +// List, Map, and Message Values are called "composite" values. +// +// A composite Value may alias (reference) memory at some location, +// such that changes to the Value updates the that location. +// A composite value acquired with a Mutable method, such as Message.Mutable, +// always references the source object. +// +// For example: +// // Append a 0 to a "repeated int32" field. +// // Since the Value returned by Mutable is guaranteed to alias +// // the source message, modifying the Value modifies the message. +// message.Mutable(fieldDesc).(List).Append(protoreflect.ValueOfInt32(0)) +// +// // Assign [0] to a "repeated int32" field by creating a new Value, +// // modifying it, and assigning it. +// list := message.NewField(fieldDesc).(List) +// list.Append(protoreflect.ValueOfInt32(0)) +// message.Set(fieldDesc, list) +// // ERROR: Since it is not defined whether Set aliases the source, +// // appending to the List here may or may not modify the message. +// list.Append(protoreflect.ValueOfInt32(0)) +// +// Some operations, such as Message.Get, may return an "empty, read-only" +// composite Value. Modifying an empty, read-only value panics. type Value value // The protoreflect API uses a custom Value union type instead of interface{} diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go index c45debdcac6c..702ddf22a274 100644 --- a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !purego && !appengine // +build !purego,!appengine package protoreflect diff --git a/vendor/google.golang.org/protobuf/runtime/protoiface/methods.go b/vendor/google.golang.org/protobuf/runtime/protoiface/methods.go index 32c04f67eb73..44cf467d8845 100644 --- a/vendor/google.golang.org/protobuf/runtime/protoiface/methods.go +++ b/vendor/google.golang.org/protobuf/runtime/protoiface/methods.go @@ -103,6 +103,7 @@ type UnmarshalInput = struct { FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) } + Depth int } // UnmarshalOutput is output from the Unmarshal method. diff --git a/vendor/gopkg.in/yaml.v3/parserc.go b/vendor/gopkg.in/yaml.v3/parserc.go index ac66fccc059e..268558a0d632 100644 --- a/vendor/gopkg.in/yaml.v3/parserc.go +++ b/vendor/gopkg.in/yaml.v3/parserc.go @@ -687,6 +687,9 @@ func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, i func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) + if token == nil { + return false + } parser.marks = append(parser.marks, token.start_mark) skip_token(parser) } @@ -786,7 +789,7 @@ func yaml_parser_split_stem_comment(parser *yaml_parser_t, stem_len int) { } token := peek_token(parser) - if token.typ != yaml_BLOCK_SEQUENCE_START_TOKEN && token.typ != yaml_BLOCK_MAPPING_START_TOKEN { + if token == nil || token.typ != yaml_BLOCK_SEQUENCE_START_TOKEN && token.typ != yaml_BLOCK_MAPPING_START_TOKEN { return } @@ -813,6 +816,9 @@ func yaml_parser_split_stem_comment(parser *yaml_parser_t, stem_len int) { func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) + if token == nil { + return false + } parser.marks = append(parser.marks, token.start_mark) skip_token(parser) } @@ -922,6 +928,9 @@ func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_ev func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) + if token == nil { + return false + } parser.marks = append(parser.marks, token.start_mark) skip_token(parser) } diff --git a/vendor/modules.txt b/vendor/modules.txt index a7e83b28c587..c58333770961 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,6 +1,4 @@ -# cloud.google.com/go/storage v1.16.0 -## explicit; go 1.11 -# github.com/Azure/azure-sdk-for-go v64.1.0+incompatible +# github.com/Azure/azure-sdk-for-go v65.0.0+incompatible ## explicit github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/resources/mgmt/resources github.com/Azure/azure-sdk-for-go/services/aad/mgmt/2017-04-01/aad @@ -13,7 +11,6 @@ github.com/Azure/azure-sdk-for-go/services/cdn/mgmt/2020-09-01/cdn github.com/Azure/azure-sdk-for-go/services/cdn/mgmt/2021-06-01/cdn github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute github.com/Azure/azure-sdk-for-go/services/consumption/mgmt/2019-10-01/consumption -github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2019-08-01/containerservice github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2021-10-15/documentdb github.com/Azure/azure-sdk-for-go/services/costmanagement/mgmt/2020-06-01/costmanagement @@ -35,25 +32,23 @@ github.com/Azure/azure-sdk-for-go/services/healthcareapis/mgmt/2021-11-01/health github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2021-07-02/devices github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2021-10-01/keyvault github.com/Azure/azure-sdk-for-go/services/keyvault/v7.1/keyvault -github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto +github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2022-02-01/kusto github.com/Azure/azure-sdk-for-go/services/logic/mgmt/2019-05-01/logic github.com/Azure/azure-sdk-for-go/services/logz/mgmt/2020-10-01/logz github.com/Azure/azure-sdk-for-go/services/machinelearningservices/mgmt/2021-07-01/machinelearningservices github.com/Azure/azure-sdk-for-go/services/maintenance/mgmt/2021-05-01/maintenance -github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices github.com/Azure/azure-sdk-for-go/services/mariadb/mgmt/2018-06-01/mariadb github.com/Azure/azure-sdk-for-go/services/marketplaceordering/mgmt/2015-06-01/marketplaceordering github.com/Azure/azure-sdk-for-go/services/mediaservices/mgmt/2021-05-01/media github.com/Azure/azure-sdk-for-go/services/monitor/mgmt/2020-10-01/insights github.com/Azure/azure-sdk-for-go/services/mysql/mgmt/2020-01-01/mysql github.com/Azure/azure-sdk-for-go/services/mysql/mgmt/2021-05-01/mysqlflexibleservers -github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp github.com/Azure/azure-sdk-for-go/services/network/mgmt/2021-08-01/network github.com/Azure/azure-sdk-for-go/services/operationalinsights/mgmt/2020-08-01/operationalinsights github.com/Azure/azure-sdk-for-go/services/postgresql/mgmt/2020-01-01/postgresql github.com/Azure/azure-sdk-for-go/services/postgresql/mgmt/2021-06-01/postgresqlflexibleservers github.com/Azure/azure-sdk-for-go/services/preview/alertsmanagement/mgmt/2019-06-01-preview/alertsmanagement -github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform +github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-05-01-preview/appplatform github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2020-04-01-preview/authorization github.com/Azure/azure-sdk-for-go/services/preview/automation/mgmt/2020-01-13-preview/automation github.com/Azure/azure-sdk-for-go/services/preview/blueprint/mgmt/2018-11-01-preview/blueprint @@ -65,13 +60,10 @@ github.com/Azure/azure-sdk-for-go/services/preview/customproviders/mgmt/2018-09- github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2021-07-01-preview/insights github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2021-09-01-preview/insights github.com/Azure/azure-sdk-for-go/services/preview/operationsmanagement/mgmt/2015-11-01-preview/operationsmanagement -github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights -github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2019-06-01-preview/templatespecs github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2021-06-01-preview/policy github.com/Azure/azure-sdk-for-go/services/preview/security/mgmt/v3.0/security github.com/Azure/azure-sdk-for-go/services/preview/securityinsight/mgmt/2021-09-01-preview/securityinsight -github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-03-01-preview/sql github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2018-06-01-preview/sql github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v5.0/sql @@ -141,8 +133,6 @@ github.com/apparentlymart/go-textseg/textseg # github.com/apparentlymart/go-textseg/v13 v13.0.0 ## explicit; go 1.16 github.com/apparentlymart/go-textseg/v13/textseg -# github.com/aws/aws-sdk-go v1.38.69 -## explicit; go 1.11 # github.com/btubbs/datetime v0.1.0 ## explicit github.com/btubbs/datetime @@ -152,7 +142,7 @@ github.com/davecgh/go-spew/spew # github.com/dimchansky/utfbom v1.1.1 ## explicit github.com/dimchansky/utfbom -# github.com/fatih/color v1.12.0 +# github.com/fatih/color v1.13.0 ## explicit; go 1.13 github.com/fatih/color # github.com/gofrs/uuid v4.0.0+incompatible @@ -161,12 +151,10 @@ github.com/gofrs/uuid # github.com/golang-jwt/jwt/v4 v4.4.1 ## explicit; go 1.16 github.com/golang-jwt/jwt/v4 -# github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da -## explicit # github.com/golang/protobuf v1.5.2 ## explicit; go 1.9 +github.com/golang/protobuf/jsonpb github.com/golang/protobuf/proto -github.com/golang/protobuf/protoc-gen-go/descriptor github.com/golang/protobuf/ptypes github.com/golang/protobuf/ptypes/any github.com/golang/protobuf/ptypes/duration @@ -185,7 +173,7 @@ github.com/google/uuid # github.com/hashicorp/errwrap v1.1.0 ## explicit github.com/hashicorp/errwrap -# github.com/hashicorp/go-azure-helpers v0.35.0 +# github.com/hashicorp/go-azure-helpers v0.37.0 ## explicit; go 1.17 github.com/hashicorp/go-azure-helpers/authentication github.com/hashicorp/go-azure-helpers/lang/dates @@ -205,16 +193,21 @@ github.com/hashicorp/go-azure-helpers/resourcemanager/zones github.com/hashicorp/go-azure-helpers/resourceproviders github.com/hashicorp/go-azure-helpers/sender github.com/hashicorp/go-azure-helpers/storage -# github.com/hashicorp/go-azure-sdk v0.20220701.1073833 +# github.com/hashicorp/go-azure-sdk v0.20220715.1071215 ## explicit; go 1.18 github.com/hashicorp/go-azure-sdk/resource-manager/aadb2c/2021-04-01-preview/tenants github.com/hashicorp/go-azure-sdk/resource-manager/analysisservices/2017-08-01/servers -github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores +github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2022-05-01/configurationstores +github.com/hashicorp/go-azure-sdk/resource-manager/applicationinsights/2020-11-20/applicationinsights github.com/hashicorp/go-azure-sdk/resource-manager/attestation/2020-10-01/attestationproviders github.com/hashicorp/go-azure-sdk/resource-manager/azurestackhci/2020-10-01/clusters github.com/hashicorp/go-azure-sdk/resource-manager/cognitive/2021-04-30/cognitiveservicesaccounts github.com/hashicorp/go-azure-sdk/resource-manager/communication/2020-08-20/communicationservice +github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/availabilitysets +github.com/hashicorp/go-azure-sdk/resource-manager/compute/2021-11-01/sshpublickeys github.com/hashicorp/go-azure-sdk/resource-manager/confidentialledger/2022-05-13/confidentialledger +github.com/hashicorp/go-azure-sdk/resource-manager/containerinstance/2021-03-01/containerinstance +github.com/hashicorp/go-azure-sdk/resource-manager/databricks/2021-04-01-preview/workspaces github.com/hashicorp/go-azure-sdk/resource-manager/dataprotection/2022-04-01/resourceguards github.com/hashicorp/go-azure-sdk/resource-manager/desktopvirtualization/2021-09-03-preview/application github.com/hashicorp/go-azure-sdk/resource-manager/desktopvirtualization/2021-09-03-preview/applicationgroup @@ -225,15 +218,34 @@ github.com/hashicorp/go-azure-sdk/resource-manager/desktopvirtualization/2021-09 github.com/hashicorp/go-azure-sdk/resource-manager/desktopvirtualization/2021-09-03-preview/workspace github.com/hashicorp/go-azure-sdk/resource-manager/elastic/2020-07-01/monitorsresource github.com/hashicorp/go-azure-sdk/resource-manager/elastic/2020-07-01/rules +github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationruleseventhubs +github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/authorizationrulesnamespaces +github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs +github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/consumergroups +github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/disasterrecoveryconfigs +github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/eventhubs +github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/eventhubsclusters +github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2018-01-01-preview/networkrulesets +github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2021-01-01-preview/namespaces +github.com/hashicorp/go-azure-sdk/resource-manager/fluidrelay/2022-05-26/fluidrelayservers github.com/hashicorp/go-azure-sdk/resource-manager/hardwaresecuritymodules/2021-11-30/dedicatedhsms github.com/hashicorp/go-azure-sdk/resource-manager/iotcentral/2021-11-01-preview/apps github.com/hashicorp/go-azure-sdk/resource-manager/loadtestservice/2021-12-01-preview/loadtests github.com/hashicorp/go-azure-sdk/resource-manager/managedidentity/2018-11-30/managedidentity +github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments +github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationdefinitions github.com/hashicorp/go-azure-sdk/resource-manager/maps/2021-02-01/accounts github.com/hashicorp/go-azure-sdk/resource-manager/maps/2021-02-01/creators github.com/hashicorp/go-azure-sdk/resource-manager/mixedreality/2021-01-01/resource +github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/capacitypools +github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/netappaccounts +github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshotpolicy +github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/snapshots +github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumes +github.com/hashicorp/go-azure-sdk/resource-manager/netapp/2021-10-01/volumesreplication github.com/hashicorp/go-azure-sdk/resource-manager/notificationhubs/2017-04-01/namespaces github.com/hashicorp/go-azure-sdk/resource-manager/notificationhubs/2017-04-01/notificationhubs +github.com/hashicorp/go-azure-sdk/resource-manager/policyinsights/2021-10-01/policyinsights github.com/hashicorp/go-azure-sdk/resource-manager/portal/2019-01-01-preview/dashboard github.com/hashicorp/go-azure-sdk/resource-manager/portal/2019-01-01-preview/tenantconfiguration github.com/hashicorp/go-azure-sdk/resource-manager/powerbidedicated/2021-01-01/capacities @@ -248,9 +260,20 @@ github.com/hashicorp/go-azure-sdk/resource-manager/relay/2017-04-01/namespaces github.com/hashicorp/go-azure-sdk/resource-manager/search/2020-03-13/adminkeys github.com/hashicorp/go-azure-sdk/resource-manager/search/2020-03-13/querykeys github.com/hashicorp/go-azure-sdk/resource-manager/search/2020-03-13/services +github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/disasterrecoveryconfigs +github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespaces +github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/namespacesauthorizationrule +github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queues +github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/queuesauthorizationrule +github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/rules +github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/subscriptions +github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topics +github.com/hashicorp/go-azure-sdk/resource-manager/servicebus/2021-06-01-preview/topicsauthorizationrule github.com/hashicorp/go-azure-sdk/resource-manager/servicefabricmanagedcluster/2021-05-01/managedcluster github.com/hashicorp/go-azure-sdk/resource-manager/servicefabricmanagedcluster/2021-05-01/nodetype +github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr github.com/hashicorp/go-azure-sdk/resource-manager/sqlvirtualmachine/2022-02-01/sqlvirtualmachines +github.com/hashicorp/go-azure-sdk/resource-manager/storage/2021-04-01/objectreplicationpolicies github.com/hashicorp/go-azure-sdk/resource-manager/trafficmanager/2018-08-01/endpoints github.com/hashicorp/go-azure-sdk/resource-manager/trafficmanager/2018-08-01/geographichierarchies github.com/hashicorp/go-azure-sdk/resource-manager/trafficmanager/2018-08-01/profiles @@ -274,28 +297,26 @@ github.com/hashicorp/go-cty/cty/gocty github.com/hashicorp/go-cty/cty/json github.com/hashicorp/go-cty/cty/msgpack github.com/hashicorp/go-cty/cty/set -# github.com/hashicorp/go-getter v1.6.1 -## explicit; go 1.13 -# github.com/hashicorp/go-hclog v0.16.1 +# github.com/hashicorp/go-hclog v1.2.1 ## explicit; go 1.13 github.com/hashicorp/go-hclog # github.com/hashicorp/go-multierror v1.1.1 ## explicit; go 1.13 github.com/hashicorp/go-multierror -# github.com/hashicorp/go-plugin v1.4.2 -## explicit; go 1.13 +# github.com/hashicorp/go-plugin v1.4.4 +## explicit; go 1.17 github.com/hashicorp/go-plugin github.com/hashicorp/go-plugin/internal/plugin # github.com/hashicorp/go-retryablehttp v0.7.0 ## explicit; go 1.13 github.com/hashicorp/go-retryablehttp -# github.com/hashicorp/go-uuid v1.0.2 +# github.com/hashicorp/go-uuid v1.0.3 ## explicit github.com/hashicorp/go-uuid -# github.com/hashicorp/go-version v1.4.0 +# github.com/hashicorp/go-version v1.6.0 ## explicit github.com/hashicorp/go-version -# github.com/hashicorp/hc-install v0.3.2 +# github.com/hashicorp/hc-install v0.4.0 ## explicit; go 1.16 github.com/hashicorp/hc-install github.com/hashicorp/hc-install/checkpoint @@ -311,8 +332,8 @@ github.com/hashicorp/hc-install/internal/version github.com/hashicorp/hc-install/product github.com/hashicorp/hc-install/releases github.com/hashicorp/hc-install/src -# github.com/hashicorp/hcl/v2 v2.10.0 -## explicit; go 1.12 +# github.com/hashicorp/hcl/v2 v2.13.0 +## explicit; go 1.18 github.com/hashicorp/hcl/v2 github.com/hashicorp/hcl/v2/ext/customdecode github.com/hashicorp/hcl/v2/hclsyntax @@ -324,33 +345,39 @@ github.com/hashicorp/hcl2/hclwrite # github.com/hashicorp/logutils v1.0.0 ## explicit github.com/hashicorp/logutils -# github.com/hashicorp/terraform-exec v0.15.0 -## explicit; go 1.14 +# github.com/hashicorp/terraform-exec v0.17.2 +## explicit; go 1.17 github.com/hashicorp/terraform-exec/internal/version github.com/hashicorp/terraform-exec/tfexec -# github.com/hashicorp/terraform-json v0.13.0 +# github.com/hashicorp/terraform-json v0.14.0 ## explicit; go 1.13 github.com/hashicorp/terraform-json -# github.com/hashicorp/terraform-plugin-go v0.5.0 -## explicit; go 1.16 +# github.com/hashicorp/terraform-plugin-go v0.10.0 +## explicit; go 1.17 +github.com/hashicorp/terraform-plugin-go/internal/logging github.com/hashicorp/terraform-plugin-go/tfprotov5 +github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/diag github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/fromproto +github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tf5serverlogging github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5 github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/toproto github.com/hashicorp/terraform-plugin-go/tfprotov5/tf5server github.com/hashicorp/terraform-plugin-go/tfprotov6 +github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/diag github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/fromproto +github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tf6serverlogging github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6 github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/toproto github.com/hashicorp/terraform-plugin-go/tfprotov6/tf6server github.com/hashicorp/terraform-plugin-go/tftypes -# github.com/hashicorp/terraform-plugin-log v0.2.0 -## explicit; go 1.16 +# github.com/hashicorp/terraform-plugin-log v0.4.1 +## explicit; go 1.17 +github.com/hashicorp/terraform-plugin-log/internal/hclogutils github.com/hashicorp/terraform-plugin-log/internal/logging github.com/hashicorp/terraform-plugin-log/tflog github.com/hashicorp/terraform-plugin-log/tfsdklog -# github.com/hashicorp/terraform-plugin-sdk/v2 v2.10.1 -## explicit; go 1.16 +# github.com/hashicorp/terraform-plugin-sdk/v2 v2.18.0 +## explicit; go 1.17 github.com/hashicorp/terraform-plugin-sdk/v2/diag github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff @@ -363,6 +390,7 @@ github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/hashcode +github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging github.com/hashicorp/terraform-plugin-sdk/v2/internal/plans/objchange github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest @@ -370,7 +398,7 @@ github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags github.com/hashicorp/terraform-plugin-sdk/v2/meta github.com/hashicorp/terraform-plugin-sdk/v2/plugin github.com/hashicorp/terraform-plugin-sdk/v2/terraform -# github.com/hashicorp/terraform-registry-address v0.0.0-20210412075316-9b2996cce896 +# github.com/hashicorp/terraform-registry-address v0.0.0-20220623143253-7d51757b572c ## explicit; go 1.14 github.com/hashicorp/terraform-registry-address # github.com/hashicorp/terraform-svchost v0.0.0-20200729002733-f050f53b9734 @@ -379,8 +407,6 @@ github.com/hashicorp/terraform-svchost # github.com/hashicorp/yamux v0.0.0-20210316155119-a95892c5f864 ## explicit; go 1.15 github.com/hashicorp/yamux -# github.com/klauspost/compress v1.13.1 -## explicit; go 1.13 # github.com/magodo/terraform-provider-azurerm-example-gen v0.0.0-20220407025246-3a3ee0ab24a8 ## explicit; go 1.16 github.com/magodo/terraform-provider-azurerm-example-gen/examplegen @@ -396,10 +422,10 @@ github.com/manicminer/hamilton/odata ## explicit; go 1.16 github.com/manicminer/hamilton-autorest/auth github.com/manicminer/hamilton-autorest/environments -# github.com/mattn/go-colorable v0.1.8 +# github.com/mattn/go-colorable v0.1.12 ## explicit; go 1.13 github.com/mattn/go-colorable -# github.com/mattn/go-isatty v0.0.13 +# github.com/mattn/go-isatty v0.0.14 ## explicit; go 1.12 github.com/mattn/go-isatty # github.com/mitchellh/copystructure v1.2.0 @@ -414,7 +440,7 @@ github.com/mitchellh/go-testing-interface # github.com/mitchellh/go-wordwrap v1.0.1 ## explicit; go 1.14 github.com/mitchellh/go-wordwrap -# github.com/mitchellh/mapstructure v1.4.1 +# github.com/mitchellh/mapstructure v1.5.0 ## explicit; go 1.14 github.com/mitchellh/mapstructure # github.com/mitchellh/reflectwalk v1.0.2 @@ -452,13 +478,20 @@ github.com/tombuildsstuff/giovanni/storage/accesscontrol github.com/tombuildsstuff/giovanni/storage/internal/endpoints github.com/tombuildsstuff/giovanni/storage/internal/metadata github.com/tombuildsstuff/giovanni/version -# github.com/ulikunitz/xz v0.5.10 -## explicit; go 1.12 # github.com/vmihailenco/msgpack v4.0.4+incompatible ## explicit github.com/vmihailenco/msgpack github.com/vmihailenco/msgpack/codes -# github.com/zclconf/go-cty v1.9.1 +# github.com/vmihailenco/msgpack/v4 v4.3.12 +## explicit; go 1.11 +github.com/vmihailenco/msgpack/v4 +github.com/vmihailenco/msgpack/v4/codes +# github.com/vmihailenco/tagparser v0.1.1 +## explicit; go 1.13 +github.com/vmihailenco/tagparser +github.com/vmihailenco/tagparser/internal +github.com/vmihailenco/tagparser/internal/parser +# github.com/zclconf/go-cty v1.10.0 ## explicit; go 1.12 github.com/zclconf/go-cty/cty github.com/zclconf/go-cty/cty/convert @@ -467,7 +500,7 @@ github.com/zclconf/go-cty/cty/function/stdlib github.com/zclconf/go-cty/cty/gocty github.com/zclconf/go-cty/cty/json github.com/zclconf/go-cty/cty/set -# golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 +# golang.org/x/crypto v0.0.0-20220517005047-85d78b3ac167 ## explicit; go 1.17 golang.org/x/crypto/blowfish golang.org/x/crypto/cast5 @@ -511,8 +544,8 @@ golang.org/x/sys/cpu golang.org/x/sys/execabs golang.org/x/sys/internal/unsafeheader golang.org/x/sys/unix -# golang.org/x/text v0.3.6 -## explicit; go 1.11 +# golang.org/x/text v0.3.7 +## explicit; go 1.17 golang.org/x/text/secure/bidirule golang.org/x/text/transform golang.org/x/text/unicode/bidi @@ -540,8 +573,6 @@ golang.org/x/tools/internal/typesinternal ## explicit; go 1.11 golang.org/x/xerrors golang.org/x/xerrors/internal -# google.golang.org/api v0.49.0 -## explicit; go 1.11 # google.golang.org/appengine v1.6.7 ## explicit; go 1.11 google.golang.org/appengine @@ -560,8 +591,8 @@ google.golang.org/appengine/urlfetch # google.golang.org/genproto v0.0.0-20210629200056-84d6f6074151 ## explicit; go 1.11 google.golang.org/genproto/googleapis/rpc/status -# google.golang.org/grpc v1.39.0 -## explicit; go 1.11 +# google.golang.org/grpc v1.47.0 +## explicit; go 1.14 google.golang.org/grpc google.golang.org/grpc/attributes google.golang.org/grpc/backoff @@ -570,9 +601,11 @@ google.golang.org/grpc/balancer/base google.golang.org/grpc/balancer/grpclb/state google.golang.org/grpc/balancer/roundrobin google.golang.org/grpc/binarylog/grpc_binarylog_v1 +google.golang.org/grpc/channelz google.golang.org/grpc/codes google.golang.org/grpc/connectivity google.golang.org/grpc/credentials +google.golang.org/grpc/credentials/insecure google.golang.org/grpc/encoding google.golang.org/grpc/encoding/proto google.golang.org/grpc/grpclog @@ -580,6 +613,7 @@ google.golang.org/grpc/health google.golang.org/grpc/health/grpc_health_v1 google.golang.org/grpc/internal google.golang.org/grpc/internal/backoff +google.golang.org/grpc/internal/balancer/gracefulswitch google.golang.org/grpc/internal/balancerload google.golang.org/grpc/internal/binarylog google.golang.org/grpc/internal/buffer @@ -591,6 +625,7 @@ google.golang.org/grpc/internal/grpcrand google.golang.org/grpc/internal/grpcsync google.golang.org/grpc/internal/grpcutil google.golang.org/grpc/internal/metadata +google.golang.org/grpc/internal/pretty google.golang.org/grpc/internal/resolver google.golang.org/grpc/internal/resolver/dns google.golang.org/grpc/internal/resolver/passthrough @@ -610,14 +645,16 @@ google.golang.org/grpc/serviceconfig google.golang.org/grpc/stats google.golang.org/grpc/status google.golang.org/grpc/tap -# google.golang.org/protobuf v1.27.1 -## explicit; go 1.9 +# google.golang.org/protobuf v1.28.0 +## explicit; go 1.11 +google.golang.org/protobuf/encoding/protojson google.golang.org/protobuf/encoding/prototext google.golang.org/protobuf/encoding/protowire google.golang.org/protobuf/internal/descfmt google.golang.org/protobuf/internal/descopts google.golang.org/protobuf/internal/detrand google.golang.org/protobuf/internal/encoding/defval +google.golang.org/protobuf/internal/encoding/json google.golang.org/protobuf/internal/encoding/messageset google.golang.org/protobuf/internal/encoding/tag google.golang.org/protobuf/internal/encoding/text @@ -643,6 +680,6 @@ google.golang.org/protobuf/types/known/anypb google.golang.org/protobuf/types/known/durationpb google.golang.org/protobuf/types/known/emptypb google.golang.org/protobuf/types/known/timestamppb -# gopkg.in/yaml.v3 v3.0.0 +# gopkg.in/yaml.v3 v3.0.1 ## explicit gopkg.in/yaml.v3 diff --git a/website/allowed-subcategories b/website/allowed-subcategories index 51d664b4bd6e..b38792d449e7 100644 --- a/website/allowed-subcategories +++ b/website/allowed-subcategories @@ -40,6 +40,7 @@ Dev Test Digital Twins Disks Elastic +Fluid Relay HDInsight Hardware Security Module Healthcare diff --git a/website/docs/d/eventhub_authorization_rule.html.markdown b/website/docs/d/eventhub_authorization_rule.html.markdown index 8ef1ec44d841..be910e7569fc 100644 --- a/website/docs/d/eventhub_authorization_rule.html.markdown +++ b/website/docs/d/eventhub_authorization_rule.html.markdown @@ -1,4 +1,3 @@ - --- subcategory: "Messaging" layout: "azurerm" diff --git a/website/docs/d/kubernetes_cluster.html.markdown b/website/docs/d/kubernetes_cluster.html.markdown index 478f089bd067..27ce0292f3fa 100644 --- a/website/docs/d/kubernetes_cluster.html.markdown +++ b/website/docs/d/kubernetes_cluster.html.markdown @@ -128,6 +128,10 @@ A `agent_pool_profile` block exports the following: * `enable_node_public_ip` - If the Public IPs for the nodes in this Agent Pool are enabled. +* `host_group_id` - The ID of a Dedicated Host Group that this Node Pool should be run on. Changing this forces a new resource to be created. + +-> **Note:** This requires that the Preview Feature `Microsoft.ContainerService/DedicatedHostGroupPreview` is enabled and the Resource Provider is re-registered, see [the documentation](https://docs.microsoft.com/en-us/azure/aks/use-azure-dedicated-hosts#register-the-dedicatedhostgrouppreview-preview-feature) for more information. + * `min_count` - Minimum number of nodes for auto-scaling * `max_count` - Maximum number of nodes for auto-scaling diff --git a/website/docs/d/kubernetes_cluster_node_pool.html.markdown b/website/docs/d/kubernetes_cluster_node_pool.html.markdown index 64631a506785..6af43f09c91c 100644 --- a/website/docs/d/kubernetes_cluster_node_pool.html.markdown +++ b/website/docs/d/kubernetes_cluster_node_pool.html.markdown @@ -46,6 +46,10 @@ In addition to the Arguments listed above - the following Attributes are exporte * `eviction_policy` - The eviction policy used for Virtual Machines in the Virtual Machine Scale Set, when `priority` is set to `Spot`. +* `host_group_id` - The ID of a Dedicated Host Group that this Node Pool should be run on. Changing this forces a new resource to be created. + +-> **Note:** This requires that the Preview Feature `Microsoft.ContainerService/DedicatedHostGroupPreview` is enabled and the Resource Provider is re-registered, see [the documentation](https://docs.microsoft.com/en-us/azure/aks/use-azure-dedicated-hosts#register-the-dedicatedhostgrouppreview-preview-feature) for more information. + * `max_count` - The maximum number of Nodes allowed when auto-scaling is enabled. * `max_pods` - The maximum number of Pods allowed on each Node in this Node Pool. diff --git a/website/docs/d/lb_backend_address_pool.html.markdown b/website/docs/d/lb_backend_address_pool.html.markdown index 5c62c2b1db7f..3c17aa6ea252 100644 --- a/website/docs/d/lb_backend_address_pool.html.markdown +++ b/website/docs/d/lb_backend_address_pool.html.markdown @@ -53,6 +53,8 @@ The following attributes are exported: * `load_balancing_rules` - A list of the Load Balancing Rules associated with this Backend Address Pool. +* `inbound_nat_rules` - A list of the Load Balancing Inbound NAT Rules associated with this Backend Address Pool. + * `outbound_rules` - A list of the Load Balancing Outbound Rules associated with this Backend Address Pool. --- @@ -65,6 +67,18 @@ A `backend_address` block exports the following: * `ip_address` - The Static IP address for this Load Balancer within the Virtual Network. +* `inbound_nat_rule_port_mapping` - A list of `inbound_nat_rule_port_mapping` block as defined below. + +--- + +A `inbound_nat_rule_port_mapping` block exports the following: + +* `inbound_nat_rule_name` - The name of the Load Balancing Inbound NAT Rules associated with this Backend Address Pool Address. + +* `frontend_port` - The Frontend Port of the Load Balancing Inbound NAT Rules associated with this Backend Address Pool Address. + +* `backend_port` - The Backend Port of the Load Balancing Inbound NAT Rules associated with this Backend Address Pool Address. + ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: diff --git a/website/docs/d/public_maintenance_configurations.html.markdown b/website/docs/d/public_maintenance_configurations.html.markdown new file mode 100644 index 000000000000..71e4d6c556a4 --- /dev/null +++ b/website/docs/d/public_maintenance_configurations.html.markdown @@ -0,0 +1,65 @@ +--- +subcategory: "Maintenance" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_public_maintenance_configurations" +description: |- + Get information about existing Public Maintenance Configurations. +--- + +# Data Source: azurerm_public_maintenance_configurations + +Use this data source to access information about existing Public Maintenance Configurations. + +## Example Usage + +```hcl +data "azurerm_public_maintenance_configurations" "existing" { + location = "West Europe" + scope = "SQLManagedInstance" + recur_every = "Monday-Thursday" +} + +output "name" { + value = data.azurerm_public_maintenance_configurations.existing.configs[0].name +} +``` + +## Argument Reference + +* `location` - The Azure location to filter the list of Public Maintenance Configurations against. + +* `scope` - The scope to filter the list of Public Maintenance Configurations against. Possible values are `All`, `Extension`, `Host`, `InGuestPatch`, `OSImage`, `SQLDB` and `SQLManagedInstance`. + +* `recur_every` - The recurring window to filter the list of Public Maintenance Configurations against. Possible values are `Monday-Thursday` and `Friday-Sunday` + +## Attributes Reference + +* `configs` - A `configs` block as defined below. + +--- + +A `configs` block exports the following: + +* `name` - The name of the Public Maintenance Configuration. + +* `id` - The id of the Public Maintenance Configuration. + +* `location` - The Azure location of the Public Maintenance Configuration. + +* `description` - A description of the Public Maintenance Configuration. + +* `duration` - The duration of the Public Maintenance Configuration window. + +* `maintenance_scope` - The scope of the Public Maintenance Configuration. + +* `time_zone` - The time zone for the maintenance window. + +* `recur_every` - The rate at which a maintenance window is expected to recur. + +--- + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `read` - (Defaults to 5 minutes) Used when retrieving the Public Maintenance Configuration. diff --git a/website/docs/d/storage_management_policy.html.markdown b/website/docs/d/storage_management_policy.html.markdown index b71f0719d479..3a1909e4439b 100644 --- a/website/docs/d/storage_management_policy.html.markdown +++ b/website/docs/d/storage_management_policy.html.markdown @@ -19,7 +19,7 @@ data "azurerm_storage_account" "example" { } data "azurerm_storage_management_policy" "example" { - storage_account_id = azurerm_storage_account.example.id + storage_account_id = data.azurerm_storage_account.example.id } ``` @@ -50,6 +50,7 @@ The following arguments are supported: * `prefix_match` - An array of strings for prefixes to be matched. * `blob_types` - An array of predefined values. Valid options are `blockBlob` and `appendBlob`. * `match_blob_index_tag` - A `match_blob_index_tag` block as defined below. The block defines the blob index tag based filtering for blob objects. + --- `actions` supports the following: @@ -63,8 +64,11 @@ The following arguments are supported: `base_blob` supports the following: * `tier_to_cool_after_days_since_modification_greater_than` - The age in days after last modification to tier blobs to cool storage. Supports blob currently at Hot tier. +* `tier_to_cool_after_days_since_last_access_time_greater_than` - The age in days after last access time to tier blobs to cool storage. Supports blob currently at Hot tier. * `tier_to_archive_after_days_since_modification_greater_than` - The age in days after last modification to tier blobs to archive storage. Supports blob currently at Hot or Cool tier. +* `tier_to_archive_after_days_since_last_access_time_greater_than` - The age in days after last access time to tier blobs to archive storage. Supports blob currently at Hot or Cool tier. * `delete_after_days_since_modification_greater_than` - The age in days after last modification to delete the blob. +* `delete_after_days_since_last_access_time_greater_than` - The age in days after last access time to delete the blob. --- diff --git a/website/docs/r/app_service_certificate_order.html.markdown b/website/docs/r/app_service_certificate_order.html.markdown index 2a0fe80f441b..897ef10005cb 100644 --- a/website/docs/r/app_service_certificate_order.html.markdown +++ b/website/docs/r/app_service_certificate_order.html.markdown @@ -104,5 +104,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d App Service Certificate Orders can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_app_certificate_order.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.CertificateRegistration/certificateOrders/certificateorder1 +terraform import azurerm_app_service_certificate_order.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.CertificateRegistration/certificateOrders/certificateorder1 ``` diff --git a/website/docs/r/application_gateway.html.markdown b/website/docs/r/application_gateway.html.markdown index bf03c30c8dee..da6090f774ce 100644 --- a/website/docs/r/application_gateway.html.markdown +++ b/website/docs/r/application_gateway.html.markdown @@ -109,7 +109,6 @@ resource "azurerm_application_gateway" "network" { http_listener_name = local.listener_name backend_address_pool_name = local.backend_address_pool_name backend_http_settings_name = local.http_setting_name - priority = 10 } } ``` @@ -432,9 +431,9 @@ A `request_routing_rule` block supports the following: * `url_path_map_name` - (Optional) The Name of the URL Path Map which should be associated with this Routing Rule. -* `priority` - (Required) Rule evaluation order can be dictated by specifying an integer value from `1` to `20000` with `1` being the highest priority and `20000` being the lowest priority. +* `priority` - (Optional) Rule evaluation order can be dictated by specifying an integer value from `1` to `20000` with `1` being the highest priority and `20000` being the lowest priority. -~> **NOTE:** The `priority` field is mandatory with AzureRM release 3.6.0 and later. +-> **NOTE:** `priority` is required when `sku.0.tier` is set to `*_v2`. --- diff --git a/website/docs/r/application_insights_workbook_template.html.markdown b/website/docs/r/application_insights_workbook_template.html.markdown new file mode 100644 index 000000000000..c5482a97310e --- /dev/null +++ b/website/docs/r/application_insights_workbook_template.html.markdown @@ -0,0 +1,146 @@ +--- +subcategory: "Application Insights" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_application_insights_workbook_template" +description: |- + Manages an Application Insights Workbook Template. +--- + +# azurerm_application_insights_workbook_template + +Manages an Application Insights Workbook Template. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-resources" + location = "West Europe" +} + +resource "azurerm_application_insights_workbook_template" "example" { + name = "example-aiwt" + resource_group_name = azurerm_resource_group.example.name + location = "West Europe" + author = "test author" + priority = 1 + + galleries { + category = "workbook" + name = "test" + order = 100 + resource_type = "microsoft.insights/components" + type = "tsg" + } + + template_data = jsonencode({ + "version" : "Notebook/1.0", + "items" : [ + { + "type" : 1, + "content" : { + "json" : "## New workbook\n---\n\nWelcome to your new workbook." + }, + "name" : "text - 2" + } + ], + "styleSettings" : {}, + "$schema" : "https://github.com/Microsoft/Application-Insights-Workbooks/blob/master/schema/workbook.json" + }) + + localized = jsonencode({ + "ar" : [ + { + "galleries" : [ + { + "name" : "test", + "category" : "Failures", + "type" : "tsg", + "resourceType" : "microsoft.insights/components", + "order" : 100 + } + ], + "templateData" : { + "version" : "Notebook/1.0", + "items" : [ + { + "type" : 1, + "content" : { + "json" : "## New workbook\n---\n\nWelcome to your new workbook." + }, + "name" : "text - 2" + } + ], + "styleSettings" : {}, + "$schema" : "https://github.com/Microsoft/Application-Insights-Workbooks/blob/master/schema/workbook.json" + }, + } + ] + }) + + tags = { + key = "value" + } +} +``` + +## Arguments Reference + +The following arguments are supported: + +* `name` - (Required) Specifies the name which should be used for this Application Insights Workbook Template. Changing this forces a new Application Insights Workbook Template to be created. + +* `resource_group_name` - (Required) Specifies the name of the Resource Group where the Application Insights Workbook Template should exist. Changing this forces a new Application Insights Workbook Template to be created. + +* `galleries` - (Required) A `galleries` block as defined below. + +* `location` - (Required) Specifies the Azure Region where the Application Insights Workbook Template should exist. Changing this forces a new Application Insights Workbook Template to be created. + +* `template_data` - (Required) Valid JSON object containing workbook template payload. + +* `author` - (Optional) Information about the author of the workbook template. + +* `localized` - (Optional) Key value pairs of localized gallery. Each key is the locale code of languages supported by the Azure portal. + +* `priority` - (Optional) Priority of the template. Determines which template to open when a workbook gallery is opened in viewer mode. Defaults to `0`. + +* `tags` - (Optional) A mapping of tags which should be assigned to the Application Insights Workbook Template. + +--- + +A `galleries` block supports the following: + +* `name` - (Required) Name of the workbook template in the gallery. + +* `category` - (Required) Category for the gallery. + +* `order` - (Optional) Order of the template within the gallery. Defaults to `0`. + +* `resource_type` - (Optional) Azure resource type supported by the gallery. Defaults to `Azure Monitor`. + +* `type` - (Optional) Type of workbook supported by the workbook template. Defaults to `workbook`. + +~> **Note:** See [documentation](https://docs.microsoft.com/en-us/azure/azure-monitor/visualize/workbooks-automate#galleries) for more information of `resource_type` and `type`. + +## Attributes Reference + +In addition to the Arguments listed above - the following Attributes are exported: + +* `id` - The ID of the Application Insights Workbook Template. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Application Insights Workbook Template. +* `read` - (Defaults to 5 minutes) Used when retrieving the Application Insights Workbook Template. +* `update` - (Defaults to 30 minutes) Used when updating the Application Insights Workbook Template. +* `delete` - (Defaults to 30 minutes) Used when deleting the Application Insights Workbook Template. + +## Import + +Application Insights Workbook Template can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_application_insights_workbook_template.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resourceGroup1/providers/Microsoft.Insights/workbooktemplates/resource1 +``` diff --git a/website/docs/r/cdn_frontdoor_endpoint.html.markdown b/website/docs/r/cdn_frontdoor_endpoint.html.markdown index 7fc630fb7221..51ed09ea7353 100644 --- a/website/docs/r/cdn_frontdoor_endpoint.html.markdown +++ b/website/docs/r/cdn_frontdoor_endpoint.html.markdown @@ -21,6 +21,8 @@ resource "azurerm_resource_group" "example" { resource "azurerm_cdn_frontdoor_profile" "example" { name = "example-profile" resource_group_name = azurerm_resource_group.example.name + sku_name = "Standard_AzureFrontDoor" + } resource "azurerm_cdn_frontdoor_endpoint" "example" { diff --git a/website/docs/r/cdn_frontdoor_rule_set.html.markdown b/website/docs/r/cdn_frontdoor_rule_set.html.markdown index 31d51f44d9dc..31550b81ae6c 100644 --- a/website/docs/r/cdn_frontdoor_rule_set.html.markdown +++ b/website/docs/r/cdn_frontdoor_rule_set.html.markdown @@ -21,10 +21,12 @@ resource "azurerm_resource_group" "example" { resource "azurerm_cdn_frontdoor_profile" "example" { name = "example-profile" resource_group_name = azurerm_resource_group.example.name + sku_name = "Standard_AzureFrontDoor" + } resource "azurerm_cdn_frontdoor_rule_set" "example" { - name = "example-rule-set" + name = "ExampleRuleSet" cdn_frontdoor_profile_id = azurerm_cdn_frontdoor_profile.example.id } ``` diff --git a/website/docs/r/cognitive_account.html.markdown b/website/docs/r/cognitive_account.html.markdown index aaeda7dea976..577c4c0000d8 100644 --- a/website/docs/r/cognitive_account.html.markdown +++ b/website/docs/r/cognitive_account.html.markdown @@ -44,7 +44,7 @@ The following arguments are supported: * `location` - (Required) Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. -* `kind` - (Required) Specifies the type of Cognitive Service Account that should be created. Possible values are `Academic`, `AnomalyDetector`, `Bing.Autosuggest`, `Bing.Autosuggest.v7`, `Bing.CustomSearch`, `Bing.Search`, `Bing.Search.v7`, `Bing.Speech`, `Bing.SpellCheck`, `Bing.SpellCheck.v7`, `CognitiveServices`, `ComputerVision`, `ContentModerator`, `CustomSpeech`, `CustomVision.Prediction`, `CustomVision.Training`, `Emotion`, `Face`,`FormRecognizer`, `ImmersiveReader`, `LUIS`, `LUIS.Authoring`, `MetricsAdvisor`, `Personalizer`, `QnAMaker`, `Recommendations`, `SpeakerRecognition`, `Speech`, `SpeechServices`, `SpeechTranslation`, `TextAnalytics`, `TextTranslation` and `WebLM`. Changing this forces a new resource to be created. +* `kind` - (Required) Specifies the type of Cognitive Service Account that should be created. Possible values are `Academic`, `AnomalyDetector`, `Bing.Autosuggest`, `Bing.Autosuggest.v7`, `Bing.CustomSearch`, `Bing.Search`, `Bing.Search.v7`, `Bing.Speech`, `Bing.SpellCheck`, `Bing.SpellCheck.v7`, `CognitiveServices`, `ComputerVision`, `ContentModerator`, `CustomSpeech`, `CustomVision.Prediction`, `CustomVision.Training`, `Emotion`, `Face`,`FormRecognizer`, `ImmersiveReader`, `LUIS`, `LUIS.Authoring`, `MetricsAdvisor`, `Personalizer`, `QnAMaker`, `Recommendations`, `SpeakerRecognition`, `Speech`, `SpeechServices`, `SpeechTranslation`, `TextAnalytics`(Language service), `TextTranslation` and `WebLM`. Changing this forces a new resource to be created. -> **NOTE:** You must create your first Face, Text Analytics, or Computer Vision resources from the Azure portal to review and acknowledge the terms and conditions. In Azure Portal, the checkbox to accept terms and conditions is only displayed when a US region is selected. More information on [Prerequisites](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account-cli?tabs=windows#prerequisites). diff --git a/website/docs/r/container_group.html.markdown b/website/docs/r/container_group.html.markdown index 90336b4fcec8..c6c3821186a3 100644 --- a/website/docs/r/container_group.html.markdown +++ b/website/docs/r/container_group.html.markdown @@ -308,6 +308,8 @@ The `http_get` block supports: * `scheme` - (Optional) Scheme to use for connecting to the host. Possible values are `Http` and `Https`. Changing this forces a new resource to be created. +* `http_headers` - (Optional) A map of HTTP headers used to access on the container. Changing this forces a new resource to be created. + --- The `dns_config` block supports: diff --git a/website/docs/r/cosmosdb_cassandra_datacenter.html.markdown b/website/docs/r/cosmosdb_cassandra_datacenter.html.markdown index 1c975782d5a3..a89f0bd2a14d 100644 --- a/website/docs/r/cosmosdb_cassandra_datacenter.html.markdown +++ b/website/docs/r/cosmosdb_cassandra_datacenter.html.markdown @@ -90,6 +90,14 @@ The following arguments are supported: --- +* `backup_storage_customer_key_uri` - (Optional) The key URI of the customer key to use for the encryption of the backup Storage Account. + +* `base64_encoded_yaml_fragment` - (Optional) The fragment of the cassandra.yaml configuration file to be included in the cassandra.yaml for all nodes in this Cassandra Datacenter. The fragment should be Base64 encoded and only a subset of keys is allowed. + +* `disk_sku` - (Optional) The Disk SKU that is used for this Cassandra Datacenter. Defaults to `P30`. + +* `managed_disk_customer_key_uri` - (Optional) The key URI of the customer key to use for the encryption of the Managed Disk. + * `sku_name` - (Optional) Determines the selected sku. Defaults to Standard_DS14_v2. * `disk_count` - (Optional) Determines the number of p30 disks that are attached to each node. Defaults to `4`. @@ -106,10 +114,10 @@ In addition to the Arguments listed above - the following Attributes are exporte The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: -* `create` - (Defaults to 30 minutes) Used when creating the Cassandra Datacenter. +* `create` - (Defaults to 60 minutes) Used when creating the Cassandra Datacenter. * `read` - (Defaults to 5 minutes) Used when retrieving the Cassandra Datacenter. -* `update` - (Defaults to 30 minutes) Used when updating the Cassandra Datacenter. -* `delete` - (Defaults to 30 minutes) Used when deleting the Cassandra Datacenter. +* `update` - (Defaults to 60 minutes) Used when updating the Cassandra Datacenter. +* `delete` - (Defaults to 60 minutes) Used when deleting the Cassandra Datacenter. ## Import diff --git a/website/docs/r/data_factory_trigger_schedule.html.markdown b/website/docs/r/data_factory_trigger_schedule.html.markdown index f76f77be7c1a..6cbd9e0d6668 100644 --- a/website/docs/r/data_factory_trigger_schedule.html.markdown +++ b/website/docs/r/data_factory_trigger_schedule.html.markdown @@ -121,5 +121,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d Data Factory Schedule Trigger can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_data_factory_schedule_trigger.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.DataFactory/factories/example/triggers/example +terraform import azurerm_data_factory_trigger_schedule.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.DataFactory/factories/example/triggers/example ``` diff --git a/website/docs/r/databox_edge_order.html.markdown b/website/docs/r/databox_edge_order.html.markdown index f6faac241031..c599b51bc83e 100644 --- a/website/docs/r/databox_edge_order.html.markdown +++ b/website/docs/r/databox_edge_order.html.markdown @@ -163,5 +163,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d Databox Edge Orders can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_databoxedge_order.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/device1/orders/default +terraform import azurerm_databox_edge_order.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/device1/orders/default ``` diff --git a/website/docs/r/databricks_workspace_customer_managed_key.html.markdown b/website/docs/r/databricks_workspace_customer_managed_key.html.markdown index 77dbb9bfc10b..6bc99e9d6664 100644 --- a/website/docs/r/databricks_workspace_customer_managed_key.html.markdown +++ b/website/docs/r/databricks_workspace_customer_managed_key.html.markdown @@ -117,7 +117,7 @@ resource "azurerm_key_vault_access_policy" "databricks" { The following arguments are supported: -* `workspace_id` - (Required) The ID of the Databricks workspace. +* `workspace_id` - (Required) The ID of the Databricks Workspace.. * `key_vault_key_id` - (Required) The ID of the Key Vault. @@ -126,22 +126,22 @@ The following arguments are supported: The following attributes are exported: -* `id` - The ID of the Databricks Customer Managed Key. +* `id` - The ID of the Databricks Workspace. ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: -* `create` - (Defaults to 30 minutes) Used when creating the Databricks Customer Managed Key. -* `update` - (Defaults to 30 minutes) Used when updating the Databricks Customer Managed Key. -* `read` - (Defaults to 5 minutes) Used when retrieving the Databricks Customer Managed Key. -* `delete` - (Defaults to 30 minutes) Used when deleting the Databricks Customer Managed Key. +* `create` - (Defaults to 30 minutes) Used when creating the Customer Managed Key for this Databricks Workspace. +* `update` - (Defaults to 30 minutes) Used when updating the Customer Managed Key for this Databricks Workspace. +* `read` - (Defaults to 5 minutes) Used when retrieving the Customer Managed Key for this Databricks Workspace. +* `delete` - (Defaults to 30 minutes) Used when deleting the Customer Managed Key for this Databricks Workspace. ## Import Databricks Workspace Customer Managed Key can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_databricks_workspace_customer_managed_key.workspace1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Databricks/customerManagedKey/workspace1 +terraform import azurerm_databricks_workspace_customer_managed_key.workspace1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Databricks/workspaces/workspace1 ``` diff --git a/website/docs/r/fluid_relay_servers.html.markdown b/website/docs/r/fluid_relay_servers.html.markdown new file mode 100644 index 000000000000..ab147a9de8e5 --- /dev/null +++ b/website/docs/r/fluid_relay_servers.html.markdown @@ -0,0 +1,91 @@ +--- +subcategory: "Fluid Relay" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_fluid_relay_server" +description: |- + Manages a Fluid Relay Server. +--- + +# azurerm_fluid_relay_server + +Manages a Fluid Relay Server. + +## Example Usage + +```hcl +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "example" { + name = "example-resources" + location = "West Europe" +} + +resource "azurerm_fluid_relay_server" "example" { + name = "example" + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location +} +``` + +## Arguments Reference + +The following arguments are supported: + +* `location` - (Required) The Azure Region where the Fluid Relay Server should exist. Changing this forces a new Fluid Relay Server to be created. + +* `name` - (Required) The name which should be used for this Fluid Relay Server. Changing this forces a new Fluid Relay Server to be created. + +* `resource_group_name` - (Required) The name of the Resource Group where the Fluid Relay Server should exist. Changing this forces a new Fluid Relay Server to be created. + +* `tags` - (Optional) A mapping of tags which should be assigned to the Fluid Relay Server. + +* `identity` - (Optional) An `identity` block as defined below. + +* `storage_sku` - (Optional) Sku of the storage associated with the resource, Possible values are `standard` and `basic`. Changing this forces a new Fluid Relay Server to be created. + +--- + +An `identity` block supports the following: + +* `type` - (Required) Specifies the type of Managed Service Identity that should be configured on this Fluid Relay Service. Possible values are `SystemAssigned`,`UserAssigned` and `SystemAssigned, UserAssigned`. + +* `identity_ids` - (Optional) Specifies a list of User Assigned Managed Identity IDs to be assigned to this Fluid Relay Service. + +## Attributes Reference + +In addition to the Arguments listed above - the following Attributes are exported: + +* `id` - The ID of the Fluid Relay Server. + +* `frs_tenant_id` - The Fluid tenantId for this server. + +* `orderer_endpoints` - An array of the Fluid Relay Orderer endpoints. + +* `storage_endpoints` - An array of storage endpoints for this Fluid Relay Server. + +--- + +`identity` exports the following: + +* `principal_id` - The Principal ID for the Service Principal associated with the Identity of this Fluid Relay Server. + +* `tenant_id` - The Tenant ID for the Service Principal associated with the Identity of this Fluid Relay Server. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Fluid Relay Server. +* `read` - (Defaults to 5 minutes) Used when retrieving the Fluid Relay Server. +* `update` - (Defaults to 10 minutes) Used when updating the Fluid Relay Server. +* `delete` - (Defaults to 10 minutes) Used when deleting the Fluid Relay Server. + +## Import + +Fluid Relay Servers can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_fluid_relay_server.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.FluidRelay/fluidRelayServers/server1 +``` diff --git a/website/docs/r/gallery_application.html.markdown b/website/docs/r/gallery_application.html.markdown new file mode 100644 index 000000000000..17452748dd32 --- /dev/null +++ b/website/docs/r/gallery_application.html.markdown @@ -0,0 +1,82 @@ +--- +subcategory: "Compute" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_gallery_application" +description: |- + Manages a Gallery Application. +--- + +# azurerm_gallery_application + +Manages a Gallery Application. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-rg" + location = "West Europe" +} + +resource "azurerm_shared_image_gallery" "example" { + name = "example-gallery" + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location +} + +resource "azurerm_gallery_application" "example" { + name = "example-app" + gallery_id = azurerm_shared_image_gallery.example.id + location = azurerm_resource_group.example.location + supported_os_type = "Linux" +} +``` + +## Arguments Reference + +The following arguments are supported: + +* `name` - (Required) The name of the Gallery Application. Changing this forces a new resource to be created. + +* `gallery_id` - (Required) The ID of the Shared Image Gallery. Changing this forces a new resource to be created. + +* `location` - (Required) The Azure Region where the Gallery Application exists. Changing this forces a new resource to be created. + +* `supported_os_type` - (Required) The type of the Operating System supported for the Gallery Application. Possible values are `Linux` and `Windows`. Changing this forces a new resource to be created. + +--- + +* `description` - (Optional) A description of the Gallery Application. + +* `end_of_life_date` - (Optional) The end of life date in RFC3339 format of the Gallery Application. + +* `eula` - (Optional) The End User Licence Agreement of the Gallery Application. + +* `privacy_statement_uri` - (Optional) The URI containing the Privacy Statement associated with the Gallery Application. + +* `release_note_uri` - (Optional) The URI containing the Release Notes associated with the Gallery Application. + +* `tags` - (Optional) A mapping of tags to assign to the Gallery Application. + +## Attributes Reference + +In addition to the Arguments listed above - the following Attributes are exported: + +* `id` - The ID of the Gallery Application. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Gallery Application. +* `read` - (Defaults to 5 minutes) Used when retrieving the Gallery Application. +* `update` - (Defaults to 30 minutes) Used when updating the Gallery Application. +* `delete` - (Defaults to 30 minutes) Used when deleting the Gallery Application. + +## Import + +Gallery Applications can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_gallery_application.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1 +``` diff --git a/website/docs/r/gallery_application_version.html.markdown b/website/docs/r/gallery_application_version.html.markdown new file mode 100644 index 000000000000..cf9a4050d067 --- /dev/null +++ b/website/docs/r/gallery_application_version.html.markdown @@ -0,0 +1,152 @@ +--- +subcategory: "Compute" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_gallery_application_version" +description: |- + Manages a Gallery Application Version. +--- + +# azurerm_gallery_application_version + +Manages a Gallery Application Version. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-rg" + location = "West Europe" +} + +resource "azurerm_shared_image_gallery" "example" { + name = "example-gallery" + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location +} + +resource "azurerm_gallery_application" "example" { + name = "example-app" + gallery_id = azurerm_shared_image_gallery.example.id + location = azurerm_resource_group.example.location + supported_os_type = "Linux" +} + +resource "azurerm_storage_account" "example" { + name = "example-storage" + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_storage_container" "example" { + name = "example-container" + storage_account_name = azurerm_storage_account.example.name + container_access_type = "blob" +} + +resource "azurerm_storage_blob" "example" { + name = "scripts" + storage_account_name = azurerm_storage_account.example.name + storage_container_name = azurerm_storage_container.example.name + type = "Block" + source_content = "[scripts file content]" +} + +resource "azurerm_gallery_application_version" "example" { + name = "0.0.1" + gallery_application_id = azurerm_gallery_application.example.id + location = azurerm_gallery_application.example.location + + manage_action { + install = "[install command]" + remove = "[remove command]" + } + + source { + media_link = azurerm_storage_blob.example.id + } + + target_region { + name = azurerm_gallery_application.example.location + regional_replica_count = 1 + } +} +``` + +## Arguments Reference + +The following arguments are supported: + +* `name` - (Required) The version name of the Gallery Application Version, such as `1.0.0`. Changing this forces a new resource to be created. + +* `gallery_application_id` - (Required) The ID of the Gallery Application. Changing this forces a new resource to be created. + +* `location` - (Required) The Azure Region where the Gallery Application Version exists. Changing this forces a new resource to be created. + +* `manage_action` - (Required) A `manage_action` block as defined below. + +* `source` - (Required) A `source` block as defined below. + +* `target_region` - (Required) One or more `target_region` blocks as defined below. + +--- + +* `enable_health_check` - (Optional) Should the Gallery Application reports health. Defaults to `false`. + +* `end_of_life_date` - (Optional) The end of life date in RFC3339 format of the Gallery Application Version. + +* `exclude_from_latest` - (Optional) Should the Gallery Application Version be excluded from the `latest` filter? If set to `true` this Gallery Application Version won't be returned for the `latest` version. Defaults to `false`. + +* `tags` - (Optional) A mapping of tags to assign to the Gallery Application Version. + +--- + +A `manage_action` block supports the following: + +* `install` - (Required) The command to install the Gallery Application. Changing this forces a new resource to be created. + +* `remove` - (Required) The command to remove the Gallery Application. Changing this forces a new resource to be created. + +* `update` - (Optional) The command to update the Gallery Application. Changing this forces a new resource to be created. + +--- + +A `source` block supports the following: + +* `media_link` - (Required) The Storage Blob URI of the source application package. Changing this forces a new resource to be created. + +* `default_configuration_link` - (Optional) The Storage Blob URI of the default configuration. Changing this forces a new resource to be created. + +--- + +A `target_region` block supports the following: + +* `name` - (Required) The Azure Region in which the Gallery Application Version exists. + +* `regional_replica_count` - (Required) The number of replicas of the Gallery Application Version to be created per region. Possible values are between `1` and `10`. + +* `storage_account_type` - (Optional) The storage account type for the Gallery Application Version. Possible values are `Standard_LRS`, `Premium_LRS` and `Standard_ZRS`. Defaults to `Standard_LRS`. + +## Attributes Reference + +In addition to the Arguments listed above - the following Attributes are exported: + +* `id` - The ID of the Gallery Application Version. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Gallery Application Version. +* `read` - (Defaults to 5 minutes) Used when retrieving the Gallery Application Version. +* `update` - (Defaults to 30 minutes) Used when updating the Gallery Application Version. +* `delete` - (Defaults to 30 minutes) Used when deleting the Gallery Application Version. + +## Import + +Gallery Application Versions can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_gallery_application_version.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Compute/galleries/gallery1/applications/galleryApplication1/versions/galleryApplicationVersion1 +``` diff --git a/website/docs/r/hdinsight_kafka_cluster.html.markdown b/website/docs/r/hdinsight_kafka_cluster.html.markdown index 6a6bce3c7d0b..803a11462b91 100644 --- a/website/docs/r/hdinsight_kafka_cluster.html.markdown +++ b/website/docs/r/hdinsight_kafka_cluster.html.markdown @@ -96,6 +96,8 @@ The following arguments are supported: * `roles` - (Required) A `roles` block as defined below. +* `network` - (Optional) A `network` block as defined below. + * `storage_account` - (Required) One or more `storage_account` block as defined below. * `storage_account_gen2` - (Required) A `storage_account_gen2` block as defined below. @@ -170,6 +172,16 @@ A `roles` block supports the following: --- +A `network` block supports the following: + +* `connection_direction` - (Optional) The direction of the resource provider connection. Possible values include `Inbound` or `Outbound`. Defaults to `Inbound`. Changing this forces a new resource to be created. + +-> **NOTE:** To enabled the private link the `connection_direction` must be set to `Outbound`. + +* `private_link_enabled` - (Optional) Is the private link enabled? Possible values include `True` or `False`. Defaults to `False`. Changing this forces a new resource to be created. + +--- + A `storage_account` block supports the following: * `is_default` - (Required) Is this the Default Storage Account for the HDInsight Hadoop Cluster? Changing this forces a new resource to be created. diff --git a/website/docs/r/iot_time_series_insights_access_policy.html.markdown b/website/docs/r/iot_time_series_insights_access_policy.html.markdown index b223ace470ed..33be0c142f67 100644 --- a/website/docs/r/iot_time_series_insights_access_policy.html.markdown +++ b/website/docs/r/iot_time_series_insights_access_policy.html.markdown @@ -69,5 +69,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d Azure IoT Time Series Insights Access Policy can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_iot_time_series_access_policy.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.TimeSeriesInsights/environments/environment1/accessPolicies/example +terraform import azurerm_iot_time_series_insights_access_policy.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.TimeSeriesInsights/environments/environment1/accessPolicies/example ``` diff --git a/website/docs/r/iot_time_series_insights_standard_environment.html.markdown b/website/docs/r/iot_time_series_insights_standard_environment.html.markdown index 6685979844ed..a09e8e26d57c 100644 --- a/website/docs/r/iot_time_series_insights_standard_environment.html.markdown +++ b/website/docs/r/iot_time_series_insights_standard_environment.html.markdown @@ -66,5 +66,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d Azure IoT Time Series Insights Standard Environment can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_iot_time_series_environment.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.TimeSeriesInsights/environments/example +terraform import azurerm_iot_time_series_insights_standard_environment.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.TimeSeriesInsights/environments/example ``` diff --git a/website/docs/r/kubernetes_cluster.html.markdown b/website/docs/r/kubernetes_cluster.html.markdown index 7474fedd8af6..34ce0827334e 100644 --- a/website/docs/r/kubernetes_cluster.html.markdown +++ b/website/docs/r/kubernetes_cluster.html.markdown @@ -312,6 +312,8 @@ A `default_node_pool` block supports the following: * `vm_size` - (Required) The size of the Virtual Machine, such as `Standard_DS2_v2`. Changing this forces a new resource to be created. +* `capacity_reservation_group_id` - (Optional) Specifies the ID of the Capacity Reservation Group within which this AKS Cluster should be created. Changing this forces a new resource to be created. + * `enable_auto_scaling` - (Optional) Should [the Kubernetes Auto Scaler](https://docs.microsoft.com/azure/aks/cluster-autoscaler) be enabled for this Node Pool? Defaults to `false`. -> **Note:** This requires that the `type` is set to `VirtualMachineScaleSets`. @@ -352,8 +354,6 @@ A `default_node_pool` block supports the following: * `pod_subnet_id` - (Optional) The ID of the Subnet where the pods in the default Node Pool should exist. Changing this forces a new resource to be created. --> **Note:** This requires that the Preview Feature `Microsoft.ContainerService/PodSubnetPreview` is enabled and the Resource Provider is re-registered, see [the documentation](https://docs.microsoft.com/azure/aks/configure-azure-cni#register-the-podsubnetpreview-preview-feature) for more information. - * `type` - (Optional) The type of Node Pool which should be created. Possible values are `AvailabilitySet` and `VirtualMachineScaleSets`. Defaults to `VirtualMachineScaleSets`. * `tags` - (Optional) A mapping of tags to assign to the Node Pool. diff --git a/website/docs/r/kubernetes_cluster_node_pool.html.markdown b/website/docs/r/kubernetes_cluster_node_pool.html.markdown index edb75ddc7175..75c0defc7b94 100644 --- a/website/docs/r/kubernetes_cluster_node_pool.html.markdown +++ b/website/docs/r/kubernetes_cluster_node_pool.html.markdown @@ -71,6 +71,8 @@ The following arguments are supported: --- +* `capacity_reservation_group_id` - (Optional) Specifies the ID of the Capacity Reservation Group where this Node Pool should exist. Changing this forces a new resource to be created. + * `enable_auto_scaling` - (Optional) Whether to enable [auto-scaler](https://docs.microsoft.com/azure/aks/cluster-autoscaler). Defaults to `false`. * `enable_host_encryption` - (Optional) Should the nodes in this Node Pool have host encryption enabled? Defaults to `false`. @@ -113,8 +115,6 @@ The following arguments are supported: * `pod_subnet_id` - (Optional) The ID of the Subnet where the pods in the Node Pool should exist. Changing this forces a new resource to be created. --> **NOTE:** This requires that the Preview Feature `Microsoft.ContainerService/PodSubnetPreview` is enabled and the Resource Provider is re-registered, see [the documentation](https://docs.microsoft.com/azure/aks/configure-azure-cni#register-the-podsubnetpreview-preview-feature) for more information. - * `os_sku` - (Optional) OsSKU to be used to specify Linux OSType. Not applicable to Windows OSType. Possible values include: `Ubuntu`, `CBLMariner`. Defaults to `Ubuntu`. Changing this forces a new resource to be created. * `os_type` - (Optional) The Operating System which should be used for this Node Pool. Changing this forces a new resource to be created. Possible values are `Linux` and `Windows`. Defaults to `Linux`. diff --git a/website/docs/r/kusto_cluster.html.markdown b/website/docs/r/kusto_cluster.html.markdown index 5a988a4a9501..a9de1e98fd0a 100644 --- a/website/docs/r/kusto_cluster.html.markdown +++ b/website/docs/r/kusto_cluster.html.markdown @@ -56,6 +56,8 @@ The following arguments are supported: * `streaming_ingestion_enabled` - (Optional) Specifies if the streaming ingest is enabled. +* `public_ip_type` - (Optional) Indicates what public IP type to create - IPv4 (default), or DualStack (both IPv4 and IPv6). + * `public_network_access_enabled` - (Optional) Is the public network access enabled? Defaults to `true`. * `purge_enabled` - (Optional) Specifies if the purge operations are enabled. diff --git a/website/docs/r/kusto_eventgrid_data_connection.html.markdown b/website/docs/r/kusto_eventgrid_data_connection.html.markdown index 862b679ef574..1ba049cfc72d 100644 --- a/website/docs/r/kusto_eventgrid_data_connection.html.markdown +++ b/website/docs/r/kusto_eventgrid_data_connection.html.markdown @@ -124,7 +124,13 @@ The following arguments are supported: Values are `Microsoft.Storage.BlobCreated` and `Microsoft.Storage.BlobRenamed`. Defaults to `Microsoft.Storage.BlobCreated`. -* `data_format` - (Optional) Specifies the data format of the EventHub messages. Allowed values: `AVRO`, `CSV`, `JSON`, `MULTIJSON`, `PSV`, `RAW`, `SCSV`, `SINGLEJSON`, `SOHSV`, `TSV` and `TXT` +* `data_format` - (Optional) Specifies the data format of the EventHub messages. Allowed values: `AVRO`, `CSV`, `JSON`, `MULTIJSON`, `PSV`, `RAW`, `SCSV`, `SINGLEJSON`, `SOHSV`, `TSV` and `TXT`. + +* `database_routing_type` - (Optional) Indication for database routing information from the data connection, by default only database routing information is allowed. Allowed values: `Single`, `Multi`. + +* `eventgrid_resource_id` - (Optional) The resource ID of the event grid that is subscribed to the storage account events. + +* `managed_identity_resource_id` - (Optional) Empty for non-managed identity based data connection. For system assigned identity, provide cluster resource Id. For user assigned identity (UAI) provide the UAI resource Id. * `mapping_rule_name` - (Optional) Specifies the mapping rule used for the message ingestion. Mapping rule must exist before resource is created. diff --git a/website/docs/r/kusto_eventhub_data_connection.html.markdown b/website/docs/r/kusto_eventhub_data_connection.html.markdown index ceb27ff8beaf..95639418f896 100644 --- a/website/docs/r/kusto_eventhub_data_connection.html.markdown +++ b/website/docs/r/kusto_eventhub_data_connection.html.markdown @@ -92,7 +92,6 @@ The following arguments are supported: * `database_name` - (Required) Specifies the name of the Kusto Database this data connection will be added to. Changing this forces a new resource to be created. - * `eventhub_id` - (Required) Specifies the resource id of the EventHub this data connection will use for ingestion. Changing this forces a new resource to be created. * `event_system_properties` - (Optional) Specifies a list of system properties for the Event Hub. @@ -107,6 +106,8 @@ The following arguments are supported: * `data_format` - (Optional) Specifies the data format of the EventHub messages. Allowed values: `APACHEAVRO`, `AVRO`, `CSV`, `JSON`, `MULTIJSON`, `ORC`, `PARQUET`, `PSV`, `RAW`, `SCSV`, `SINGLEJSON`, `SOHSV`, `TSVE`, `TSV`, `TXT`, and `W3CLOGFILE`. +* `database_routing_type` - (Optional) Indication for database routing information from the data connection, by default only database routing information is allowed. Allowed values: `Single`, `Multi`. + ## Attributes Reference The following attributes are exported: diff --git a/website/docs/r/kusto_iothub_data_connection.html.markdown b/website/docs/r/kusto_iothub_data_connection.html.markdown index 1d1297f5815f..9ee882fd319d 100644 --- a/website/docs/r/kusto_iothub_data_connection.html.markdown +++ b/website/docs/r/kusto_iothub_data_connection.html.markdown @@ -110,6 +110,8 @@ The following arguments are supported: * `data_format` - (Optional) Specifies the data format of the IoTHub messages. Allowed values: `APACHEAVRO`, `AVRO`, `CSV`, `JSON`, `MULTIJSON`, `ORC`, `PARQUET`, `PSV`, `RAW`, `SCSV`, `SINGLEJSON`, `SOHSV`, `TSV`, `TSVE`, `TXT` and `W3CLOGFILE`. +* `database_routing_type` - (Optional) Indication for database routing information from the data connection, by default only database routing information is allowed. Allowed values: `Single`, `Multi`. + ## Attributes Reference The following attributes are exported: diff --git a/website/docs/r/kusto_script.html.markdown b/website/docs/r/kusto_script.html.markdown index 695a050fe09d..5dd1a00e2a34 100644 --- a/website/docs/r/kusto_script.html.markdown +++ b/website/docs/r/kusto_script.html.markdown @@ -98,16 +98,18 @@ The following arguments are supported: * `database_id` - (Required) The ID of the Kusto Database. Changing this forces a new Kusto Script to be created. -* `sas_token` - (Required) The SAS token used to access the script. - -* `url` - (Required) The url to the KQL script blob file. Please reference [this documentation](https://docs.microsoft.com/azure/data-explorer/database-script) that describes the commands that are allowed in the script. - --- * `continue_on_errors_enabled` - (Optional) Flag that indicates whether to continue if one of the command fails. * `force_an_update_when_value_changed` - (Optional) A unique string. If changed the script will be applied again. +* `script_content` - (Optional) The script content. This property should be used when the script is provide inline and not through file in a SA. Must not be used together with `url` and `sas_token` properties. + +* `sas_token` - (Optional) The SAS token used to access the script. Must be provided when using scriptUrl property. + +* `url` - (Optional) The url to the KQL script blob file. Must not be used together with scriptContent property. Please reference [this documentation](https://docs.microsoft.com/azure/data-explorer/database-script) that describes the commands that are allowed in the script. + ## Attributes Reference In addition to the Arguments listed above - the following Attributes are exported: diff --git a/website/docs/r/lb_backend_address_pool.html.markdown b/website/docs/r/lb_backend_address_pool.html.markdown index 95c26b798deb..36140e72930f 100644 --- a/website/docs/r/lb_backend_address_pool.html.markdown +++ b/website/docs/r/lb_backend_address_pool.html.markdown @@ -76,6 +76,8 @@ The following attributes are exported: * `load_balancing_rules` - The Load Balancing Rules associated with this Backend Address Pool. +* `inbound_nat_rules` - An array of the Load Balancing Inbound NAT Rules associated with this Backend Address Pool. + * `outbound_rules` - An array of the Load Balancing Outbound Rules associated with this Backend Address Pool. ## Timeouts diff --git a/website/docs/r/lb_backend_address_pool_address.html.markdown b/website/docs/r/lb_backend_address_pool_address.html.markdown index 399c07dab82c..9e44c4285cf5 100644 --- a/website/docs/r/lb_backend_address_pool_address.html.markdown +++ b/website/docs/r/lb_backend_address_pool_address.html.markdown @@ -58,6 +58,18 @@ In addition to the Arguments listed above - the following Attributes are exporte * `id` - The ID of the Backend Address Pool Address. +* `inbound_nat_rule_port_mapping` - A list of `inbound_nat_rule_port_mapping` block as defined below. + +--- + +A `inbound_nat_rule_port_mapping` block exports the following: + +* `inbound_nat_rule_name` - The name of the Load Balancing Inbound NAT Rules associated with this Backend Address Pool Address. + +* `frontend_port` - The Frontend Port of the Load Balancing Inbound NAT Rules associated with this Backend Address Pool Address. + +* `backend_port` - The Backend Port of the Load Balancing Inbound NAT Rules associated with this Backend Address Pool Address. + ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: diff --git a/website/docs/r/lb_nat_rule.html.markdown b/website/docs/r/lb_nat_rule.html.markdown index 670e0c086829..ef42570bca3d 100644 --- a/website/docs/r/lb_nat_rule.html.markdown +++ b/website/docs/r/lb_nat_rule.html.markdown @@ -40,6 +40,12 @@ resource "azurerm_lb" "example" { } } +resource "azurerm_lb_backend_address_pool" "example" { + resource_group_name = azurerm_resource_group.example.name + loadbalancer_id = azurerm_lb.example.id + name = "be" +} + resource "azurerm_lb_nat_rule" "example" { resource_group_name = azurerm_resource_group.example.name loadbalancer_id = azurerm_lb.example.id @@ -49,6 +55,18 @@ resource "azurerm_lb_nat_rule" "example" { backend_port = 3389 frontend_ip_configuration_name = "PublicIPAddress" } + +resource "azurerm_lb_nat_rule" "example1" { + resource_group_name = azurerm_resource_group.example.name + loadbalancer_id = azurerm_lb.example.id + name = "RDPAccess" + protocol = "Tcp" + frontend_port_start = 3000 + frontend_port_end = 3389 + backend_port = 3389 + backend_address_pool_id = azurerm_lb_backend_address_pool.example.id + frontend_ip_configuration_name = "PublicIPAddress" +} ``` ## Argument Reference @@ -60,8 +78,11 @@ The following arguments are supported: * `loadbalancer_id` - (Required) The ID of the Load Balancer in which to create the NAT Rule. * `frontend_ip_configuration_name` - (Required) The name of the frontend IP configuration exposing this rule. * `protocol` - (Required) The transport protocol for the external endpoint. Possible values are `Udp`, `Tcp` or `All`. -* `frontend_port` - (Required) The port for the external endpoint. Port numbers for each Rule must be unique within the Load Balancer. Possible values range between 0 and 65534, inclusive. -* `backend_port` - (Required) The port used for internal connections on the endpoint. Possible values range between 0 and 65535, inclusive. +* `frontend_port` - (Optional) The port for the external endpoint. Port numbers for each Rule must be unique within the Load Balancer. Possible values range between 1 and 65534, inclusive. +* `backend_port` - (Required) The port used for internal connections on the endpoint. Possible values range between 1 and 65535, inclusive. +* `frontend_port_start` - (Optional) The port range start for the external endpoint. This property is used together with BackendAddressPool and FrontendPortRangeEnd. Individual inbound NAT rule port mappings will be created for each backend address from BackendAddressPool. Acceptable values range from 1 to 65534, inclusive. +* `frontend_port_end` - (Optional) The port range end for the external endpoint. This property is used together with BackendAddressPool and FrontendPortRangeStart. Individual inbound NAT rule port mappings will be created for each backend address from BackendAddressPool. Acceptable values range from 1 to 65534, inclusive. +* `backend_address_pool_id` - (Optional) Specifies a reference to backendAddressPool resource. * `idle_timeout_in_minutes` - (Optional) Specifies the idle timeout in minutes for TCP connections. Valid values are between `4` and `30` minutes. Defaults to `4` minutes. * `enable_floating_ip` - (Optional) Are the Floating IPs enabled for this Load Balancer Rule? A "floating” IP is reassigned to a secondary server in case the primary server fails. Required to configure a SQL AlwaysOn Availability Group. Defaults to `false`. * `enable_tcp_reset` - (Optional) Is TCP Reset enabled for this Load Balancer Rule? Defaults to `false`. diff --git a/website/docs/r/linux_virtual_machine.html.markdown b/website/docs/r/linux_virtual_machine.html.markdown index ae07bfa0459c..979c8c2a3899 100644 --- a/website/docs/r/linux_virtual_machine.html.markdown +++ b/website/docs/r/linux_virtual_machine.html.markdown @@ -126,6 +126,10 @@ The following arguments are supported: * `boot_diagnostics` - (Optional) A `boot_diagnostics` block as defined below. +* `capacity_reservation_group_id` - (Optional) Specifies the ID of the Capacity Reservation Group which the Virtual Machine should be allocated to. + +~> **NOTE:** `capacity_reservation_group_id` cannot be used with `availability_set_id` or `proximity_placement_group_id` + * `computer_name` - (Optional) Specifies the Hostname which should be used for this Virtual Machine. If unspecified this defaults to the value for the `name` field. If the value of the `name` field is not a valid `computer_name`, then you must specify `computer_name`. Changing this forces a new resource to be created. * `custom_data` - (Optional) The Base64-Encoded Custom Data which should be used for this Virtual Machine. Changing this forces a new resource to be created. diff --git a/website/docs/r/linux_virtual_machine_scale_set.html.markdown b/website/docs/r/linux_virtual_machine_scale_set.html.markdown index 17f59e446e0f..8d93dde0352a 100644 --- a/website/docs/r/linux_virtual_machine_scale_set.html.markdown +++ b/website/docs/r/linux_virtual_machine_scale_set.html.markdown @@ -132,6 +132,12 @@ The following arguments are supported: * `boot_diagnostics` - (Optional) A `boot_diagnostics` block as defined below. +* `capacity_reservation_group_id` - (Optional) Specifies the ID of the Capacity Reservation Group which the Virtual Machine Scale Set should be allocated to. Changing this forces a new resource to be created. + +~> **NOTE:** `capacity_reservation_group_id` cannot be used with `proximity_placement_group_id` + +~> **NOTE:** `single_placement_group` must be set to `false` when `capacity_reservation_group_id` is specified + * `computer_name_prefix` - (Optional) The prefix which should be used for the name of the Virtual Machines in this Scale Set. If unspecified this defaults to the value for the `name` field. If the value of the `name` field is not a valid `computer_name_prefix`, then you must specify `computer_name_prefix`. * `custom_data` - (Optional) The Base64-Encoded Custom Data which should be used for this Virtual Machine Scale Set. @@ -306,7 +312,9 @@ A `data_disk` block supports the following: A `diff_disk_settings` block supports the following: -`option` - (Required) Specifies the Ephemeral Disk Settings for the OS Disk. At this time the only possible value is `Local`. Changing this forces a new resource to be created. +* `option` - (Required) Specifies the Ephemeral Disk Settings for the OS Disk. At this time the only possible value is `Local`. Changing this forces a new resource to be created. + +* `placement` - (Optional) Specifies where to store the Ephemeral Disk. Possible values are `CacheDisk` and `ResourceDisk`. Defaults to `CacheDisk`. Changing this forces a new resource to be created. --- diff --git a/website/docs/r/linux_web_app.html.markdown b/website/docs/r/linux_web_app.html.markdown index 9801fad160a1..814fee85d216 100644 --- a/website/docs/r/linux_web_app.html.markdown +++ b/website/docs/r/linux_web_app.html.markdown @@ -417,6 +417,8 @@ A `site_config` block supports the following: * `always_on` - (Optional) If this Linux Web App is Always On enabled. Defaults to `true`. +~> **NOTE:** `always_on` must be explicitly set to `false` when using `Free`, `F1`, `D1`, or `Shared` Service Plans. + * `api_management_config_id` - (Optional) The ID of the APIM configuration for this Linux Web App. * `app_command_line` - (Optional) The App command line to launch. diff --git a/website/docs/r/logz_sub_account.html.markdown b/website/docs/r/logz_sub_account.html.markdown new file mode 100644 index 000000000000..080fdf89dbb6 --- /dev/null +++ b/website/docs/r/logz_sub_account.html.markdown @@ -0,0 +1,104 @@ +--- +subcategory: "Logz" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_logz_sub_account" +description: |- + Manages a logz Sub Account. +--- + +# azurerm_logz_sub_account + +Manages a logz Sub Account. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-logz" + location = "West Europe" +} + +resource "azurerm_logz_monitor" "example" { + name = "example-monitor" + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + plan { + billing_cycle = "MONTHLY" + effective_date = "2022-06-06T00:00:00Z" + plan_id = "100gb14days" + usage_type = "COMMITTED" + } + + user { + email = "user@example.com" + first_name = "Example" + last_name = "User" + phone_number = "+12313803556" + } +} + +resource "azurerm_logz_sub_account" "example" { + name = "example-subaccount" + logz_monitor_id = azurerm_logz_monitor.example.id + + user { + email = azurerm_logz_monitor.example.user[0].email + first_name = azurerm_logz_monitor.example.user[0].first_name + last_name = azurerm_logz_monitor.example.user[0].last_name + phone_number = azurerm_logz_monitor.example.user[0].phone_number + } +} +``` + +## Arguments Reference + +The following arguments are supported: + +* `name` - (Required) The name which should be used for this logz Sub Account. Possible values must be between 1 and 32 characters in length and may contain only letters, numbers, hyphens and underscores. Changing this forces a new logz Sub Account to be created. + +* `logz_monitor_id` - (Required) The ID of the Logz Monitor. Changing this forces a new logz Sub Account to be created. + +* `user` - (Required) A `user` block as defined below. + +--- + +* `enabled` - (Optional) Whether the resource monitoring is enabled? Defaults to `true`. + +* `tags` - (Optional) A mapping of tags which should be assigned to the logz Sub Account. + +--- + +An `user` block exports the following: + +* `email` - (Required) Email of the user used by Logz for contacting them if needed. A valid email address consists of an email prefix and an email domain. The prefix and domain may contain only letters, numbers, underscores, periods and dashes. Changing this forces a new logz Sub Account to be created. + +~> **NOTE** If you use the Azure CLI to authenticate to Azure, the Email of your Azure account needs to be granted the admin permission in your Logz.io account. Otherwise, you may not be able to delete this resource. There is no such limitation for the Service Principal authentication. + +* `first_name` - (Required) First Name of the user. Possible values must be between 1 and 50 characters in length. Changing this forces a new logz Sub Account to be created. + +* `last_name` - (Required) Last Name of the user. Possible values must be between 1 and 50 characters in length. Changing this forces a new logz Sub Account to be created. + +* `phone_number` - (Required) Phone number of the user used by Logz for contacting them if needed. Possible values must be between 1 and 40 characters in length. Changing this forces a new logz Sub Account to be created. + +## Attributes Reference + +In addition to the Arguments listed above - the following Attributes are exported: + +* `id` - The ID of the logz Sub Account. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the logz Sub Account. +* `read` - (Defaults to 5 minutes) Used when retrieving the logz Sub Account. +* `update` - (Defaults to 30 minutes) Used when updating the logz Sub Account. +* `delete` - (Defaults to 30 minutes) Used when deleting the logz Sub Account. + +## Import + +logz SubAccounts can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_logz_sub_account.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Logz/monitors/monitor1/accounts/subAccount1 +``` diff --git a/website/docs/r/managed_disk.html.markdown b/website/docs/r/managed_disk.html.markdown index a5ee4086193c..a7a5d88da381 100644 --- a/website/docs/r/managed_disk.html.markdown +++ b/website/docs/r/managed_disk.html.markdown @@ -219,5 +219,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d Managed Disks can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_managed_disk.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/microsoft.compute/disks/manageddisk1 +terraform import azurerm_managed_disk.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Compute/disks/manageddisk1 ``` diff --git a/website/docs/r/management_group_policy_exemption.html.markdown b/website/docs/r/management_group_policy_exemption.html.markdown new file mode 100644 index 000000000000..7c17279d0e9b --- /dev/null +++ b/website/docs/r/management_group_policy_exemption.html.markdown @@ -0,0 +1,86 @@ +--- +subcategory: "Policy" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_management_group_policy_exemption" +description: |- + Manages a Management Group Policy Exemption. +--- + +# azurerm_management_group_policy_exemption + +Manages a Management Group Policy Exemption. + +## Example Usage + +```hcl +resource "azurerm_management_group" "example" { + display_name = "Example MgmtGroup" +} + +data "azurerm_policy_set_definition" "example" { + display_name = "Audit machines with insecure password security settings" +} + +resource "azurerm_management_group_policy_assignment" "example" { + name = "assignment1" + management_group_id = azurerm_management_group.example.id + policy_definition_id = data.azurerm_policy_set_definition.example.id + location = "westus" + + identity { + type = "SystemAssigned" + } +} + +resource "azurerm_management_group_policy_exemption" "example" { + name = "exemption1" + management_group_id = azurerm_management_group.example.id + policy_assignment_id = azurerm_management_group_policy_assignment.example.id + exemption_category = "Mitigated" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the Policy Exemption. Changing this forces a new resource to be created. + +* `management_group_id`- (Required) The Management Group ID where the Policy Exemption should be applied. Changing this forces a new resource to be created. + +* `exemption_category` - (Required) The category of this policy exemption. Possible values are `Waiver` and `Mitigated`. + +* `policy_assignment_id` - (Required) The ID of the Policy Assignment to be exempted at the specified Scope. + +* `description` - (Optional) A description to use for this Policy Exemption. + +* `display_name` - (Optional) A friendly display name to use for this Policy Exemption. + +* `expires_on` - (Optional) The expiration date and time in UTC ISO 8601 format of this policy exemption. + +* `policy_definition_reference_ids` - (Optional) The policy definition reference ID list when the associated policy assignment is an assignment of a policy set definition. + +* `metadata` - (Optional) The metadata for this policy exemption. This is a JSON string representing additional metadata that should be stored with the policy exemption. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The Policy Exemption id. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Policy Exemption. +* `update` - (Defaults to 30 minutes) Used when updating the Policy Exemption. +* `read` - (Defaults to 5 minutes) Used when retrieving the Policy Exemption. +* `delete` - (Defaults to 30 minutes) Used when deleting the Policy Exemption. + +## Import + +Policy Exemptions can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_management_group_policy_exemption.exemption1 /providers/Microsoft.Management/managementGroups/group1/providers/Microsoft.Authorization/policyExemptions/exemption1 +``` diff --git a/website/docs/r/management_group_policy_remediation.html.markdown b/website/docs/r/management_group_policy_remediation.html.markdown new file mode 100644 index 000000000000..69c5779859ad --- /dev/null +++ b/website/docs/r/management_group_policy_remediation.html.markdown @@ -0,0 +1,80 @@ +--- +subcategory: "Policy" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_management_group_policy_remediation" +description: |- + Manages an Azure Management Group Policy Remediation. +--- + +# azurerm_management_group_policy_remediation + +Manages an Azure Management Group Policy Remediation. + +## Example Usage + +```hcl +resource "azurerm_management_group" "example" { + display_name = "Example Management Group" +} + +data "azurerm_policy_definition" "example" { + display_name = "Allowed locations" +} + +resource "azurerm_management_group_policy_assignment" "example" { + name = "exampleAssignment" + management_group_id = azurerm_management_group.example.id + policy_definition_id = data.azurerm_policy_definition.example.id + parameters = jsonencode({ + "listOfAllowedLocations" = { + "value" = ["East US"] + } + }) +} + +resource "azurerm_management_group_policy_remediation" "example" { + name = "exampleRemediation" + management_group_id = azurerm_management_group.example.id + policy_assignment_id = azurerm_management_group_policy_assignment.example.id +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the Policy Remediation. Changing this forces a new resource to be created. + +* `management_group_id` - (Required) The Management Group ID at which the Policy Remediation should be applied. Changing this forces a new resource to be created. + +* `policy_assignment_id` - (Required) The ID of the Policy Assignment that should be remediated. + +* `policy_definition_id` - (Optional) The unique ID for the policy definition within the policy set definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. + +* `location_filters` - (Optional) A list of the resource locations that will be remediated. + +* `resource_discovery_mode` - (Optional) The way that resources to remediate are discovered. Possible values are `ExistingNonCompliant`, `ReEvaluateCompliance`. Defaults to `ExistingNonCompliant`. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The ID of the Policy Remediation. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Policy Remediation. +* `update` - (Defaults to 30 minutes) Used when updating the Policy Remediation. +* `read` - (Defaults to 5 minutes) Used when retrieving the Policy Remediation. +* `delete` - (Defaults to 30 minutes) Used when deleting the Policy Remediation. + + +## Import + +Policy Remediations can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_management_group_policy_remediation.example /providers/Microsoft.Management/managementGroups/my-mgmt-group-id/providers/Microsoft.PolicyInsights/remediations/remediation1 +``` diff --git a/website/docs/r/media_live_output.html.markdown b/website/docs/r/media_live_output.html.markdown index 92016c17fc5c..ff99937c15f2 100644 --- a/website/docs/r/media_live_output.html.markdown +++ b/website/docs/r/media_live_output.html.markdown @@ -115,5 +115,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d Live Outputs can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_media_live_output.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Media/mediaservices/account1/liveevents/event1/liveoutputs/output1 +terraform import azurerm_media_live_event_output.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Media/mediaservices/account1/liveevents/event1/liveoutputs/output1 ``` diff --git a/website/docs/r/mssql_database.html.markdown b/website/docs/r/mssql_database.html.markdown index d7cf8f20a9ef..f35a1d9c301a 100644 --- a/website/docs/r/mssql_database.html.markdown +++ b/website/docs/r/mssql_database.html.markdown @@ -10,8 +10,6 @@ description: |- Manages a MS SQL Database. -~> **Note:** The Database Extended Auditing Policy can be set inline here, as well as with the [mssql_database_extended_auditing_policy resource](mssql_database_extended_auditing_policy.html) resource. You can only use one or the other and using both will cause a conflict. - ## Example Usage ```hcl @@ -79,8 +77,6 @@ The following arguments are supported: * `elastic_pool_id` - (Optional) Specifies the ID of the elastic pool containing this database. -* `extended_auditing_policy` - (Optional) A `extended_auditing_policy` block as defined below. - * `geo_backup_enabled` - (Optional) A boolean that specifies if the Geo Backup Policy is enabled. ~> **Note:** `geo_backup_enabled` is only applicable for DataWarehouse SKUs (DW*). This setting is ignored for all other SKUs. @@ -140,16 +136,6 @@ a `threat_detection_policy` block supports the following: --- -A `extended_auditing_policy` block supports the following: - -* `storage_account_access_key` - (Optional) Specifies the access key to use for the auditing storage account. -* `storage_endpoint` - (Optional) Specifies the blob storage endpoint (e.g. https://example.blob.core.windows.net). -* `storage_account_access_key_is_secondary` - (Optional) Specifies whether `storage_account_access_key` value is the storage's secondary key. -* `retention_in_days` - (Optional) Specifies the number of days to retain logs for in the storage account. -* `log_monitoring_enabled` - (Optional) Enable audit events to Azure Monitor? To enable audit events to Log Analytics, please refer to the example which can be found in [the `./examples/sql-azure/sql_auditing_log_analytics` directory within the GitHub Repository](https://github.com/hashicorp/terraform-provider-azurerm/tree/main/examples/sql-azure/sql_auditing_log_analytics). To enable audit events to Eventhub, please refer to the example which can be found in [the `./examples/sql-azure/sql_auditing_eventhub` directory within the GitHub Repository](https://github.com/hashicorp/terraform-provider-azurerm/tree/main/examples/sql-azure/sql_auditing_eventhub). - ---- - A `long_term_retention_policy` block supports the following: * `weekly_retention` - (Optional) The weekly retention policy for an LTR backup in an ISO 8601 format. Valid value is between 1 to 520 weeks. e.g. `P1Y`, `P1M`, `P1W` or `P7D`. diff --git a/website/docs/r/mssql_managed_instance_failover_group.html.markdown b/website/docs/r/mssql_managed_instance_failover_group.html.markdown index 0a52f22578af..6e9fa79f2ed1 100644 --- a/website/docs/r/mssql_managed_instance_failover_group.html.markdown +++ b/website/docs/r/mssql_managed_instance_failover_group.html.markdown @@ -119,8 +119,6 @@ The following arguments are supported: * `name` - (Required) The name which should be used for this Managed Instance Failover Group. Changing this forces a new resource to be created. -* `resource_group_name` - (Required) The name of the Resource Group where the Managed Instance Failover Group should exist. Changing this forces a new resource to be created. - * `location` - The Azure Region where the Managed Instance Failover Group should exist. Changing this forces a new resource to be created. * `managed_instance_id` - (Required) The ID of the Azure SQL Managed Instance which will be replicated using a Managed Instance Failover Group. Changing this forces a new resource to be created. diff --git a/website/docs/r/netapp_snapshot_policy.html.markdown b/website/docs/r/netapp_snapshot_policy.html.markdown index 17d9701b0541..181fa37cff0b 100644 --- a/website/docs/r/netapp_snapshot_policy.html.markdown +++ b/website/docs/r/netapp_snapshot_policy.html.markdown @@ -162,5 +162,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d NetApp Snapshot Policy can be imported using the `resource id`, e.g. ```shell -$ terraform import azurerm_netapp_snapshot.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.NetApp/netAppAccounts/account1/snapshotPolicies/snapshotpolicy1 +$ terraform import azurerm_netapp_snapshot_policy.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.NetApp/netAppAccounts/account1/snapshotPolicies/snapshotpolicy1 ``` diff --git a/website/docs/r/orchestrated_virtual_machine_scale_set.html.markdown b/website/docs/r/orchestrated_virtual_machine_scale_set.html.markdown index 5140c78f56a7..7968ee085db6 100644 --- a/website/docs/r/orchestrated_virtual_machine_scale_set.html.markdown +++ b/website/docs/r/orchestrated_virtual_machine_scale_set.html.markdown @@ -97,7 +97,7 @@ The following arguments are supported: --- -A `os_profile` block supports the following: +A `os_profile` block supports the following: * `custom_data` - (Optional) The Base64-Encoded Custom Data which should be used for this Orchestrated Virtual Machine Scale Set. @@ -133,7 +133,7 @@ A `windows_configuration` block supports the following: * `timezone` - (Optional) Specifies the time zone of the virtual machine, the possible values are defined [here](https://jackstromberg.com/2017/01/list-of-time-zones-consumed-by-azure/). -* `winrm_listener` - (Optional) One or more `winrm_listener` blocks as defined below. +* `winrm_listener` - (Optional) One or more `winrm_listener` blocks as defined below. --- @@ -193,7 +193,7 @@ A `admin_ssh_key` block supports the following: --- -A `winrm_listener` block supports the following: +A `winrm_listener` block supports the following: * `certificate_url` - (Optional) The Secret URL of a Key Vault Certificate, which must be specified when protocol is set to `Https`. @@ -201,7 +201,7 @@ A `winrm_listener` block supports the following: --- -A `automatic_instance_repair` block supports the following: +A `automatic_instance_repair` block supports the following: * `enabled` - (Required) Should the automatic instance repair be enabled on this Orchestrated Virtual Machine Scale Set? Possible values are `true` and `false`. Defaults to `false`. @@ -209,19 +209,19 @@ A `automatic_instance_repair` block supports the following: --- -A `boot_diagnostics` block supports the following: +A `boot_diagnostics` block supports the following: * `storage_account_uri` - (Optional) The Primary/Secondary Endpoint for the Azure Storage Account which should be used to store Boot Diagnostics, including Console Output and Screenshots from the Hypervisor. By including a `boot_diagnostics` block without passing the `storage_account_uri` field will cause the API to utilize a Managed Storage Account to store the Boot Diagnostics output. --- -A `certificate` block supports the following: +A `certificate` block supports the following: -* `store` - (Required) The certificate store on the Virtual Machine where the certificate should be added. +* `store` - (Required) The certificate store on the Virtual Machine where the certificate should be added. -* `url` - (Required) The Secret URL of a Key Vault Certificate. +* `url` - (Required) The Secret URL of a Key Vault Certificate. -~> **NOTE:** This can be sourced from the `secret_id` field within the `azurerm_key_vault_certificate` Resource. +~> **NOTE:** This can be sourced from the `secret_id` field within the `azurerm_key_vault_certificate` Resource. --- @@ -229,41 +229,43 @@ A `diff_disk_settings` block supports the following: * `option` - (Required) Specifies the Ephemeral Disk Settings for the OS Disk. At this time the only possible value is `Local`. Changing this forces a new resource to be created. +* `placement` - (Optional) Specifies where to store the Ephemeral Disk. Possible values are `CacheDisk` and `ResourceDisk`. Defaults to `CacheDisk`. Changing this forces a new resource to be created. + --- -A `data_disk` block supports the following: +A `data_disk` block supports the following: -* `caching` - (Required) The type of Caching which should be used for this Data Disk. Possible values are None, ReadOnly and ReadWrite. +* `caching` - (Required) The type of Caching which should be used for this Data Disk. Possible values are None, ReadOnly and ReadWrite. -* `create_option` - (Optional) The create option which should be used for this Data Disk. Possible values are Empty and FromImage. Defaults to Empty. (FromImage should only be used if the source image includes data disks). +* `create_option` - (Optional) The create option which should be used for this Data Disk. Possible values are Empty and FromImage. Defaults to Empty. (FromImage should only be used if the source image includes data disks). -* `disk_size_gb` - (Required) The size of the Data Disk which should be created. +* `disk_size_gb` - (Required) The size of the Data Disk which should be created. -* `lun` - (Required) The Logical Unit Number of the Data Disk, which must be unique within the Virtual Machine. +* `lun` - (Required) The Logical Unit Number of the Data Disk, which must be unique within the Virtual Machine. -* `storage_account_type` - (Required) The Type of Storage Account which should back this Data Disk. Possible values include Standard_LRS, StandardSSD_LRS, Premium_LRS and UltraSSD_LRS. +* `storage_account_type` - (Required) The Type of Storage Account which should back this Data Disk. Possible values include Standard_LRS, StandardSSD_LRS, Premium_LRS and UltraSSD_LRS. --- -An `extension` block supports the following: +An `extension` block supports the following: -* `name` - (Required) The name for the Virtual Machine Scale Set Extension. +* `name` - (Required) The name for the Virtual Machine Scale Set Extension. -* `publisher` - (Required) Specifies the Publisher of the Extension. +* `publisher` - (Required) Specifies the Publisher of the Extension. -* `type` - (Required) Specifies the Type of the Extension. +* `type` - (Required) Specifies the Type of the Extension. -* `type_handler_version` - (Required) Specifies the version of the extension to use, available versions can be found using the Azure CLI. +* `type_handler_version` - (Required) Specifies the version of the extension to use, available versions can be found using the Azure CLI. -* `auto_upgrade_minor_version_enabled` - (Optional) Should the latest version of the Extension be used at Deployment Time, if one is available? This won't auto-update the extension on existing installation. Defaults to true. +* `auto_upgrade_minor_version_enabled` - (Optional) Should the latest version of the Extension be used at Deployment Time, if one is available? This won't auto-update the extension on existing installation. Defaults to true. * `extensions_to_provision_after_vm_creation` - (Optional) An ordered list of Extension names which Orchestrated Virtual Machine Scale Set should provision after VM creation. -* `force_extension_execution_on_change` - (Optional) A value which, when different to the previous value can be used to force-run the Extension even if the Extension Configuration hasn't changed. +* `force_extension_execution_on_change` - (Optional) A value which, when different to the previous value can be used to force-run the Extension even if the Extension Configuration hasn't changed. -* `protected_settings` - (Optional) A JSON String which specifies Sensitive Settings (such as Passwords) for the Extension. +* `protected_settings` - (Optional) A JSON String which specifies Sensitive Settings (such as Passwords) for the Extension. -~> **NOTE:** Keys within the `protected_settings` block are notoriously case-sensitive, where the casing required (e.g. `TitleCase` vs `snakeCase`) depends on the Extension being used. Please refer to the documentation for the specific Orchestrated Virtual Machine Extension you're looking to use for more information. +~> **NOTE:** Keys within the `protected_settings` block are notoriously case-sensitive, where the casing required (e.g. `TitleCase` vs `snakeCase`) depends on the Extension being used. Please refer to the documentation for the specific Orchestrated Virtual Machine Extension you're looking to use for more information. --- @@ -287,7 +289,7 @@ A `ip_configuration` block supports the following: * `subnet_id` - (Optional) The ID of the Subnet which this IP Configuration should be connected to. -~> **NOTE:** `subnet_id` is required if version is set to `IPv4`. +~> **NOTE:** `subnet_id` is required if version is set to `IPv4`. * `version` - (Optional) The Internet Protocol Version which should be used for this IP Configuration. Possible values are `IPv4` and `IPv6`. Defaults to `IPv4`. @@ -301,7 +303,7 @@ A `ip_tag` block supports the following: --- -A `network_interface` block supports the following: +A `network_interface` block supports the following: * `name` - (Required) The Name which should be used for this Network Interface. Changing this forces a new resource to be created. @@ -323,21 +325,21 @@ A `network_interface` block supports the following: A `os_disk` block supports the following: -* `caching` - (Required) The Type of Caching which should be used for the Internal OS Disk. Possible values are `None`, `ReadOnly` and `ReadWrite`. +* `caching` - (Required) The Type of Caching which should be used for the Internal OS Disk. Possible values are `None`, `ReadOnly` and `ReadWrite`. -* `storage_account_type` - (Required) The Type of Storage Account which should back this the Internal OS Disk. Possible values include `Standard_LRS`, `StandardSSD_LRS` and `Premium_LRS`. +* `storage_account_type` - (Required) The Type of Storage Account which should back this the Internal OS Disk. Possible values include `Standard_LRS`, `StandardSSD_LRS` and `Premium_LRS`. * `diff_disk_settings` - (Optional) A `diff_disk_settings` block as defined above. -* `disk_encryption_set_id` - (Optional) The ID of the Disk Encryption Set which should be used to encrypt this OS Disk. +* `disk_encryption_set_id` - (Optional) The ID of the Disk Encryption Set which should be used to encrypt this OS Disk. -~> **NOTE:** Disk Encryption Sets are in Public Preview in a limited set of regions +~> **NOTE:** Disk Encryption Sets are in Public Preview in a limited set of regions * `disk_size_gb` - (Optional) The Size of the Internal OS Disk in GB, if you wish to vary from the size used in the image this Virtual Machine Scale Set is sourced from. --- -A `plan` block supports the following: +A `plan` block supports the following: * `name` - (Required) Specifies the name of the image from the marketplace. Changing this forces a new resource to be created. @@ -355,37 +357,37 @@ A `identity` block supports the following: --- -A `public_ip_address` block supports the following: +A `public_ip_address` block supports the following: -* `name` - (Required) The Name of the Public IP Address Configuration. +* `name` - (Required) The Name of the Public IP Address Configuration. * `domain_name_label` - (Optional) The Prefix which should be used for the Domain Name Label for each Virtual Machine Instance. Azure concatenates the Domain Name Label and Virtual Machine Index to create a unique Domain Name Label for each Virtual Machine. Valid values must be between `1` and `26` characters long, start with a lower case letter, end with a lower case letter or number and contains only `a-z`, `0-9` and `hyphens`. -* `idle_timeout_in_minutes` - (Optional) The Idle Timeout in Minutes for the Public IP Address. Possible values are in the range `4` to `32`. +* `idle_timeout_in_minutes` - (Optional) The Idle Timeout in Minutes for the Public IP Address. Possible values are in the range `4` to `32`. * `ip_tag` - (Optional) One or more `ip_tag` blocks as defined above. -* `public_ip_prefix_id` - (Optional) The ID of the Public IP Address Prefix from where Public IP Addresses should be allocated. Changing this forces a new resource to be created. +* `public_ip_prefix_id` - (Optional) The ID of the Public IP Address Prefix from where Public IP Addresses should be allocated. Changing this forces a new resource to be created. --- A `termination_notification` block supports the following: -* `enabled` - (Required) Should the termination notification be enabled on this Virtual Machine Scale Set? Possible values `true` or `false` Defaults to `false`. +* `enabled` - (Required) Should the termination notification be enabled on this Virtual Machine Scale Set? Possible values `true` or `false` Defaults to `false`. * `timeout` - (Optional) Length of time (in minutes, between `5` and `15`) a notification to be sent to the VM on the instance metadata server till the VM gets deleted. The time duration should be specified in `ISO 8601` format. Defaults to `PT5M`. --- -A `source_image_reference` block supports the following: +A `source_image_reference` block supports the following: -* `publisher` - (Optional) Specifies the publisher of the image used to create the virtual machines. +* `publisher` - (Optional) Specifies the publisher of the image used to create the virtual machines. -* `offer` - (Optional) Specifies the offer of the image used to create the virtual machines. +* `offer` - (Optional) Specifies the offer of the image used to create the virtual machines. -* `sku` - (Optional) Specifies the SKU of the image used to create the virtual machines. +* `sku` - (Optional) Specifies the SKU of the image used to create the virtual machines. -* `version` - (Optional) Specifies the version of the image used to create the virtual machines. +* `version` - (Optional) Specifies the version of the image used to create the virtual machines. --- diff --git a/website/docs/r/postgresql_flexible_server_configuration.html.markdown b/website/docs/r/postgresql_flexible_server_configuration.html.markdown index 74e70cf238b0..e4ddde68601b 100644 --- a/website/docs/r/postgresql_flexible_server_configuration.html.markdown +++ b/website/docs/r/postgresql_flexible_server_configuration.html.markdown @@ -42,12 +42,46 @@ resource "azurerm_postgresql_flexible_server_configuration" "example" { } ``` +## Example Usage - Azure Extensions + +```hcl +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "example" { + name = "example-resources" + location = "West Europe" +} + +resource "azurerm_postgresql_flexible_server" "example" { + name = "example-psqlflexibleserver" + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + version = "12" + administrator_login = "psqladmin" + administrator_password = "H@Sh1CoR3!" + + storage_mb = 32768 + + sku_name = "GP_Standard_D4s_v3" +} + +resource "azurerm_postgresql_flexible_server_configuration" "example" { + name = "azure.extensions" + server_id = azurerm_postgresql_flexible_server.example.id + value = "CUBE,CITEXT,BTREE_GIST" +} +``` + ## Argument Reference The following arguments are supported: * `name` - (Required) Specifies the name of the PostgreSQL Configuration, which needs [to be a valid PostgreSQL configuration name](https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIER). Changing this forces a new resource to be created. +-> **Note:** PostgreSQL provides the ability to extend the functionality using azure extensions, with PostgreSQL azure extensions you should specify the `name` value as `azure.extensions` and the `value` you wish to allow in the [extensions list](https://docs.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-extensions?WT.mc_id=Portal-Microsoft_Azure_OSSDatabases#postgres-13-extensions). + * `server_id` - (Required) The ID of the PostgreSQL Flexible Server where we want to change configuration. Changing this forces a new PostgreSQL Flexible Server Configuration resource. * `value` - (Required) Specifies the value of the PostgreSQL Configuration. See the PostgreSQL documentation for valid values. diff --git a/website/docs/r/resource_group_policy_exemption.html.markdown b/website/docs/r/resource_group_policy_exemption.html.markdown new file mode 100644 index 000000000000..d4462b4d5002 --- /dev/null +++ b/website/docs/r/resource_group_policy_exemption.html.markdown @@ -0,0 +1,87 @@ +--- +subcategory: "Policy" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_resource_group_policy_exemption" +description: |- + Manages a Resource Group Policy Exemption. +--- + +# azurerm_resource_group_policy_exemption + +Manages a Resource Group Policy Exemption. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "resourceGroup1" + location = "westus" +} + +data "azurerm_policy_definition" "example" { + display_name = "Allowed locations" +} + +resource "azurerm_resource_group_policy_assignment" "example" { + name = "exampleAssignment" + resource_group_id = azurerm_resource_group.example.id + policy_definition_id = data.azurerm_policy_definition.example.id + parameters = jsonencode({ + "listOfAllowedLocations" = { + "value" = [azurerm_resource_group.example.location] + } + }) +} + +resource "azurerm_resource_group_policy_exemption" "example" { + name = "exampleExemption" + resource_group_id = azurerm_resource_group.example.id + policy_assignment_id = azurerm_resource_group_policy_assignment.example.id + exemption_category = "Mitigated" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the Policy Exemption. Changing this forces a new resource to be created. + +* `resource_group_id`- (Required) The Resource Group ID where the Policy Exemption should be applied. Changing this forces a new resource to be created. + +* `exemption_category` - (Required) The category of this policy exemption. Possible values are `Waiver` and `Mitigated`. + +* `policy_assignment_id` - (Required) The ID of the Policy Assignment to be exempted at the specified Scope. + +* `description` - (Optional) A description to use for this Policy Exemption. + +* `display_name` - (Optional) A friendly display name to use for this Policy Exemption. + +* `expires_on` - (Optional) The expiration date and time in UTC ISO 8601 format of this policy exemption. + +* `policy_definition_reference_ids` - (Optional) The policy definition reference ID list when the associated policy assignment is an assignment of a policy set definition. + +* `metadata` - (Optional) The metadata for this policy exemption. This is a JSON string representing additional metadata that should be stored with the policy exemption. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The Policy Exemption id. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Policy Exemption. +* `update` - (Defaults to 30 minutes) Used when updating the Policy Exemption. +* `read` - (Defaults to 5 minutes) Used when retrieving the Policy Exemption. +* `delete` - (Defaults to 30 minutes) Used when deleting the Policy Exemption. + +## Import + +Policy Exemptions can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_resource_group_policy_exemption.exemption1 /subscriptions/00000000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Authorization/policyExemptions/exemption1 +``` diff --git a/website/docs/r/resource_group_policy_remediation.html.markdown b/website/docs/r/resource_group_policy_remediation.html.markdown new file mode 100644 index 000000000000..6c195e198162 --- /dev/null +++ b/website/docs/r/resource_group_policy_remediation.html.markdown @@ -0,0 +1,107 @@ +--- +subcategory: "Policy" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_resource_group_policy_remediation" +description: |- + Manages an Azure Resource Group Policy Remediation. +--- + +# azurerm_resource_group_policy_remediation + +Manages an Azure Resource Group Policy Remediation. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-resources" + location = "West Europe" +} + +resource "azurerm_policy_definition" "example" { + name = "my-policy-definition" + policy_type = "Custom" + mode = "All" + display_name = "my-policy-definition" + + policy_rule = < **NOTE:** Partitioning is available at entity creation for all queues and topics in Basic or Standard SKUs. It is not available for the Premium messaging SKU, but any previously existing partitioned entities in Premium namespaces continue to work as expected. Please [see the documentation](https://docs.microsoft.com/azure/service-bus-messaging/service-bus-partitioning) for more information. diff --git a/website/docs/r/shared_image.html.markdown b/website/docs/r/shared_image.html.markdown index 4cdd180593f9..34d9c610ee60 100644 --- a/website/docs/r/shared_image.html.markdown +++ b/website/docs/r/shared_image.html.markdown @@ -68,6 +68,10 @@ The following arguments are supported: * `description` - (Optional) A description of this Shared Image. +* `disk_types_not_allowed` - (Optional) One or more Disk Types not allowed for the Image. Possible values include `Standard_LRS` and `Premium_LRS`. + +* `end_of_life_date` - (Optional) The end of life date in RFC3339 format of the Image. + * `eula` - (Optional) The End User Licence Agreement for the Shared Image. Changing this forces a new resource to be created. * `specialized` - (Optional) Specifies that the Operating System used inside this Image has not been Generalized (for example, `sysprep` on Windows has not been run). Defaults to `false`. Changing this forces a new resource to be created. @@ -76,6 +80,14 @@ The following arguments are supported: * `hyper_v_generation` - (Optional) The generation of HyperV that the Virtual Machine used to create the Shared Image is based on. Possible values are `V1` and `V2`. Defaults to `V1`. Changing this forces a new resource to be created. +* `max_recommended_vcpu_count` - (Optional) Maximum count of vCPUs recommended for the Image. + +* `min_recommended_vcpu_count` - (Optional) Minimum count of vCPUs recommended for the Image. + +* `max_recommended_memory_in_gb` - (Optional) Maximum memory in GB recommended for the Image. + +* `min_recommended_memory_in_gb` - (Optional) Minimum memory in GB recommended for the Image. + * `privacy_statement_uri` - (Optional) The URI containing the Privacy Statement associated with this Shared Image. Changing this forces a new resource to be created. * `release_note_uri` - (Optional) The URI containing the Release Notes associated with this Shared Image. diff --git a/website/docs/r/signalr_service.html.markdown b/website/docs/r/signalr_service.html.markdown index b2b9f16fe1db..70f5ad419e2c 100644 --- a/website/docs/r/signalr_service.html.markdown +++ b/website/docs/r/signalr_service.html.markdown @@ -69,6 +69,8 @@ The following arguments are supported: * `upstream_endpoint` - (Optional) An `upstream_endpoint` block as documented below. Using this block requires the SignalR service to be Serverless. When creating multiple blocks they will be processed in the order they are defined in. +* `live_trace` - (Optional) A `live_trace` block as defined below. + * `tags` - (Optional) A mapping of tags to assign to the resource. --- @@ -91,6 +93,18 @@ An `upstream_endpoint` block supports the following: --- +A `live_trace` block supports the following: + +* `enabled` - (Optional) Whether the live trace is enabled? Defaults to `true`. + +* `messaging_logs_enabled` - (Optional) Whether the log category `MessagingLogs` is enabled? Defaults to `true` + +* `connectivity_logs_enabled` - (Optional) Whether the log category `ConnectivityLogs` is enabled? Defaults to `true` + +* `http_request_logs_enabled` - (Optional) Whether the log category `HttpRequestLogs` is enabled? Defaults to `true` + +--- + A `sku` block supports the following: * `name` - (Required) Specifies which tier to use. Valid values are `Free_F1`, `Standard_S1` and `Premium_P1`. diff --git a/website/docs/r/spring_cloud_build_deployment.html.markdown b/website/docs/r/spring_cloud_build_deployment.html.markdown index 18cd81e2d483..56a4dda0109b 100644 --- a/website/docs/r/spring_cloud_build_deployment.html.markdown +++ b/website/docs/r/spring_cloud_build_deployment.html.markdown @@ -64,6 +64,8 @@ The following arguments are supported: --- +* `addon_json` - (Optional) A JSON object that contains the addon configurations of the Spring Cloud Build Deployment. + * `environment_variables` - (Optional) Specifies the environment variables of the Spring Cloud Deployment as a map of key-value pairs. * `instance_count` - (Optional) Specifies the required instance count of the Spring Cloud Deployment. Possible Values are between `1` and `500`. Defaults to `1` if not specified. diff --git a/website/docs/r/spring_cloud_container_deployment.html.markdown b/website/docs/r/spring_cloud_container_deployment.html.markdown index ca215159b10f..4ef3fc0fa263 100644 --- a/website/docs/r/spring_cloud_container_deployment.html.markdown +++ b/website/docs/r/spring_cloud_container_deployment.html.markdown @@ -39,8 +39,8 @@ resource "azurerm_spring_cloud_container_deployment" "example" { name = "example" spring_cloud_app_id = azurerm_spring_cloud_app.example.id instance_count = 2 - arguments = ["-c", "echo hello"] - commands = ["/bin/sh"] + arguments = ["-cp", "/app/resources:/app/classes:/app/libs/*", "hello.Application"] + commands = ["java"] environment_variables = { "Foo" : "Bar" "Env" : "Staging" @@ -65,6 +65,8 @@ The following arguments are supported: --- +* `addon_json` - (Optional) A JSON object that contains the addon configurations of the Spring Cloud Container Deployment. + * `arguments` - (Optional) Specifies the arguments to the entrypoint. The docker image's `CMD` is used if not specified. * `commands` - (Optional) Specifies the entrypoint array. It will not be executed within a shell. The docker image's `ENTRYPOINT` is used if not specified. diff --git a/website/docs/r/stream_analytics_output_blob.html.markdown b/website/docs/r/stream_analytics_output_blob.html.markdown index 5f3fcf7a58b3..227539834f26 100644 --- a/website/docs/r/stream_analytics_output_blob.html.markdown +++ b/website/docs/r/stream_analytics_output_blob.html.markdown @@ -72,18 +72,20 @@ The following arguments are supported: * `storage_account_name` - (Required) The name of the Storage Account. -* `storage_account_key` - (Required) The Access Key which should be used to connect to this Storage Account. - * `storage_container_name` - (Required) The name of the Container within the Storage Account. * `time_format` - (Required) The time format. Wherever `{time}` appears in `path_pattern`, the value of this property is used as the time format instead. * `serialization` - (Required) A `serialization` block as defined below. +* `authentication_mode` - (Optional) The authentication mode for the Stream Output. Possible values are `Msi` and `ConnectionString`. Defaults to `ConnectionString`. + * `batch_max_wait_time` - (Optional) The maximum wait time per batch in `hh:mm:ss` e.g. `00:02:00` for two minutes. * `batch_min_rows` - (Optional) The minimum number of rows per batch (must be between `0` and `10000`). +* `storage_account_key` - (Optional) The Access Key which should be used to connect to this Storage Account. + --- A `serialization` block supports the following: diff --git a/website/docs/r/subscription_policy_exemption.html.markdown b/website/docs/r/subscription_policy_exemption.html.markdown new file mode 100644 index 000000000000..b7022584d0c7 --- /dev/null +++ b/website/docs/r/subscription_policy_exemption.html.markdown @@ -0,0 +1,84 @@ +--- +subcategory: "Policy" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_subscription_policy_exemption" +description: |- + Manages a Subscription Policy Exemption. +--- + +# azurerm_subscription_policy_exemption + +Manages a Subscription Policy Exemption. + +## Example Usage + +```hcl +data "azurerm_subscription" "example" {} + +data "azurerm_policy_set_definition" "example" { + display_name = "Audit machines with insecure password security settings" +} + +resource "azurerm_subscription_policy_assignment" "example" { + name = "exampleAssignment" + subscription_id = data.azurerm_subscription.example.id + policy_definition_id = data.azurerm_policy_set_definition.example.id + location = "westus" + + identity { + type = "SystemAssigned" + } +} + +resource "azurerm_subscription_policy_exemption" "example" { + name = "exampleExemption" + subscription_id = data.azurerm_subscription.example.id + policy_assignment_id = azurerm_subscription_policy_assignment.example.id + exemption_category = "Mitigated" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the Policy Exemption. Changing this forces a new resource to be created. + +* `subscription_id`- (Required) The Subscription ID where the Policy Exemption should be applied. Changing this forces a new resource to be created. + +* `exemption_category` - (Required) The category of this policy exemption. Possible values are `Waiver` and `Mitigated`. + +* `policy_assignment_id` - (Required) The ID of the Policy Assignment to be exempted at the specified Scope. + +* `description` - (Optional) A description to use for this Policy Exemption. + +* `display_name` - (Optional) A friendly display name to use for this Policy Exemption. + +* `expires_on` - (Optional) The expiration date and time in UTC ISO 8601 format of this policy exemption. + +* `policy_definition_reference_ids` - (Optional) The policy definition reference ID list when the associated policy assignment is an assignment of a policy set definition. + +* `metadata` - (Optional) The metadata for this policy exemption. This is a JSON string representing additional metadata that should be stored with the policy exemption. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The Policy Exemption id. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Policy Exemption. +* `update` - (Defaults to 30 minutes) Used when updating the Policy Exemption. +* `read` - (Defaults to 5 minutes) Used when retrieving the Policy Exemption. +* `delete` - (Defaults to 30 minutes) Used when deleting the Policy Exemption. + +## Import + +Policy Exemptions can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_subscription_policy_exemption.exemption1 /subscriptions/00000000-0000-0000-000000000000/providers/Microsoft.Authorization/policyExemptions/exemption1 +``` diff --git a/website/docs/r/subscription_policy_remediation.html.markdown b/website/docs/r/subscription_policy_remediation.html.markdown new file mode 100644 index 000000000000..956950ca9be4 --- /dev/null +++ b/website/docs/r/subscription_policy_remediation.html.markdown @@ -0,0 +1,78 @@ +--- +subcategory: "Policy" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_subscription_policy_remediation" +description: |- + Manages an Azure Subscription Policy Remediation. +--- + +# azurerm_subscription_policy_remediation + +Manages an Azure Subscription Policy Remediation. + +## Example Usage + +```hcl +data "azurerm_subscription" "example" {} + +data "azurerm_policy_definition" "example" { + display_name = "Allowed resource types" +} + +resource "azurerm_subscription_policy_assignment" "example" { + name = "exampleAssignment" + subscription_id = data.azurerm_subscription.example.id + policy_definition_id = data.azurerm_policy_definition.example.id + parameters = jsonencode({ + "listOfAllowedLocations" = { + "value" = ["West Europe", "East US"] + } + }) +} + +resource "azurerm_subscription_policy_remediation" "example" { + name = "example" + subscription_id = data.azurerm_subscription.example.id + policy_assignment_id = azurerm_subscription_policy_assignment.example.id +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the Policy Remediation. Changing this forces a new resource to be created. + +* `subscription_id` - (Required) The Subscription ID at which the Policy Remediation should be applied. Changing this forces a new resource to be created. + +* `policy_assignment_id` - (Required) The ID of the Policy Assignment that should be remediated. + +* `policy_definition_id` - (Optional) The unique ID for the policy definition within the policy set definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. + +* `location_filters` - (Optional) A list of the resource locations that will be remediated. + +* `resource_discovery_mode` - (Optional) The way that resources to remediate are discovered. Possible values are `ExistingNonCompliant`, `ReEvaluateCompliance`. Defaults to `ExistingNonCompliant`. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The ID of the Policy Remediation. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Policy Remediation. +* `update` - (Defaults to 30 minutes) Used when updating the Policy Remediation. +* `read` - (Defaults to 5 minutes) Used when retrieving the Policy Remediation. +* `delete` - (Defaults to 30 minutes) Used when deleting the Policy Remediation. + + +## Import + +Policy Remediations can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_subscription_policy_remediation.example /subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.PolicyInsights/remediations/remediation1 +``` diff --git a/website/docs/r/synapse_integration_runtime_azure.html.markdown b/website/docs/r/synapse_integration_runtime_azure.html.markdown index ec55c9c31d3b..9456479e5335 100644 --- a/website/docs/r/synapse_integration_runtime_azure.html.markdown +++ b/website/docs/r/synapse_integration_runtime_azure.html.markdown @@ -74,7 +74,7 @@ The following arguments are supported: * `synapse_workspace_id` - (Required) The Synapse Workspace ID in which to associate the Integration Runtime with. Changing this forces a new Synapse Azure Integration Runtime to be created. -* `location` - (Required) The Azure Region where the Synapse Azure Integration Runtime should exist. Changing this forces a new Synapse Azure Integration Runtime to be created. +* `location` - (Required) The Azure Region where the Synapse Azure Integration Runtime should exist. Use `AutoResolve` to create an auto-resolve integration runtime. Changing this forces a new Synapse Azure Integration Runtime to be created. --- diff --git a/website/docs/r/traffic_manager_azure_endpoint.html.markdown b/website/docs/r/traffic_manager_azure_endpoint.html.markdown index 1ceaeea1a4d8..6294f7b92187 100644 --- a/website/docs/r/traffic_manager_azure_endpoint.html.markdown +++ b/website/docs/r/traffic_manager_azure_endpoint.html.markdown @@ -69,7 +69,7 @@ The following arguments are supported: * `target_resource_id` - (Required) The ID of the Azure Resource which should be used as a target. -* `weight` - (Required) Specifies how much traffic should be distributed to this endpoint. Valid values are between `1` and `1000`. +* `weight` - (Optional) Specifies how much traffic should be distributed to this endpoint, this must be specified for Profiles using the Weighted traffic routing method. Valid values are between `1` and `1000`. --- diff --git a/website/docs/r/traffic_manager_external_endpoint.html.markdown b/website/docs/r/traffic_manager_external_endpoint.html.markdown index b55309463aa4..1816bbaec813 100644 --- a/website/docs/r/traffic_manager_external_endpoint.html.markdown +++ b/website/docs/r/traffic_manager_external_endpoint.html.markdown @@ -60,8 +60,7 @@ The following arguments are supported: * `target` - (Required) The FQDN DNS name of the target. -* `weight` - (Required) Specifies how much traffic should be distributed to this - endpoint. Valid values are between `1` and `1000`. +* `weight` - (Optional) Specifies how much traffic should be distributed to this endpoint, this must be specified for Profiles using the Weighted traffic routing method. Valid values are between `1` and `1000`. * `endpoint_location` - (Optional) Specifies the Azure location of the Endpoint, this must be specified for Profiles using the `Performance` routing method. diff --git a/website/docs/r/traffic_manager_nested_endpoint.html.markdown b/website/docs/r/traffic_manager_nested_endpoint.html.markdown index d5021ee4fc93..9af176095243 100644 --- a/website/docs/r/traffic_manager_nested_endpoint.html.markdown +++ b/website/docs/r/traffic_manager_nested_endpoint.html.markdown @@ -96,8 +96,7 @@ The following arguments are supported: * `target_resource_id` - (Required) The resource id of an Azure resource to target. -* `weight` - (Required) Specifies how much traffic should be distributed to this - endpoint. Valid values are between `1` and `1000`. +* `weight` - (Optional) Specifies how much traffic should be distributed to this endpoint, this must be specified for Profiles using the Weighted traffic routing method. Valid values are between `1` and `1000`. --- diff --git a/website/docs/r/windows_virtual_machine.html.markdown b/website/docs/r/windows_virtual_machine.html.markdown index e905c8c4dcfd..22726a2b3f3e 100644 --- a/website/docs/r/windows_virtual_machine.html.markdown +++ b/website/docs/r/windows_virtual_machine.html.markdown @@ -119,6 +119,10 @@ The following arguments are supported: * `boot_diagnostics` - (Optional) A `boot_diagnostics` block as defined below. +* `capacity_reservation_group_id` - (Optional) Specifies the ID of the Capacity Reservation Group which the Virtual Machine should be allocated to. + +~> **NOTE:** `capacity_reservation_group_id` cannot be used with `availability_set_id` or `proximity_placement_group_id` + * `computer_name` - (Optional) Specifies the Hostname which should be used for this Virtual Machine. If unspecified this defaults to the value for the `name` field. If the value of the `name` field is not a valid `computer_name`, then you must specify `computer_name`. Changing this forces a new resource to be created. * `custom_data` - (Optional) The Base64-Encoded Custom Data which should be used for this Virtual Machine. Changing this forces a new resource to be created. diff --git a/website/docs/r/windows_virtual_machine_scale_set.html.markdown b/website/docs/r/windows_virtual_machine_scale_set.html.markdown index f24200931197..9d2d2b7adf23 100644 --- a/website/docs/r/windows_virtual_machine_scale_set.html.markdown +++ b/website/docs/r/windows_virtual_machine_scale_set.html.markdown @@ -120,6 +120,12 @@ The following arguments are supported: * `boot_diagnostics` - (Optional) A `boot_diagnostics` block as defined below. +* `capacity_reservation_group_id` - (Optional) Specifies the ID of the Capacity Reservation Group which the Virtual Machine Scale Set should be allocated to. Changing this forces a new resource to be created. + +~> **NOTE:** `capacity_reservation_group_id` cannot be used with `proximity_placement_group_id` + +~> **NOTE:** `single_placement_group` must be set to `false` when `capacity_reservation_group_id` is specified + * `computer_name_prefix` - (Optional) The prefix which should be used for the name of the Virtual Machines in this Scale Set. If unspecified this defaults to the value for the `name` field. If the value of the `name` field is not a valid `computer_name_prefix`, then you must specify `computer_name_prefix`. * `custom_data` - (Optional) The Base64-Encoded Custom Data which should be used for this Virtual Machine Scale Set. @@ -294,7 +300,9 @@ A `data_disk` block supports the following: A `diff_disk_settings` block supports the following: -`option` - (Required) Specifies the Ephemeral Disk Settings for the OS Disk. At this time the only possible value is `Local`. Changing this forces a new resource to be created. +* `option` - (Required) Specifies the Ephemeral Disk Settings for the OS Disk. At this time the only possible value is `Local`. Changing this forces a new resource to be created. + +* `placement` - (Optional) Specifies where to store the Ephemeral Disk. Possible values are `CacheDisk` and `ResourceDisk`. Defaults to `CacheDisk`. Changing this forces a new resource to be created. --- diff --git a/website/docs/r/windows_web_app.html.markdown b/website/docs/r/windows_web_app.html.markdown index 5c02f70820a7..e7f3c28b390f 100644 --- a/website/docs/r/windows_web_app.html.markdown +++ b/website/docs/r/windows_web_app.html.markdown @@ -420,6 +420,8 @@ A `site_config` block supports the following: * `always_on` - (Optional) If this Windows Web App is Always On enabled. Defaults to `true`. +~> **NOTE:** `always_on` must be explicitly set to `false` when using `Free`, `F1`, `D1`, or `Shared` Service Plans. + * `api_management_api_id` - (Optional) The API Management API ID this Windows Web App Slot is associated with. * `app_command_line` - (Optional) The App command line to launch. From ee652fdb43b6c557bee7c455511a061396ac4b25 Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 19 Jul 2022 16:39:06 +0800 Subject: [PATCH 10/12] update wps id --- internal/services/signalr/client/client.go | 2 +- internal/services/signalr/parse/web_pubsub.go | 4 +- .../services/signalr/parse/web_pubsub_hub.go | 4 +- .../signalr/parse/web_pubsub_hub_test.go | 10 +- ...web_pubsub_shared_private_link_resource.go | 4 +- ...ubsub_shared_private_link_resource_test.go | 10 +- .../services/signalr/parse/web_pubsub_test.go | 6 +- internal/services/signalr/resourceids.go | 6 +- .../validate/web_pubsub_hub_id_test.go | 8 +- .../signalr/validate/web_pubsub_id_test.go | 4 +- ...ub_shared_private_link_resource_id_test.go | 8 +- .../web_pubsub_network_acl_resource_test.go | 6 +- ...ubsub_shared_private_link_resource_test.go | 6 +- .../2021-03-01/containerinstance/CHANGELOG.md | 2 - .../2021-03-01/containerinstance/_meta.json | 11 - .../2021-03-01/containerinstance/client.go | 41 - .../containerinstance/containergroups.go | 844 -- .../containerinstance/containers.go | 280 - .../2021-03-01/containerinstance/enums.go | 180 - .../2021-03-01/containerinstance/location.go | 337 - .../2021-03-01/containerinstance/models.go | 1813 ---- .../containerinstance/operations.go | 140 - .../2021-03-01/containerinstance/version.go | 19 - .../kusto/mgmt/2021-08-27/kusto/CHANGELOG.md | 2 - .../kusto/mgmt/2021-08-27/kusto/_meta.json | 11 - .../kusto/attacheddatabaseconfigurations.go | 449 - .../kusto/mgmt/2021-08-27/kusto/client.go | 42 - .../kusto/clusterprincipalassignments.go | 446 - .../kusto/mgmt/2021-08-27/kusto/clusters.go | 1525 --- .../kusto/databaseprincipalassignments.go | 456 - .../kusto/mgmt/2021-08-27/kusto/databases.go | 761 -- .../mgmt/2021-08-27/kusto/dataconnections.go | 618 -- .../kusto/mgmt/2021-08-27/kusto/enums.go | 600 -- .../kusto/managedprivateendpoints.go | 534 - .../kusto/mgmt/2021-08-27/kusto/models.go | 4761 --------- .../kusto/mgmt/2021-08-27/kusto/operations.go | 142 - .../2021-08-27/kusto/operationsresults.go | 110 - .../kusto/privateendpointconnections.go | 360 - .../2021-08-27/kusto/privatelinkresources.go | 188 - .../kusto/mgmt/2021-08-27/kusto/scripts.go | 545 - .../kusto/mgmt/2021-08-27/kusto/version.go | 19 - .../2019-06-01/managedservices/CHANGELOG.md | 2 - .../2019-06-01/managedservices/_meta.json | 11 - .../mgmt/2019-06-01/managedservices/client.go | 39 - .../mgmt/2019-06-01/managedservices/enums.go | 42 - .../mgmt/2019-06-01/managedservices/models.go | 707 -- .../2019-06-01/managedservices/operations.go | 98 - .../registrationassignments.go | 410 - .../registrationdefinitions.go | 396 - .../2019-06-01/managedservices/version.go | 19 - .../mgmt/2021-10-01/netapp/CHANGELOG.md | 2 - .../netapp/mgmt/2021-10-01/netapp/_meta.json | 11 - .../mgmt/2021-10-01/netapp/accountbackups.go | 290 - .../netapp/mgmt/2021-10-01/netapp/accounts.go | 629 -- .../mgmt/2021-10-01/netapp/backuppolicies.go | 485 - .../netapp/mgmt/2021-10-01/netapp/backups.go | 741 -- .../netapp/mgmt/2021-10-01/netapp/client.go | 41 - .../netapp/mgmt/2021-10-01/netapp/enums.go | 346 - .../netapp/mgmt/2021-10-01/netapp/models.go | 5721 ---------- .../mgmt/2021-10-01/netapp/operations.go | 98 - .../netapp/mgmt/2021-10-01/netapp/pools.go | 550 - .../netapp/mgmt/2021-10-01/netapp/resource.go | 284 - .../2021-10-01/netapp/resourcequotalimits.go | 182 - .../2021-10-01/netapp/snapshotpolicies.go | 569 - .../mgmt/2021-10-01/netapp/snapshots.go | 654 -- .../mgmt/2021-10-01/netapp/subvolumes.go | 698 -- .../netapp/mgmt/2021-10-01/netapp/vaults.go | 116 - .../netapp/mgmt/2021-10-01/netapp/version.go | 19 - .../mgmt/2021-10-01/netapp/volumegroups.go | 397 - .../netapp/mgmt/2021-10-01/netapp/volumes.go | 1422 --- .../appplatform/CHANGELOG.md | 2 - .../2022-03-01-preview/appplatform/_meta.json | 11 - .../appplatform/apiportalcustomdomains.go | 404 - .../appplatform/apiportals.go | 484 - .../2022-03-01-preview/appplatform/apps.go | 760 -- .../appplatform/bindings.go | 490 - .../appplatform/buildpackbinding.go | 412 - .../appplatform/buildservice.go | 1203 --- .../appplatform/buildserviceagentpool.go | 321 - .../appplatform/buildservicebuilder.go | 404 - .../appplatform/certificates.go | 395 - .../2022-03-01-preview/appplatform/client.go | 41 - .../appplatform/configservers.go | 376 - .../appplatform/configurationservices.go | 482 - .../appplatform/customdomains.go | 490 - .../appplatform/deployments.go | 1205 --- .../2022-03-01-preview/appplatform/enums.go | 634 -- .../appplatform/gatewaycustomdomains.go | 404 - .../appplatform/gatewayrouteconfigs.go | 405 - .../appplatform/gateways.go | 484 - .../2022-03-01-preview/appplatform/models.go | 9391 ----------------- .../appplatform/monitoringsettings.go | 287 - .../appplatform/operations.go | 140 - .../appplatform/runtimeversions.go | 98 - .../appplatform/serviceregistries.go | 393 - .../appplatform/services.go | 1136 -- .../2022-03-01-preview/appplatform/skus.go | 144 - .../appplatform/storages.go | 395 - .../2022-03-01-preview/appplatform/version.go | 19 - .../policyinsights/CHANGELOG.md | 2 - .../policyinsights/_meta.json | 11 - .../policyinsights/client.go | 39 - .../policyinsights/enums.go | 38 - .../policyinsights/models.go | 2962 ------ .../policyinsights/operations.go | 98 - .../policyinsights/policyevents.go | 1336 --- .../policyinsights/policymetadata.go | 226 - .../policyinsights/policystates.go | 2314 ---- .../policyinsights/policytrackedresources.go | 560 - .../policyinsights/remediations.go | 2306 ---- .../policyinsights/version.go | 19 - .../2019-01-01-preview/portal/CHANGELOG.md | 2 - .../mgmt/2019-01-01-preview/portal/_meta.json | 11 - .../mgmt/2019-01-01-preview/portal/client.go | 41 - .../2019-01-01-preview/portal/dashboards.go | 603 -- .../mgmt/2019-01-01-preview/portal/models.go | 801 -- .../2019-01-01-preview/portal/operations.go | 140 - .../portal/tenantconfigurations.go | 316 - .../mgmt/2019-01-01-preview/portal/version.go | 19 - .../servicebus/CHANGELOG.md | 2 - .../2021-06-01-preview/servicebus/_meta.json | 11 - .../2021-06-01-preview/servicebus/client.go | 41 - .../servicebus/disasterrecoveryconfigs.go | 1040 -- .../2021-06-01-preview/servicebus/enums.go | 310 - .../servicebus/migrationconfigs.go | 608 -- .../2021-06-01-preview/servicebus/models.go | 3989 ------- .../servicebus/namespaces.go | 1600 --- .../servicebus/operations.go | 140 - .../servicebus/privateendpointconnections.go | 431 - .../servicebus/privatelinkresources.go | 119 - .../2021-06-01-preview/servicebus/queues.go | 1069 -- .../2021-06-01-preview/servicebus/rules.go | 492 - .../servicebus/subscriptions.go | 472 - .../2021-06-01-preview/servicebus/topics.go | 1069 -- .../2021-06-01-preview/servicebus/version.go | 19 - .../protoc-gen-go/descriptor/descriptor.pb.go | 200 - .../2020-06-01/configurationstores/README.md | 175 - .../2020-06-01/configurationstores/client.go | 18 - .../configurationstores/constants.go | 136 - .../id_configurationstore.go | 124 - .../method_create_autorest.go | 79 - .../method_delete_autorest.go | 78 - .../method_get_autorest.go | 67 - .../method_list_autorest.go | 187 - .../method_listbyresourcegroup_autorest.go | 187 - .../method_listkeys_autorest.go | 186 - .../method_listkeyvalue_autorest.go | 69 - .../method_regeneratekey_autorest.go | 69 - .../method_update_autorest.go | 79 - .../configurationstores/model_apikey.go | 31 - .../model_configurationstore.go | 19 - .../model_configurationstoreproperties.go | 31 - ...gurationstorepropertiesupdateparameters.go | 9 - ...odel_configurationstoreupdateparameters.go | 15 - .../model_encryptionproperties.go | 8 - .../configurationstores/model_keyvalue.go | 33 - .../model_keyvaultproperties.go | 9 - .../model_listkeyvalueparameters.go | 9 - .../model_privateendpoint.go | 8 - ...del_privateendpointconnectionproperties.go | 10 - ...odel_privateendpointconnectionreference.go | 11 - ...model_privatelinkserviceconnectionstate.go | 10 - .../model_regeneratekeyparameters.go | 8 - .../configurationstores/model_sku.go | 8 - .../configurationstores/predicates.go | 67 - .../2020-06-01/configurationstores/version.go | 12 - ...ryconfigschecknameavailability_autorest.go | 69 + ...pertiesregistrationdefinitionproperties.go | 15 + .../hashicorp/terraform-exec/tfexec/add.go | 101 - .../terraform-exec/tfexec/cmdstring.go | 12 - .../terraform-exec/tfexec/cmdstring_go112.go | 19 - .../tfprotov5/internal/tfplugin5/generate.sh | 16 - .../tfprotov6/internal/tfplugin6/generate.sh | 16 - .../configs/hcl2shim/single_attr_body.go | 85 - .../github.com/mattn/go-colorable/.travis.yml | 15 - vendor/github.com/mattn/go-isatty/.travis.yml | 14 - .../grpc/credentials/go12.go | 30 - vendor/google.golang.org/grpc/install_gae.sh | 6 - .../internal/credentials/spiffe_appengine.go | 31 - .../credentials/syscallconn_appengine.go | 30 - .../grpc/internal/grpcutil/target.go | 89 - .../grpc/internal/resolver/dns/go113.go | 33 - 182 files changed, 125 insertions(+), 77367 deletions(-) delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/_meta.json delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/containergroups.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/containers.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/enums.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/location.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/models.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/operations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/version.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/_meta.json delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/attacheddatabaseconfigurations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/clusterprincipalassignments.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/clusters.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/databaseprincipalassignments.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/databases.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/dataconnections.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/enums.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/managedprivateendpoints.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/models.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/operations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/operationsresults.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/privateendpointconnections.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/privatelinkresources.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/scripts.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/version.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/_meta.json delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/enums.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/models.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/operations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/registrationassignments.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/registrationdefinitions.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/version.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/_meta.json delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/accountbackups.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/accounts.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/backuppolicies.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/backups.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/enums.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/models.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/operations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/pools.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/resource.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/resourcequotalimits.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/snapshotpolicies.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/snapshots.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/subvolumes.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/vaults.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/version.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/volumegroups.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/volumes.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/_meta.json delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apiportalcustomdomains.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apiportals.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apps.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/bindings.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildpackbinding.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildservice.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildserviceagentpool.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildservicebuilder.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/certificates.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/configservers.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/configurationservices.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/customdomains.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/deployments.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/enums.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gatewaycustomdomains.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gatewayrouteconfigs.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gateways.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/models.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/monitoringsettings.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/operations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/runtimeversions.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/serviceregistries.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/services.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/skus.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/storages.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/version.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/_meta.json delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/enums.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/models.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/operations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policyevents.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policymetadata.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policystates.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policytrackedresources.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/remediations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/version.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/_meta.json delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/dashboards.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/models.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/operations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/tenantconfigurations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/version.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/CHANGELOG.md delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/_meta.json delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/disasterrecoveryconfigs.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/enums.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/migrationconfigs.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/models.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/namespaces.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/operations.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/privateendpointconnections.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/privatelinkresources.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/queues.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/rules.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/subscriptions.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/topics.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/version.go delete mode 100644 vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/README.md delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/client.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/constants.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/id_configurationstore.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_create_autorest.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_delete_autorest.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_get_autorest.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_list_autorest.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listbyresourcegroup_autorest.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listkeys_autorest.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listkeyvalue_autorest.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_regeneratekey_autorest.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_update_autorest.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_apikey.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstore.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstoreproperties.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstorepropertiesupdateparameters.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstoreupdateparameters.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_encryptionproperties.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_keyvalue.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_keyvaultproperties.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_listkeyvalueparameters.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpoint.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpointconnectionproperties.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpointconnectionreference.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privatelinkserviceconnectionstate.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_regeneratekeyparameters.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_sku.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/predicates.go delete mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/version.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/method_disasterrecoveryconfigschecknameavailability_autorest.go create mode 100644 vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentpropertiesregistrationdefinitionproperties.go delete mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/add.go delete mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/cmdstring.go delete mode 100644 vendor/github.com/hashicorp/terraform-exec/tfexec/cmdstring_go112.go delete mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/generate.sh delete mode 100644 vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/generate.sh delete mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/single_attr_body.go delete mode 100644 vendor/github.com/mattn/go-colorable/.travis.yml delete mode 100644 vendor/github.com/mattn/go-isatty/.travis.yml delete mode 100644 vendor/google.golang.org/grpc/credentials/go12.go delete mode 100644 vendor/google.golang.org/grpc/install_gae.sh delete mode 100644 vendor/google.golang.org/grpc/internal/credentials/spiffe_appengine.go delete mode 100644 vendor/google.golang.org/grpc/internal/credentials/syscallconn_appengine.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/target.go delete mode 100644 vendor/google.golang.org/grpc/internal/resolver/dns/go113.go diff --git a/internal/services/signalr/client/client.go b/internal/services/signalr/client/client.go index 21bd031df0f1..b2bc565fce27 100644 --- a/internal/services/signalr/client/client.go +++ b/internal/services/signalr/client/client.go @@ -2,8 +2,8 @@ package client import ( "github.com/Azure/azure-sdk-for-go/services/webpubsub/mgmt/2021-10-01/webpubsub" + "github.com/hashicorp/go-azure-sdk/resource-manager/signalr/2022-02-01/signalr" "github.com/hashicorp/terraform-provider-azurerm/internal/common" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/signalr/sdk/2020-05-01/signalr" ) type Client struct { diff --git a/internal/services/signalr/parse/web_pubsub.go b/internal/services/signalr/parse/web_pubsub.go index 5bfe2e5e64ef..532d5b9462ec 100644 --- a/internal/services/signalr/parse/web_pubsub.go +++ b/internal/services/signalr/parse/web_pubsub.go @@ -33,7 +33,7 @@ func (id WebPubsubId) String() string { } func (id WebPubsubId) ID() string { - fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/WebPubSub/%s" + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/webPubSub/%s" return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.WebPubSubName) } @@ -57,7 +57,7 @@ func WebPubsubID(input string) (*WebPubsubId, error) { return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") } - if resourceId.WebPubSubName, err = id.PopSegment("WebPubSub"); err != nil { + if resourceId.WebPubSubName, err = id.PopSegment("webPubSub"); err != nil { return nil, err } diff --git a/internal/services/signalr/parse/web_pubsub_hub.go b/internal/services/signalr/parse/web_pubsub_hub.go index 619a9ea87809..5550771b412d 100644 --- a/internal/services/signalr/parse/web_pubsub_hub.go +++ b/internal/services/signalr/parse/web_pubsub_hub.go @@ -36,7 +36,7 @@ func (id WebPubsubHubId) String() string { } func (id WebPubsubHubId) ID() string { - fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/WebPubSub/%s/hubs/%s" + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/webPubSub/%s/hubs/%s" return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.WebPubSubName, id.HubName) } @@ -60,7 +60,7 @@ func WebPubsubHubID(input string) (*WebPubsubHubId, error) { return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") } - if resourceId.WebPubSubName, err = id.PopSegment("WebPubSub"); err != nil { + if resourceId.WebPubSubName, err = id.PopSegment("webPubSub"); err != nil { return nil, err } if resourceId.HubName, err = id.PopSegment("hubs"); err != nil { diff --git a/internal/services/signalr/parse/web_pubsub_hub_test.go b/internal/services/signalr/parse/web_pubsub_hub_test.go index ca3f00a09599..0dff2dd75b38 100644 --- a/internal/services/signalr/parse/web_pubsub_hub_test.go +++ b/internal/services/signalr/parse/web_pubsub_hub_test.go @@ -12,7 +12,7 @@ var _ resourceids.Id = WebPubsubHubId{} func TestWebPubsubHubIDFormatter(t *testing.T) { actual := NewWebPubsubHubID("12345678-1234-9876-4563-123456789012", "resGroup1", "Webpubsub1", "Webpubsubhub1").ID() - expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/hubs/Webpubsubhub1" + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/hubs/Webpubsubhub1" if actual != expected { t.Fatalf("Expected %q but got %q", expected, actual) } @@ -63,25 +63,25 @@ func TestWebPubsubHubID(t *testing.T) { { // missing value for WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/", Error: true, }, { // missing HubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/", Error: true, }, { // missing value for HubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/hubs/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/hubs/", Error: true, }, { // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/hubs/Webpubsubhub1", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/hubs/Webpubsubhub1", Expected: &WebPubsubHubId{ SubscriptionId: "12345678-1234-9876-4563-123456789012", ResourceGroup: "resGroup1", diff --git a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go index 4d7958bc9372..f96e7c776aa6 100644 --- a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go +++ b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource.go @@ -36,7 +36,7 @@ func (id WebPubsubSharedPrivateLinkResourceId) String() string { } func (id WebPubsubSharedPrivateLinkResourceId) ID() string { - fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/WebPubSub/%s/sharedPrivateLinkResources/%s" + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.SignalRService/webPubSub/%s/sharedPrivateLinkResources/%s" return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.WebPubSubName, id.SharedPrivateLinkResourceName) } @@ -60,7 +60,7 @@ func WebPubsubSharedPrivateLinkResourceID(input string) (*WebPubsubSharedPrivate return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") } - if resourceId.WebPubSubName, err = id.PopSegment("WebPubSub"); err != nil { + if resourceId.WebPubSubName, err = id.PopSegment("webPubSub"); err != nil { return nil, err } if resourceId.SharedPrivateLinkResourceName, err = id.PopSegment("sharedPrivateLinkResources"); err != nil { diff --git a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go index 7d94bdce4738..c4f3c6a6c188 100644 --- a/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go +++ b/internal/services/signalr/parse/web_pubsub_shared_private_link_resource_test.go @@ -12,7 +12,7 @@ var _ resourceids.Id = WebPubsubSharedPrivateLinkResourceId{} func TestWebPubsubSharedPrivateLinkResourceIDFormatter(t *testing.T) { actual := NewWebPubsubSharedPrivateLinkResourceID("12345678-1234-9876-4563-123456789012", "resGroup1", "Webpubsub1", "resource1").ID() - expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1" + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/sharedPrivateLinkResources/resource1" if actual != expected { t.Fatalf("Expected %q but got %q", expected, actual) } @@ -63,25 +63,25 @@ func TestWebPubsubSharedPrivateLinkResourceID(t *testing.T) { { // missing value for WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/", Error: true, }, { // missing SharedPrivateLinkResourceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/", Error: true, }, { // missing value for SharedPrivateLinkResourceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/sharedPrivateLinkResources/", Error: true, }, { // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", Expected: &WebPubsubSharedPrivateLinkResourceId{ SubscriptionId: "12345678-1234-9876-4563-123456789012", ResourceGroup: "resGroup1", diff --git a/internal/services/signalr/parse/web_pubsub_test.go b/internal/services/signalr/parse/web_pubsub_test.go index 9e286529d3b0..c2fcc4350570 100644 --- a/internal/services/signalr/parse/web_pubsub_test.go +++ b/internal/services/signalr/parse/web_pubsub_test.go @@ -12,7 +12,7 @@ var _ resourceids.Id = WebPubsubId{} func TestWebPubsubIDFormatter(t *testing.T) { actual := NewWebPubsubID("12345678-1234-9876-4563-123456789012", "resGroup1", "Webpubsub1").ID() - expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1" + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1" if actual != expected { t.Fatalf("Expected %q but got %q", expected, actual) } @@ -63,13 +63,13 @@ func TestWebPubsubID(t *testing.T) { { // missing value for WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/", Error: true, }, { // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1", Expected: &WebPubsubId{ SubscriptionId: "12345678-1234-9876-4563-123456789012", ResourceGroup: "resGroup1", diff --git a/internal/services/signalr/resourceids.go b/internal/services/signalr/resourceids.go index c0a0850c9c54..6e26df08a2da 100644 --- a/internal/services/signalr/resourceids.go +++ b/internal/services/signalr/resourceids.go @@ -1,5 +1,5 @@ package signalr -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1 -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubHub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/hubs/Webpubsubhub1 -//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubSharedPrivateLinkResource -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1 +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1 +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubHub -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/hubs/Webpubsubhub1 +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=WebPubsubSharedPrivateLinkResource -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/sharedPrivateLinkResources/resource1 diff --git a/internal/services/signalr/validate/web_pubsub_hub_id_test.go b/internal/services/signalr/validate/web_pubsub_hub_id_test.go index 378cfd76e23c..d37a736e98f5 100644 --- a/internal/services/signalr/validate/web_pubsub_hub_id_test.go +++ b/internal/services/signalr/validate/web_pubsub_hub_id_test.go @@ -48,25 +48,25 @@ func TestWebPubsubHubID(t *testing.T) { { // missing value for WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/", Valid: false, }, { // missing HubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/", Valid: false, }, { // missing value for HubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/hubs/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/hubs/", Valid: false, }, { // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/hubs/Webpubsubhub1", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/hubs/Webpubsubhub1", Valid: true, }, diff --git a/internal/services/signalr/validate/web_pubsub_id_test.go b/internal/services/signalr/validate/web_pubsub_id_test.go index 2138c415fe3c..722e8ef3e912 100644 --- a/internal/services/signalr/validate/web_pubsub_id_test.go +++ b/internal/services/signalr/validate/web_pubsub_id_test.go @@ -48,13 +48,13 @@ func TestWebPubsubID(t *testing.T) { { // missing value for WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/", Valid: false, }, { // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1", Valid: true, }, diff --git a/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go b/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go index 70cc51a2da70..fa247d5d6ee8 100644 --- a/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go +++ b/internal/services/signalr/validate/web_pubsub_shared_private_link_resource_id_test.go @@ -48,25 +48,25 @@ func TestWebPubsubSharedPrivateLinkResourceID(t *testing.T) { { // missing value for WebPubSubName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/", Valid: false, }, { // missing SharedPrivateLinkResourceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/", Valid: false, }, { // missing value for SharedPrivateLinkResourceName - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/sharedPrivateLinkResources/", Valid: false, }, { // valid - Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/WebPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resGroup1/providers/Microsoft.SignalRService/webPubSub/Webpubsub1/sharedPrivateLinkResources/resource1", Valid: true, }, diff --git a/internal/services/signalr/web_pubsub_network_acl_resource_test.go b/internal/services/signalr/web_pubsub_network_acl_resource_test.go index 1d2fe0f173b1..ed4702183399 100644 --- a/internal/services/signalr/web_pubsub_network_acl_resource_test.go +++ b/internal/services/signalr/web_pubsub_network_acl_resource_test.go @@ -327,7 +327,11 @@ resource "azurerm_web_pubsub_network_acl" "test" { func (r WebPubsubNetworkACLResource) template(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { - features {} + features { + resource_group { + prevent_deletion_if_contains_resources = false + } + } } resource "azurerm_resource_group" "test" { diff --git a/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go b/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go index 2c14c1bea544..d7712163e892 100644 --- a/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go +++ b/internal/services/signalr/web_pubsub_shared_private_link_resource_test.go @@ -78,15 +78,15 @@ resource "azurerm_key_vault" "test" { object_id = data.azurerm_client_config.current.object_id certificate_permissions = [ - "managecontacts", + "ManageContacts", ] key_permissions = [ - "create", + "Create", ] secret_permissions = [ - "set", + "Set", ] } } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/CHANGELOG.md deleted file mode 100644 index 52911e4cc5e4..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/_meta.json deleted file mode 100644 index 5bf1ae599a33..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "e9a6009d8f1a98656cf5b6f1fe5809251bfa0085", - "readme": "/_/azure-rest-api-specs/specification/containerinstance/resource-manager/readme.md", - "tag": "package-2021-03", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-2021-03 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix /_/azure-rest-api-specs/specification/containerinstance/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/client.go deleted file mode 100644 index 48ebb63f1463..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/client.go +++ /dev/null @@ -1,41 +0,0 @@ -// Package containerinstance implements the Azure ARM Containerinstance service API version 2021-03-01. -// -// -package containerinstance - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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 Containerinstance - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Containerinstance. -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 using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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/containerinstance/mgmt/2021-03-01/containerinstance/containergroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/containergroups.go deleted file mode 100644 index 24edd5e539a7..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/containergroups.go +++ /dev/null @@ -1,844 +0,0 @@ -package containerinstance - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ContainerGroupsClient is the client for the ContainerGroups methods of the Containerinstance service. -type ContainerGroupsClient struct { - BaseClient -} - -// NewContainerGroupsClient creates an instance of the ContainerGroupsClient client. -func NewContainerGroupsClient(subscriptionID string) ContainerGroupsClient { - return NewContainerGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewContainerGroupsClientWithBaseURI creates an instance of the ContainerGroupsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewContainerGroupsClientWithBaseURI(baseURI string, subscriptionID string) ContainerGroupsClient { - return ContainerGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update container groups with specified configurations. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -// containerGroup - the properties of the container group to be created or updated. -func (client ContainerGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, containerGroupName string, containerGroup ContainerGroup) (result ContainerGroupsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: containerGroup, - Constraints: []validation.Constraint{{Target: "containerGroup.ContainerGroupProperties", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "containerGroup.ContainerGroupProperties.Containers", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "containerGroup.ContainerGroupProperties.IPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "containerGroup.ContainerGroupProperties.IPAddress.Ports", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "containerGroup.ContainerGroupProperties.Diagnostics", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "containerGroup.ContainerGroupProperties.Diagnostics.LogAnalytics", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "containerGroup.ContainerGroupProperties.Diagnostics.LogAnalytics.WorkspaceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "containerGroup.ContainerGroupProperties.Diagnostics.LogAnalytics.WorkspaceKey", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}, - {Target: "containerGroup.ContainerGroupProperties.NetworkProfile", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "containerGroup.ContainerGroupProperties.NetworkProfile.ID", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "containerGroup.ContainerGroupProperties.DNSConfig", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "containerGroup.ContainerGroupProperties.DNSConfig.NameServers", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "containerGroup.ContainerGroupProperties.EncryptionProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "containerGroup.ContainerGroupProperties.EncryptionProperties.VaultBaseURL", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "containerGroup.ContainerGroupProperties.EncryptionProperties.KeyName", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "containerGroup.ContainerGroupProperties.EncryptionProperties.KeyVersion", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("containerinstance.ContainerGroupsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, containerGroupName, containerGroup) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ContainerGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, containerGroupName string, containerGroup ContainerGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-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.ContainerInstance/containerGroups/{containerGroupName}", pathParameters), - autorest.WithJSON(containerGroup), - 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 ContainerGroupsClient) CreateOrUpdateSender(req *http.Request) (future ContainerGroupsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ContainerGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result ContainerGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the specified container group in the specified subscription and resource group. The operation does not -// delete other resources provided by the user, such as volumes. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -func (client ContainerGroupsClient) Delete(ctx context.Context, resourceGroupName string, containerGroupName string) (result ContainerGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, containerGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ContainerGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, containerGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-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.ContainerInstance/containerGroups/{containerGroupName}", 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 ContainerGroupsClient) DeleteSender(req *http.Request) (future ContainerGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ContainerGroupsClient) DeleteResponder(resp *http.Response) (result ContainerGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get gets the properties of the specified container group in the specified subscription and resource group. The -// operation returns the properties of each container group including containers, image registry credentials, restart -// policy, IP address type, OS type, state, and volumes. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -func (client ContainerGroupsClient) Get(ctx context.Context, resourceGroupName string, containerGroupName string) (result ContainerGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, containerGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ContainerGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, containerGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-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.ContainerInstance/containerGroups/{containerGroupName}", 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 ContainerGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ContainerGroupsClient) GetResponder(resp *http.Response) (result ContainerGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List get a list of container groups in the specified subscription. This operation returns properties of each -// container group including containers, image registry credentials, restart policy, IP address type, OS type, state, -// and volumes. -func (client ContainerGroupsClient) List(ctx context.Context) (result ContainerGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.List") - defer func() { - sc := -1 - if result.cglr.Response.Response != nil { - sc = result.cglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.cglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "List", resp, "Failure sending request") - return - } - - result.cglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "List", resp, "Failure responding to request") - return - } - if result.cglr.hasNextLink() && result.cglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ContainerGroupsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/containerGroups", 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 ContainerGroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ContainerGroupsClient) ListResponder(resp *http.Response) (result ContainerGroupListResult, err error) { - err = autorest.Respond( - resp, - 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 ContainerGroupsClient) listNextResults(ctx context.Context, lastResults ContainerGroupListResult) (result ContainerGroupListResult, err error) { - req, err := lastResults.containerGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "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, "containerinstance.ContainerGroupsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ContainerGroupsClient) ListComplete(ctx context.Context) (result ContainerGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup get a list of container groups in a specified subscription and resource group. This operation -// returns properties of each container group including containers, image registry credentials, restart policy, IP -// address type, OS type, state, and volumes. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ContainerGroupsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ContainerGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.cglr.Response.Response != nil { - sc = result.cglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.cglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.cglr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.cglr.hasNextLink() && result.cglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ContainerGroupsClient) 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 = "2021-03-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.ContainerInstance/containerGroups", 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 ContainerGroupsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ContainerGroupsClient) ListByResourceGroupResponder(resp *http.Response) (result ContainerGroupListResult, err error) { - err = autorest.Respond( - resp, - 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 ContainerGroupsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ContainerGroupListResult) (result ContainerGroupListResult, err error) { - req, err := lastResults.containerGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "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, "containerinstance.ContainerGroupsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ContainerGroupsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ContainerGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// Restart restarts all containers in a container group in place. If container image has updates, new image will be -// downloaded. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -func (client ContainerGroupsClient) Restart(ctx context.Context, resourceGroupName string, containerGroupName string) (result ContainerGroupsRestartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.Restart") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RestartPreparer(ctx, resourceGroupName, containerGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Restart", nil, "Failure preparing request") - return - } - - result, err = client.RestartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Restart", result.Response(), "Failure sending request") - return - } - - return -} - -// RestartPreparer prepares the Restart request. -func (client ContainerGroupsClient) RestartPreparer(ctx context.Context, resourceGroupName string, containerGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-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.ContainerInstance/containerGroups/{containerGroupName}/restart", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RestartSender sends the Restart request. The method will close the -// http.Response Body if it receives an error. -func (client ContainerGroupsClient) RestartSender(req *http.Request) (future ContainerGroupsRestartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RestartResponder handles the response to the Restart request. The method always -// closes the http.Response Body. -func (client ContainerGroupsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Start starts all containers in a container group. Compute resources will be allocated and billing will start. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -func (client ContainerGroupsClient) Start(ctx context.Context, resourceGroupName string, containerGroupName string) (result ContainerGroupsStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, containerGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client ContainerGroupsClient) StartPreparer(ctx context.Context, resourceGroupName string, containerGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-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.ContainerInstance/containerGroups/{containerGroupName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client ContainerGroupsClient) StartSender(req *http.Request) (future ContainerGroupsStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client ContainerGroupsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Stop stops all containers in a container group. Compute resources will be deallocated and billing will stop. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -func (client ContainerGroupsClient) Stop(ctx context.Context, resourceGroupName string, containerGroupName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.Stop") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, containerGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Stop", nil, "Failure preparing request") - return - } - - resp, err := client.StopSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Stop", resp, "Failure sending request") - return - } - - result, err = client.StopResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Stop", resp, "Failure responding to request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client ContainerGroupsClient) StopPreparer(ctx context.Context, resourceGroupName string, containerGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-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.ContainerInstance/containerGroups/{containerGroupName}/stop", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopSender sends the Stop request. The method will close the -// http.Response Body if it receives an error. -func (client ContainerGroupsClient) StopSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// StopResponder handles the response to the Stop request. The method always -// closes the http.Response Body. -func (client ContainerGroupsClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update updates container group tags with specified values. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -// resource - the container group resource with just the tags to be updated. -func (client ContainerGroupsClient) Update(ctx context.Context, resourceGroupName string, containerGroupName string, resource Resource) (result ContainerGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupsClient.Update") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, containerGroupName, resource) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Update", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Update", resp, "Failure sending request") - return - } - - result, err = client.UpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsClient", "Update", resp, "Failure responding to request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ContainerGroupsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, containerGroupName string, resource Resource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - resource.ID = nil - resource.Name = nil - resource.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}", pathParameters), - autorest.WithJSON(resource), - 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 ContainerGroupsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ContainerGroupsClient) UpdateResponder(resp *http.Response) (result ContainerGroup, err error) { - err = autorest.Respond( - resp, - 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/containerinstance/mgmt/2021-03-01/containerinstance/containers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/containers.go deleted file mode 100644 index 8fbdcba24fbc..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/containers.go +++ /dev/null @@ -1,280 +0,0 @@ -package containerinstance - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// ContainersClient is the client for the Containers methods of the Containerinstance service. -type ContainersClient struct { - BaseClient -} - -// NewContainersClient creates an instance of the ContainersClient client. -func NewContainersClient(subscriptionID string) ContainersClient { - return NewContainersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewContainersClientWithBaseURI creates an instance of the ContainersClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewContainersClientWithBaseURI(baseURI string, subscriptionID string) ContainersClient { - return ContainersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Attach attach to the output stream of a specific container instance in a specified resource group and container -// group. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -// containerName - the name of the container instance. -func (client ContainersClient) Attach(ctx context.Context, resourceGroupName string, containerGroupName string, containerName string) (result ContainerAttachResponse, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainersClient.Attach") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.AttachPreparer(ctx, resourceGroupName, containerGroupName, containerName) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainersClient", "Attach", nil, "Failure preparing request") - return - } - - resp, err := client.AttachSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.ContainersClient", "Attach", resp, "Failure sending request") - return - } - - result, err = client.AttachResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainersClient", "Attach", resp, "Failure responding to request") - return - } - - return -} - -// AttachPreparer prepares the Attach request. -func (client ContainersClient) AttachPreparer(ctx context.Context, resourceGroupName string, containerGroupName string, containerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "containerName": autorest.Encode("path", containerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-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.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/attach", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// AttachSender sends the Attach request. The method will close the -// http.Response Body if it receives an error. -func (client ContainersClient) AttachSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// AttachResponder handles the response to the Attach request. The method always -// closes the http.Response Body. -func (client ContainersClient) AttachResponder(resp *http.Response) (result ContainerAttachResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ExecuteCommand executes a command for a specific container instance in a specified resource group and container -// group. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -// containerName - the name of the container instance. -// containerExecRequest - the request for the exec command. -func (client ContainersClient) ExecuteCommand(ctx context.Context, resourceGroupName string, containerGroupName string, containerName string, containerExecRequest ContainerExecRequest) (result ContainerExecResponse, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainersClient.ExecuteCommand") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ExecuteCommandPreparer(ctx, resourceGroupName, containerGroupName, containerName, containerExecRequest) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainersClient", "ExecuteCommand", nil, "Failure preparing request") - return - } - - resp, err := client.ExecuteCommandSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.ContainersClient", "ExecuteCommand", resp, "Failure sending request") - return - } - - result, err = client.ExecuteCommandResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainersClient", "ExecuteCommand", resp, "Failure responding to request") - return - } - - return -} - -// ExecuteCommandPreparer prepares the ExecuteCommand request. -func (client ContainersClient) ExecuteCommandPreparer(ctx context.Context, resourceGroupName string, containerGroupName string, containerName string, containerExecRequest ContainerExecRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "containerName": autorest.Encode("path", containerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-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.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/exec", pathParameters), - autorest.WithJSON(containerExecRequest), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ExecuteCommandSender sends the ExecuteCommand request. The method will close the -// http.Response Body if it receives an error. -func (client ContainersClient) ExecuteCommandSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ExecuteCommandResponder handles the response to the ExecuteCommand request. The method always -// closes the http.Response Body. -func (client ContainersClient) ExecuteCommandResponder(resp *http.Response) (result ContainerExecResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListLogs get the logs for a specified container instance in a specified resource group and container group. -// Parameters: -// resourceGroupName - the name of the resource group. -// containerGroupName - the name of the container group. -// containerName - the name of the container instance. -// tail - the number of lines to show from the tail of the container instance log. If not provided, all -// available logs are shown up to 4mb. -// timestamps - if true, adds a timestamp at the beginning of every line of log output. If not provided, -// defaults to false. -func (client ContainersClient) ListLogs(ctx context.Context, resourceGroupName string, containerGroupName string, containerName string, tail *int32, timestamps *bool) (result Logs, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainersClient.ListLogs") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListLogsPreparer(ctx, resourceGroupName, containerGroupName, containerName, tail, timestamps) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainersClient", "ListLogs", nil, "Failure preparing request") - return - } - - resp, err := client.ListLogsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.ContainersClient", "ListLogs", resp, "Failure sending request") - return - } - - result, err = client.ListLogsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainersClient", "ListLogs", resp, "Failure responding to request") - return - } - - return -} - -// ListLogsPreparer prepares the ListLogs request. -func (client ContainersClient) ListLogsPreparer(ctx context.Context, resourceGroupName string, containerGroupName string, containerName string, tail *int32, timestamps *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerGroupName": autorest.Encode("path", containerGroupName), - "containerName": autorest.Encode("path", containerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if tail != nil { - queryParameters["tail"] = autorest.Encode("query", *tail) - } - if timestamps != nil { - queryParameters["timestamps"] = autorest.Encode("query", *timestamps) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/containers/{containerName}/logs", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListLogsSender sends the ListLogs request. The method will close the -// http.Response Body if it receives an error. -func (client ContainersClient) ListLogsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListLogsResponder handles the response to the ListLogs request. The method always -// closes the http.Response Body. -func (client ContainersClient) ListLogsResponder(resp *http.Response) (result Logs, err error) { - err = autorest.Respond( - resp, - 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/containerinstance/mgmt/2021-03-01/containerinstance/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/enums.go deleted file mode 100644 index 9396340601e8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/enums.go +++ /dev/null @@ -1,180 +0,0 @@ -package containerinstance - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// ContainerGroupIPAddressType enumerates the values for container group ip address type. -type ContainerGroupIPAddressType string - -const ( - // ContainerGroupIPAddressTypePrivate ... - ContainerGroupIPAddressTypePrivate ContainerGroupIPAddressType = "Private" - // ContainerGroupIPAddressTypePublic ... - ContainerGroupIPAddressTypePublic ContainerGroupIPAddressType = "Public" -) - -// PossibleContainerGroupIPAddressTypeValues returns an array of possible values for the ContainerGroupIPAddressType const type. -func PossibleContainerGroupIPAddressTypeValues() []ContainerGroupIPAddressType { - return []ContainerGroupIPAddressType{ContainerGroupIPAddressTypePrivate, ContainerGroupIPAddressTypePublic} -} - -// ContainerGroupNetworkProtocol enumerates the values for container group network protocol. -type ContainerGroupNetworkProtocol string - -const ( - // ContainerGroupNetworkProtocolTCP ... - ContainerGroupNetworkProtocolTCP ContainerGroupNetworkProtocol = "TCP" - // ContainerGroupNetworkProtocolUDP ... - ContainerGroupNetworkProtocolUDP ContainerGroupNetworkProtocol = "UDP" -) - -// PossibleContainerGroupNetworkProtocolValues returns an array of possible values for the ContainerGroupNetworkProtocol const type. -func PossibleContainerGroupNetworkProtocolValues() []ContainerGroupNetworkProtocol { - return []ContainerGroupNetworkProtocol{ContainerGroupNetworkProtocolTCP, ContainerGroupNetworkProtocolUDP} -} - -// ContainerGroupRestartPolicy enumerates the values for container group restart policy. -type ContainerGroupRestartPolicy string - -const ( - // ContainerGroupRestartPolicyAlways ... - ContainerGroupRestartPolicyAlways ContainerGroupRestartPolicy = "Always" - // ContainerGroupRestartPolicyNever ... - ContainerGroupRestartPolicyNever ContainerGroupRestartPolicy = "Never" - // ContainerGroupRestartPolicyOnFailure ... - ContainerGroupRestartPolicyOnFailure ContainerGroupRestartPolicy = "OnFailure" -) - -// PossibleContainerGroupRestartPolicyValues returns an array of possible values for the ContainerGroupRestartPolicy const type. -func PossibleContainerGroupRestartPolicyValues() []ContainerGroupRestartPolicy { - return []ContainerGroupRestartPolicy{ContainerGroupRestartPolicyAlways, ContainerGroupRestartPolicyNever, ContainerGroupRestartPolicyOnFailure} -} - -// ContainerGroupSku enumerates the values for container group sku. -type ContainerGroupSku string - -const ( - // ContainerGroupSkuDedicated ... - ContainerGroupSkuDedicated ContainerGroupSku = "Dedicated" - // ContainerGroupSkuStandard ... - ContainerGroupSkuStandard ContainerGroupSku = "Standard" -) - -// PossibleContainerGroupSkuValues returns an array of possible values for the ContainerGroupSku const type. -func PossibleContainerGroupSkuValues() []ContainerGroupSku { - return []ContainerGroupSku{ContainerGroupSkuDedicated, ContainerGroupSkuStandard} -} - -// ContainerNetworkProtocol enumerates the values for container network protocol. -type ContainerNetworkProtocol string - -const ( - // ContainerNetworkProtocolTCP ... - ContainerNetworkProtocolTCP ContainerNetworkProtocol = "TCP" - // ContainerNetworkProtocolUDP ... - ContainerNetworkProtocolUDP ContainerNetworkProtocol = "UDP" -) - -// PossibleContainerNetworkProtocolValues returns an array of possible values for the ContainerNetworkProtocol const type. -func PossibleContainerNetworkProtocolValues() []ContainerNetworkProtocol { - return []ContainerNetworkProtocol{ContainerNetworkProtocolTCP, ContainerNetworkProtocolUDP} -} - -// GpuSku enumerates the values for gpu sku. -type GpuSku string - -const ( - // GpuSkuK80 ... - GpuSkuK80 GpuSku = "K80" - // GpuSkuP100 ... - GpuSkuP100 GpuSku = "P100" - // GpuSkuV100 ... - GpuSkuV100 GpuSku = "V100" -) - -// PossibleGpuSkuValues returns an array of possible values for the GpuSku const type. -func PossibleGpuSkuValues() []GpuSku { - return []GpuSku{GpuSkuK80, GpuSkuP100, GpuSkuV100} -} - -// LogAnalyticsLogType enumerates the values for log analytics log type. -type LogAnalyticsLogType string - -const ( - // LogAnalyticsLogTypeContainerInsights ... - LogAnalyticsLogTypeContainerInsights LogAnalyticsLogType = "ContainerInsights" - // LogAnalyticsLogTypeContainerInstanceLogs ... - LogAnalyticsLogTypeContainerInstanceLogs LogAnalyticsLogType = "ContainerInstanceLogs" -) - -// PossibleLogAnalyticsLogTypeValues returns an array of possible values for the LogAnalyticsLogType const type. -func PossibleLogAnalyticsLogTypeValues() []LogAnalyticsLogType { - return []LogAnalyticsLogType{LogAnalyticsLogTypeContainerInsights, LogAnalyticsLogTypeContainerInstanceLogs} -} - -// OperatingSystemTypes enumerates the values for operating system types. -type OperatingSystemTypes string - -const ( - // OperatingSystemTypesLinux ... - OperatingSystemTypesLinux OperatingSystemTypes = "Linux" - // OperatingSystemTypesWindows ... - OperatingSystemTypesWindows OperatingSystemTypes = "Windows" -) - -// PossibleOperatingSystemTypesValues returns an array of possible values for the OperatingSystemTypes const type. -func PossibleOperatingSystemTypesValues() []OperatingSystemTypes { - return []OperatingSystemTypes{OperatingSystemTypesLinux, OperatingSystemTypesWindows} -} - -// OperationsOrigin enumerates the values for operations origin. -type OperationsOrigin string - -const ( - // OperationsOriginSystem ... - OperationsOriginSystem OperationsOrigin = "System" - // OperationsOriginUser ... - OperationsOriginUser OperationsOrigin = "User" -) - -// PossibleOperationsOriginValues returns an array of possible values for the OperationsOrigin const type. -func PossibleOperationsOriginValues() []OperationsOrigin { - return []OperationsOrigin{OperationsOriginSystem, OperationsOriginUser} -} - -// ResourceIdentityType enumerates the values for resource identity type. -type ResourceIdentityType string - -const ( - // ResourceIdentityTypeNone ... - ResourceIdentityTypeNone ResourceIdentityType = "None" - // ResourceIdentityTypeSystemAssigned ... - ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" - // ResourceIdentityTypeSystemAssignedUserAssigned ... - ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" - // ResourceIdentityTypeUserAssigned ... - ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" -) - -// PossibleResourceIdentityTypeValues returns an array of possible values for the ResourceIdentityType const type. -func PossibleResourceIdentityTypeValues() []ResourceIdentityType { - return []ResourceIdentityType{ResourceIdentityTypeNone, ResourceIdentityTypeSystemAssigned, ResourceIdentityTypeSystemAssignedUserAssigned, ResourceIdentityTypeUserAssigned} -} - -// Scheme enumerates the values for scheme. -type Scheme string - -const ( - // SchemeHTTP ... - SchemeHTTP Scheme = "http" - // SchemeHTTPS ... - SchemeHTTPS Scheme = "https" -) - -// PossibleSchemeValues returns an array of possible values for the Scheme const type. -func PossibleSchemeValues() []Scheme { - return []Scheme{SchemeHTTP, SchemeHTTPS} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/location.go b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/location.go deleted file mode 100644 index c9c64af27a60..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/location.go +++ /dev/null @@ -1,337 +0,0 @@ -package containerinstance - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// LocationClient is the client for the Location methods of the Containerinstance service. -type LocationClient struct { - BaseClient -} - -// NewLocationClient creates an instance of the LocationClient client. -func NewLocationClient(subscriptionID string) LocationClient { - return NewLocationClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLocationClientWithBaseURI creates an instance of the LocationClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewLocationClientWithBaseURI(baseURI string, subscriptionID string) LocationClient { - return LocationClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// ListCachedImages get the list of cached images on specific OS type for a subscription in a region. -// Parameters: -// location - the identifier for the physical azure location. -func (client LocationClient) ListCachedImages(ctx context.Context, location string) (result CachedImagesListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocationClient.ListCachedImages") - defer func() { - sc := -1 - if result.cilr.Response.Response != nil { - sc = result.cilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listCachedImagesNextResults - req, err := client.ListCachedImagesPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "ListCachedImages", nil, "Failure preparing request") - return - } - - resp, err := client.ListCachedImagesSender(req) - if err != nil { - result.cilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "ListCachedImages", resp, "Failure sending request") - return - } - - result.cilr, err = client.ListCachedImagesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "ListCachedImages", resp, "Failure responding to request") - return - } - if result.cilr.hasNextLink() && result.cilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListCachedImagesPreparer prepares the ListCachedImages request. -func (client LocationClient) ListCachedImagesPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/cachedImages", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListCachedImagesSender sends the ListCachedImages request. The method will close the -// http.Response Body if it receives an error. -func (client LocationClient) ListCachedImagesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListCachedImagesResponder handles the response to the ListCachedImages request. The method always -// closes the http.Response Body. -func (client LocationClient) ListCachedImagesResponder(resp *http.Response) (result CachedImagesListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listCachedImagesNextResults retrieves the next set of results, if any. -func (client LocationClient) listCachedImagesNextResults(ctx context.Context, lastResults CachedImagesListResult) (result CachedImagesListResult, err error) { - req, err := lastResults.cachedImagesListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "containerinstance.LocationClient", "listCachedImagesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListCachedImagesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerinstance.LocationClient", "listCachedImagesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListCachedImagesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "listCachedImagesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListCachedImagesComplete enumerates all values, automatically crossing page boundaries as required. -func (client LocationClient) ListCachedImagesComplete(ctx context.Context, location string) (result CachedImagesListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocationClient.ListCachedImages") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListCachedImages(ctx, location) - return -} - -// ListCapabilities get the list of CPU/memory/GPU capabilities of a region. -// Parameters: -// location - the identifier for the physical azure location. -func (client LocationClient) ListCapabilities(ctx context.Context, location string) (result CapabilitiesListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocationClient.ListCapabilities") - defer func() { - sc := -1 - if result.clr.Response.Response != nil { - sc = result.clr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listCapabilitiesNextResults - req, err := client.ListCapabilitiesPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "ListCapabilities", nil, "Failure preparing request") - return - } - - resp, err := client.ListCapabilitiesSender(req) - if err != nil { - result.clr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "ListCapabilities", resp, "Failure sending request") - return - } - - result.clr, err = client.ListCapabilitiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "ListCapabilities", resp, "Failure responding to request") - return - } - if result.clr.hasNextLink() && result.clr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListCapabilitiesPreparer prepares the ListCapabilities request. -func (client LocationClient) ListCapabilitiesPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/capabilities", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListCapabilitiesSender sends the ListCapabilities request. The method will close the -// http.Response Body if it receives an error. -func (client LocationClient) ListCapabilitiesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListCapabilitiesResponder handles the response to the ListCapabilities request. The method always -// closes the http.Response Body. -func (client LocationClient) ListCapabilitiesResponder(resp *http.Response) (result CapabilitiesListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listCapabilitiesNextResults retrieves the next set of results, if any. -func (client LocationClient) listCapabilitiesNextResults(ctx context.Context, lastResults CapabilitiesListResult) (result CapabilitiesListResult, err error) { - req, err := lastResults.capabilitiesListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "containerinstance.LocationClient", "listCapabilitiesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListCapabilitiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerinstance.LocationClient", "listCapabilitiesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListCapabilitiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "listCapabilitiesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListCapabilitiesComplete enumerates all values, automatically crossing page boundaries as required. -func (client LocationClient) ListCapabilitiesComplete(ctx context.Context, location string) (result CapabilitiesListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocationClient.ListCapabilities") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListCapabilities(ctx, location) - return -} - -// ListUsage get the usage for a subscription -// Parameters: -// location - the identifier for the physical azure location. -func (client LocationClient) ListUsage(ctx context.Context, location string) (result UsageListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocationClient.ListUsage") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListUsagePreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "ListUsage", nil, "Failure preparing request") - return - } - - resp, err := client.ListUsageSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "ListUsage", resp, "Failure sending request") - return - } - - result, err = client.ListUsageResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.LocationClient", "ListUsage", resp, "Failure responding to request") - return - } - - return -} - -// ListUsagePreparer prepares the ListUsage request. -func (client LocationClient) ListUsagePreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-03-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/locations/{location}/usages", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListUsageSender sends the ListUsage request. The method will close the -// http.Response Body if it receives an error. -func (client LocationClient) ListUsageSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListUsageResponder handles the response to the ListUsage request. The method always -// closes the http.Response Body. -func (client LocationClient) ListUsageResponder(resp *http.Response) (result UsageListResult, err error) { - err = autorest.Respond( - resp, - 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/containerinstance/mgmt/2021-03-01/containerinstance/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/models.go deleted file mode 100644 index 3943f3e60232..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/models.go +++ /dev/null @@ -1,1813 +0,0 @@ -package containerinstance - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance" - -// AzureFileVolume the properties of the Azure File volume. Azure File shares are mounted as volumes. -type AzureFileVolume struct { - // ShareName - The name of the Azure File share to be mounted as a volume. - ShareName *string `json:"shareName,omitempty"` - // ReadOnly - The flag indicating whether the Azure File shared mounted as a volume is read-only. - ReadOnly *bool `json:"readOnly,omitempty"` - // StorageAccountName - The name of the storage account that contains the Azure File share. - StorageAccountName *string `json:"storageAccountName,omitempty"` - // StorageAccountKey - The storage account access key used to access the Azure File share. - StorageAccountKey *string `json:"storageAccountKey,omitempty"` -} - -// CachedImages the cached image and OS type. -type CachedImages struct { - // OsType - The OS type of the cached image. - OsType *string `json:"osType,omitempty"` - // Image - The cached image name. - Image *string `json:"image,omitempty"` -} - -// CachedImagesListResult the response containing cached images. -type CachedImagesListResult struct { - autorest.Response `json:"-"` - // Value - The list of cached images. - Value *[]CachedImages `json:"value,omitempty"` - // NextLink - The URI to fetch the next page of cached images. - NextLink *string `json:"nextLink,omitempty"` -} - -// CachedImagesListResultIterator provides access to a complete listing of CachedImages values. -type CachedImagesListResultIterator struct { - i int - page CachedImagesListResultPage -} - -// NextWithContext 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 *CachedImagesListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CachedImagesListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *CachedImagesListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter CachedImagesListResultIterator) 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 CachedImagesListResultIterator) Response() CachedImagesListResult { - 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 CachedImagesListResultIterator) Value() CachedImages { - if !iter.page.NotDone() { - return CachedImages{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the CachedImagesListResultIterator type. -func NewCachedImagesListResultIterator(page CachedImagesListResultPage) CachedImagesListResultIterator { - return CachedImagesListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (cilr CachedImagesListResult) IsEmpty() bool { - return cilr.Value == nil || len(*cilr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (cilr CachedImagesListResult) hasNextLink() bool { - return cilr.NextLink != nil && len(*cilr.NextLink) != 0 -} - -// cachedImagesListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (cilr CachedImagesListResult) cachedImagesListResultPreparer(ctx context.Context) (*http.Request, error) { - if !cilr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(cilr.NextLink))) -} - -// CachedImagesListResultPage contains a page of CachedImages values. -type CachedImagesListResultPage struct { - fn func(context.Context, CachedImagesListResult) (CachedImagesListResult, error) - cilr CachedImagesListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *CachedImagesListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CachedImagesListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.cilr) - if err != nil { - return err - } - page.cilr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *CachedImagesListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page CachedImagesListResultPage) NotDone() bool { - return !page.cilr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page CachedImagesListResultPage) Response() CachedImagesListResult { - return page.cilr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page CachedImagesListResultPage) Values() []CachedImages { - if page.cilr.IsEmpty() { - return nil - } - return *page.cilr.Value -} - -// Creates a new instance of the CachedImagesListResultPage type. -func NewCachedImagesListResultPage(cur CachedImagesListResult, getNextPage func(context.Context, CachedImagesListResult) (CachedImagesListResult, error)) CachedImagesListResultPage { - return CachedImagesListResultPage{ - fn: getNextPage, - cilr: cur, - } -} - -// Capabilities the regional capabilities. -type Capabilities struct { - // ResourceType - READ-ONLY; The resource type that this capability describes. - ResourceType *string `json:"resourceType,omitempty"` - // OsType - READ-ONLY; The OS type that this capability describes. - OsType *string `json:"osType,omitempty"` - // Location - READ-ONLY; The resource location. - Location *string `json:"location,omitempty"` - // IPAddressType - READ-ONLY; The ip address type that this capability describes. - IPAddressType *string `json:"ipAddressType,omitempty"` - // Gpu - READ-ONLY; The GPU sku that this capability describes. - Gpu *string `json:"gpu,omitempty"` - // Capabilities - READ-ONLY; The supported capabilities. - Capabilities *CapabilitiesCapabilities `json:"capabilities,omitempty"` -} - -// MarshalJSON is the custom marshaler for Capabilities. -func (c Capabilities) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// CapabilitiesCapabilities the supported capabilities. -type CapabilitiesCapabilities struct { - // MaxMemoryInGB - READ-ONLY; The maximum allowed memory request in GB. - MaxMemoryInGB *float64 `json:"maxMemoryInGB,omitempty"` - // MaxCPU - READ-ONLY; The maximum allowed CPU request in cores. - MaxCPU *float64 `json:"maxCpu,omitempty"` - // MaxGpuCount - READ-ONLY; The maximum allowed GPU count. - MaxGpuCount *float64 `json:"maxGpuCount,omitempty"` -} - -// MarshalJSON is the custom marshaler for CapabilitiesCapabilities. -func (c CapabilitiesCapabilities) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// CapabilitiesListResult the response containing list of capabilities. -type CapabilitiesListResult struct { - autorest.Response `json:"-"` - // Value - The list of capabilities. - Value *[]Capabilities `json:"value,omitempty"` - // NextLink - The URI to fetch the next page of capabilities. - NextLink *string `json:"nextLink,omitempty"` -} - -// CapabilitiesListResultIterator provides access to a complete listing of Capabilities values. -type CapabilitiesListResultIterator struct { - i int - page CapabilitiesListResultPage -} - -// NextWithContext 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 *CapabilitiesListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CapabilitiesListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *CapabilitiesListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter CapabilitiesListResultIterator) 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 CapabilitiesListResultIterator) Response() CapabilitiesListResult { - 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 CapabilitiesListResultIterator) Value() Capabilities { - if !iter.page.NotDone() { - return Capabilities{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the CapabilitiesListResultIterator type. -func NewCapabilitiesListResultIterator(page CapabilitiesListResultPage) CapabilitiesListResultIterator { - return CapabilitiesListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (clr CapabilitiesListResult) IsEmpty() bool { - return clr.Value == nil || len(*clr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (clr CapabilitiesListResult) hasNextLink() bool { - return clr.NextLink != nil && len(*clr.NextLink) != 0 -} - -// capabilitiesListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (clr CapabilitiesListResult) capabilitiesListResultPreparer(ctx context.Context) (*http.Request, error) { - if !clr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(clr.NextLink))) -} - -// CapabilitiesListResultPage contains a page of Capabilities values. -type CapabilitiesListResultPage struct { - fn func(context.Context, CapabilitiesListResult) (CapabilitiesListResult, error) - clr CapabilitiesListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *CapabilitiesListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CapabilitiesListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.clr) - if err != nil { - return err - } - page.clr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *CapabilitiesListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page CapabilitiesListResultPage) NotDone() bool { - return !page.clr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page CapabilitiesListResultPage) Response() CapabilitiesListResult { - return page.clr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page CapabilitiesListResultPage) Values() []Capabilities { - if page.clr.IsEmpty() { - return nil - } - return *page.clr.Value -} - -// Creates a new instance of the CapabilitiesListResultPage type. -func NewCapabilitiesListResultPage(cur CapabilitiesListResult, getNextPage func(context.Context, CapabilitiesListResult) (CapabilitiesListResult, error)) CapabilitiesListResultPage { - return CapabilitiesListResultPage{ - fn: getNextPage, - clr: cur, - } -} - -// CloudError an error response from the Container Instance service. -type CloudError struct { - Error *CloudErrorBody `json:"error,omitempty"` -} - -// CloudErrorBody an error response from the Container Instance service. -type CloudErrorBody struct { - // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. - Code *string `json:"code,omitempty"` - // Message - A message describing the error, intended to be suitable for display in a user interface. - Message *string `json:"message,omitempty"` - // Target - The target of the particular error. For example, the name of the property in error. - Target *string `json:"target,omitempty"` - // Details - A list of additional details about the error. - Details *[]CloudErrorBody `json:"details,omitempty"` -} - -// Container a container instance. -type Container struct { - // Name - The user-provided name of the container instance. - Name *string `json:"name,omitempty"` - // ContainerProperties - The properties of the container instance. - *ContainerProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for Container. -func (c Container) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if c.Name != nil { - objectMap["name"] = c.Name - } - if c.ContainerProperties != nil { - objectMap["properties"] = c.ContainerProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Container struct. -func (c *Container) 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 - } - c.Name = &name - } - case "properties": - if v != nil { - var containerProperties ContainerProperties - err = json.Unmarshal(*v, &containerProperties) - if err != nil { - return err - } - c.ContainerProperties = &containerProperties - } - } - } - - return nil -} - -// ContainerAttachResponse the information for the output stream from container attach. -type ContainerAttachResponse struct { - autorest.Response `json:"-"` - // WebSocketURI - The uri for the output stream from the attach. - WebSocketURI *string `json:"webSocketUri,omitempty"` - // Password - The password to the output stream from the attach. Send as an Authorization header value when connecting to the websocketUri. - Password *string `json:"password,omitempty"` -} - -// ContainerExec the container execution command, for liveness or readiness probe -type ContainerExec struct { - // Command - The commands to execute within the container. - Command *[]string `json:"command,omitempty"` -} - -// ContainerExecRequest the container exec request. -type ContainerExecRequest struct { - // Command - The command to be executed. - Command *string `json:"command,omitempty"` - // TerminalSize - The size of the terminal. - TerminalSize *ContainerExecRequestTerminalSize `json:"terminalSize,omitempty"` -} - -// ContainerExecRequestTerminalSize the size of the terminal. -type ContainerExecRequestTerminalSize struct { - // Rows - The row size of the terminal - Rows *int32 `json:"rows,omitempty"` - // Cols - The column size of the terminal - Cols *int32 `json:"cols,omitempty"` -} - -// ContainerExecResponse the information for the container exec command. -type ContainerExecResponse struct { - autorest.Response `json:"-"` - // WebSocketURI - The uri for the exec websocket. - WebSocketURI *string `json:"webSocketUri,omitempty"` - // Password - The password to start the exec command. - Password *string `json:"password,omitempty"` -} - -// ContainerGroup a container group. -type ContainerGroup struct { - autorest.Response `json:"-"` - // Identity - The identity of the container group, if configured. - Identity *ContainerGroupIdentity `json:"identity,omitempty"` - // ContainerGroupProperties - The container group properties - *ContainerGroupProperties `json:"properties,omitempty"` - // ID - READ-ONLY; The resource id. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The resource type. - Type *string `json:"type,omitempty"` - // Location - The resource location. - Location *string `json:"location,omitempty"` - // Tags - The resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ContainerGroup. -func (cg ContainerGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cg.Identity != nil { - objectMap["identity"] = cg.Identity - } - if cg.ContainerGroupProperties != nil { - objectMap["properties"] = cg.ContainerGroupProperties - } - if cg.Location != nil { - objectMap["location"] = cg.Location - } - if cg.Tags != nil { - objectMap["tags"] = cg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ContainerGroup struct. -func (cg *ContainerGroup) 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 "identity": - if v != nil { - var identity ContainerGroupIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - cg.Identity = &identity - } - case "properties": - if v != nil { - var containerGroupProperties ContainerGroupProperties - err = json.Unmarshal(*v, &containerGroupProperties) - if err != nil { - return err - } - cg.ContainerGroupProperties = &containerGroupProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cg.Tags = tags - } - } - } - - return nil -} - -// ContainerGroupDiagnostics container group diagnostic information. -type ContainerGroupDiagnostics struct { - // LogAnalytics - Container group log analytics information. - LogAnalytics *LogAnalytics `json:"logAnalytics,omitempty"` -} - -// ContainerGroupIdentity identity for the container group. -type ContainerGroupIdentity struct { - // PrincipalID - READ-ONLY; The principal id of the container group identity. This property will only be provided for a system assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // TenantID - READ-ONLY; The tenant id associated with the container group. This property will only be provided for a system assigned identity. - TenantID *string `json:"tenantId,omitempty"` - // Type - The type of identity used for the container group. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the container group. Possible values include: 'ResourceIdentityTypeSystemAssigned', 'ResourceIdentityTypeUserAssigned', 'ResourceIdentityTypeSystemAssignedUserAssigned', 'ResourceIdentityTypeNone' - Type ResourceIdentityType `json:"type,omitempty"` - // UserAssignedIdentities - The list of user identities associated with the container group. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - UserAssignedIdentities map[string]*ContainerGroupIdentityUserAssignedIdentitiesValue `json:"userAssignedIdentities"` -} - -// MarshalJSON is the custom marshaler for ContainerGroupIdentity. -func (cgiVar ContainerGroupIdentity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cgiVar.Type != "" { - objectMap["type"] = cgiVar.Type - } - if cgiVar.UserAssignedIdentities != nil { - objectMap["userAssignedIdentities"] = cgiVar.UserAssignedIdentities - } - return json.Marshal(objectMap) -} - -// ContainerGroupIdentityUserAssignedIdentitiesValue ... -type ContainerGroupIdentityUserAssignedIdentitiesValue struct { - // PrincipalID - READ-ONLY; The principal id of user assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // ClientID - READ-ONLY; The client id of user assigned identity. - ClientID *string `json:"clientId,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerGroupIdentityUserAssignedIdentitiesValue. -func (cgiAiv ContainerGroupIdentityUserAssignedIdentitiesValue) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ContainerGroupListResult the container group list response that contains the container group properties. -type ContainerGroupListResult struct { - autorest.Response `json:"-"` - // Value - The list of container groups. - Value *[]ContainerGroup `json:"value,omitempty"` - // NextLink - The URI to fetch the next page of container groups. - NextLink *string `json:"nextLink,omitempty"` -} - -// ContainerGroupListResultIterator provides access to a complete listing of ContainerGroup values. -type ContainerGroupListResultIterator struct { - i int - page ContainerGroupListResultPage -} - -// NextWithContext 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 *ContainerGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ContainerGroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ContainerGroupListResultIterator) 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 ContainerGroupListResultIterator) Response() ContainerGroupListResult { - 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 ContainerGroupListResultIterator) Value() ContainerGroup { - if !iter.page.NotDone() { - return ContainerGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ContainerGroupListResultIterator type. -func NewContainerGroupListResultIterator(page ContainerGroupListResultPage) ContainerGroupListResultIterator { - return ContainerGroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (cglr ContainerGroupListResult) IsEmpty() bool { - return cglr.Value == nil || len(*cglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (cglr ContainerGroupListResult) hasNextLink() bool { - return cglr.NextLink != nil && len(*cglr.NextLink) != 0 -} - -// containerGroupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (cglr ContainerGroupListResult) containerGroupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !cglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(cglr.NextLink))) -} - -// ContainerGroupListResultPage contains a page of ContainerGroup values. -type ContainerGroupListResultPage struct { - fn func(context.Context, ContainerGroupListResult) (ContainerGroupListResult, error) - cglr ContainerGroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ContainerGroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ContainerGroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.cglr) - if err != nil { - return err - } - page.cglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ContainerGroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ContainerGroupListResultPage) NotDone() bool { - return !page.cglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ContainerGroupListResultPage) Response() ContainerGroupListResult { - return page.cglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ContainerGroupListResultPage) Values() []ContainerGroup { - if page.cglr.IsEmpty() { - return nil - } - return *page.cglr.Value -} - -// Creates a new instance of the ContainerGroupListResultPage type. -func NewContainerGroupListResultPage(cur ContainerGroupListResult, getNextPage func(context.Context, ContainerGroupListResult) (ContainerGroupListResult, error)) ContainerGroupListResultPage { - return ContainerGroupListResultPage{ - fn: getNextPage, - cglr: cur, - } -} - -// ContainerGroupNetworkProfile container group network profile information. -type ContainerGroupNetworkProfile struct { - // ID - The identifier for a network profile. - ID *string `json:"id,omitempty"` -} - -// ContainerGroupProperties the container group properties -type ContainerGroupProperties struct { - // ProvisioningState - READ-ONLY; The provisioning state of the container group. This only appears in the response. - ProvisioningState *string `json:"provisioningState,omitempty"` - // Containers - The containers within the container group. - Containers *[]Container `json:"containers,omitempty"` - // ImageRegistryCredentials - The image registry credentials by which the container group is created from. - ImageRegistryCredentials *[]ImageRegistryCredential `json:"imageRegistryCredentials,omitempty"` - // RestartPolicy - Restart policy for all containers within the container group. - // - `Always` Always restart - // - `OnFailure` Restart on failure - // - `Never` Never restart - // . Possible values include: 'ContainerGroupRestartPolicyAlways', 'ContainerGroupRestartPolicyOnFailure', 'ContainerGroupRestartPolicyNever' - RestartPolicy ContainerGroupRestartPolicy `json:"restartPolicy,omitempty"` - // IPAddress - The IP address type of the container group. - IPAddress *IPAddress `json:"ipAddress,omitempty"` - // OsType - The operating system type required by the containers in the container group. Possible values include: 'OperatingSystemTypesWindows', 'OperatingSystemTypesLinux' - OsType OperatingSystemTypes `json:"osType,omitempty"` - // Volumes - The list of volumes that can be mounted by containers in this container group. - Volumes *[]Volume `json:"volumes,omitempty"` - // InstanceView - READ-ONLY; The instance view of the container group. Only valid in response. - InstanceView *ContainerGroupPropertiesInstanceView `json:"instanceView,omitempty"` - // Diagnostics - The diagnostic information for a container group. - Diagnostics *ContainerGroupDiagnostics `json:"diagnostics,omitempty"` - // NetworkProfile - The network profile information for a container group. - NetworkProfile *ContainerGroupNetworkProfile `json:"networkProfile,omitempty"` - // DNSConfig - The DNS config information for a container group. - DNSConfig *DNSConfiguration `json:"dnsConfig,omitempty"` - // Sku - The SKU for a container group. Possible values include: 'ContainerGroupSkuStandard', 'ContainerGroupSkuDedicated' - Sku ContainerGroupSku `json:"sku,omitempty"` - // EncryptionProperties - The encryption properties for a container group. - EncryptionProperties *EncryptionProperties `json:"encryptionProperties,omitempty"` - // InitContainers - The init containers for a container group. - InitContainers *[]InitContainerDefinition `json:"initContainers,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerGroupProperties. -func (cg ContainerGroupProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cg.Containers != nil { - objectMap["containers"] = cg.Containers - } - if cg.ImageRegistryCredentials != nil { - objectMap["imageRegistryCredentials"] = cg.ImageRegistryCredentials - } - if cg.RestartPolicy != "" { - objectMap["restartPolicy"] = cg.RestartPolicy - } - if cg.IPAddress != nil { - objectMap["ipAddress"] = cg.IPAddress - } - if cg.OsType != "" { - objectMap["osType"] = cg.OsType - } - if cg.Volumes != nil { - objectMap["volumes"] = cg.Volumes - } - if cg.Diagnostics != nil { - objectMap["diagnostics"] = cg.Diagnostics - } - if cg.NetworkProfile != nil { - objectMap["networkProfile"] = cg.NetworkProfile - } - if cg.DNSConfig != nil { - objectMap["dnsConfig"] = cg.DNSConfig - } - if cg.Sku != "" { - objectMap["sku"] = cg.Sku - } - if cg.EncryptionProperties != nil { - objectMap["encryptionProperties"] = cg.EncryptionProperties - } - if cg.InitContainers != nil { - objectMap["initContainers"] = cg.InitContainers - } - return json.Marshal(objectMap) -} - -// ContainerGroupPropertiesInstanceView the instance view of the container group. Only valid in response. -type ContainerGroupPropertiesInstanceView struct { - // Events - READ-ONLY; The events of this container group. - Events *[]Event `json:"events,omitempty"` - // State - READ-ONLY; The state of the container group. Only valid in response. - State *string `json:"state,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerGroupPropertiesInstanceView. -func (cgV ContainerGroupPropertiesInstanceView) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ContainerGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ContainerGroupsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ContainerGroupsClient) (ContainerGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ContainerGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ContainerGroupsCreateOrUpdateFuture.Result. -func (future *ContainerGroupsCreateOrUpdateFuture) result(client ContainerGroupsClient) (cg ContainerGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("containerinstance.ContainerGroupsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cg.Response.Response, err = future.GetResult(sender); err == nil && cg.Response.Response.StatusCode != http.StatusNoContent { - cg, err = client.CreateOrUpdateResponder(cg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsCreateOrUpdateFuture", "Result", cg.Response.Response, "Failure responding to request") - } - } - return -} - -// ContainerGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ContainerGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ContainerGroupsClient) (ContainerGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ContainerGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ContainerGroupsDeleteFuture.Result. -func (future *ContainerGroupsDeleteFuture) result(client ContainerGroupsClient) (cg ContainerGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("containerinstance.ContainerGroupsDeleteFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cg.Response.Response, err = future.GetResult(sender); err == nil && cg.Response.Response.StatusCode != http.StatusNoContent { - cg, err = client.DeleteResponder(cg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsDeleteFuture", "Result", cg.Response.Response, "Failure responding to request") - } - } - return -} - -// ContainerGroupsRestartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ContainerGroupsRestartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ContainerGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ContainerGroupsRestartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ContainerGroupsRestartFuture.Result. -func (future *ContainerGroupsRestartFuture) result(client ContainerGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsRestartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("containerinstance.ContainerGroupsRestartFuture") - return - } - ar.Response = future.Response() - return -} - -// ContainerGroupsStartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ContainerGroupsStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ContainerGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ContainerGroupsStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ContainerGroupsStartFuture.Result. -func (future *ContainerGroupsStartFuture) result(client ContainerGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.ContainerGroupsStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("containerinstance.ContainerGroupsStartFuture") - return - } - ar.Response = future.Response() - return -} - -// ContainerHTTPGet the container Http Get settings, for liveness or readiness probe -type ContainerHTTPGet struct { - // Path - The path to probe. - Path *string `json:"path,omitempty"` - // Port - The port number to probe. - Port *int32 `json:"port,omitempty"` - // Scheme - The scheme. Possible values include: 'SchemeHTTP', 'SchemeHTTPS' - Scheme Scheme `json:"scheme,omitempty"` - // HTTPHeaders - The HTTP headers. - HTTPHeaders *HTTPHeaders `json:"httpHeaders,omitempty"` -} - -// ContainerPort the port exposed on the container instance. -type ContainerPort struct { - // Protocol - The protocol associated with the port. Possible values include: 'ContainerNetworkProtocolTCP', 'ContainerNetworkProtocolUDP' - Protocol ContainerNetworkProtocol `json:"protocol,omitempty"` - // Port - The port number exposed within the container group. - Port *int32 `json:"port,omitempty"` -} - -// ContainerProbe the container probe, for liveness or readiness -type ContainerProbe struct { - // Exec - The execution command to probe - Exec *ContainerExec `json:"exec,omitempty"` - // HTTPGet - The Http Get settings to probe - HTTPGet *ContainerHTTPGet `json:"httpGet,omitempty"` - // InitialDelaySeconds - The initial delay seconds. - InitialDelaySeconds *int32 `json:"initialDelaySeconds,omitempty"` - // PeriodSeconds - The period seconds. - PeriodSeconds *int32 `json:"periodSeconds,omitempty"` - // FailureThreshold - The failure threshold. - FailureThreshold *int32 `json:"failureThreshold,omitempty"` - // SuccessThreshold - The success threshold. - SuccessThreshold *int32 `json:"successThreshold,omitempty"` - // TimeoutSeconds - The timeout seconds. - TimeoutSeconds *int32 `json:"timeoutSeconds,omitempty"` -} - -// ContainerProperties the container instance properties. -type ContainerProperties struct { - // Image - The name of the image used to create the container instance. - Image *string `json:"image,omitempty"` - // Command - The commands to execute within the container instance in exec form. - Command *[]string `json:"command,omitempty"` - // Ports - The exposed ports on the container instance. - Ports *[]ContainerPort `json:"ports,omitempty"` - // EnvironmentVariables - The environment variables to set in the container instance. - EnvironmentVariables *[]EnvironmentVariable `json:"environmentVariables,omitempty"` - // InstanceView - READ-ONLY; The instance view of the container instance. Only valid in response. - InstanceView *ContainerPropertiesInstanceView `json:"instanceView,omitempty"` - // Resources - The resource requirements of the container instance. - Resources *ResourceRequirements `json:"resources,omitempty"` - // VolumeMounts - The volume mounts available to the container instance. - VolumeMounts *[]VolumeMount `json:"volumeMounts,omitempty"` - // LivenessProbe - The liveness probe. - LivenessProbe *ContainerProbe `json:"livenessProbe,omitempty"` - // ReadinessProbe - The readiness probe. - ReadinessProbe *ContainerProbe `json:"readinessProbe,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerProperties. -func (cp ContainerProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cp.Image != nil { - objectMap["image"] = cp.Image - } - if cp.Command != nil { - objectMap["command"] = cp.Command - } - if cp.Ports != nil { - objectMap["ports"] = cp.Ports - } - if cp.EnvironmentVariables != nil { - objectMap["environmentVariables"] = cp.EnvironmentVariables - } - if cp.Resources != nil { - objectMap["resources"] = cp.Resources - } - if cp.VolumeMounts != nil { - objectMap["volumeMounts"] = cp.VolumeMounts - } - if cp.LivenessProbe != nil { - objectMap["livenessProbe"] = cp.LivenessProbe - } - if cp.ReadinessProbe != nil { - objectMap["readinessProbe"] = cp.ReadinessProbe - } - return json.Marshal(objectMap) -} - -// ContainerPropertiesInstanceView the instance view of the container instance. Only valid in response. -type ContainerPropertiesInstanceView struct { - // RestartCount - READ-ONLY; The number of times that the container instance has been restarted. - RestartCount *int32 `json:"restartCount,omitempty"` - // CurrentState - READ-ONLY; Current container instance state. - CurrentState *ContainerState `json:"currentState,omitempty"` - // PreviousState - READ-ONLY; Previous container instance state. - PreviousState *ContainerState `json:"previousState,omitempty"` - // Events - READ-ONLY; The events of the container instance. - Events *[]Event `json:"events,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerPropertiesInstanceView. -func (cpV ContainerPropertiesInstanceView) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ContainerState the container instance state. -type ContainerState struct { - // State - READ-ONLY; The state of the container instance. - State *string `json:"state,omitempty"` - // StartTime - READ-ONLY; The date-time when the container instance state started. - StartTime *date.Time `json:"startTime,omitempty"` - // ExitCode - READ-ONLY; The container instance exit codes correspond to those from the `docker run` command. - ExitCode *int32 `json:"exitCode,omitempty"` - // FinishTime - READ-ONLY; The date-time when the container instance state finished. - FinishTime *date.Time `json:"finishTime,omitempty"` - // DetailStatus - READ-ONLY; The human-readable status of the container instance state. - DetailStatus *string `json:"detailStatus,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerState. -func (cs ContainerState) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// DNSConfiguration DNS configuration for the container group. -type DNSConfiguration struct { - // NameServers - The DNS servers for the container group. - NameServers *[]string `json:"nameServers,omitempty"` - // SearchDomains - The DNS search domains for hostname lookup in the container group. - SearchDomains *string `json:"searchDomains,omitempty"` - // Options - The DNS options for the container group. - Options *string `json:"options,omitempty"` -} - -// EncryptionProperties the container group encryption properties. -type EncryptionProperties struct { - // VaultBaseURL - The keyvault base url. - VaultBaseURL *string `json:"vaultBaseUrl,omitempty"` - // KeyName - The encryption key name. - KeyName *string `json:"keyName,omitempty"` - // KeyVersion - The encryption key version. - KeyVersion *string `json:"keyVersion,omitempty"` -} - -// EnvironmentVariable the environment variable to set within the container instance. -type EnvironmentVariable struct { - // Name - The name of the environment variable. - Name *string `json:"name,omitempty"` - // Value - The value of the environment variable. - Value *string `json:"value,omitempty"` - // SecureValue - The value of the secure environment variable. - SecureValue *string `json:"secureValue,omitempty"` -} - -// Event a container group or container instance event. -type Event struct { - // Count - READ-ONLY; The count of the event. - Count *int32 `json:"count,omitempty"` - // FirstTimestamp - READ-ONLY; The date-time of the earliest logged event. - FirstTimestamp *date.Time `json:"firstTimestamp,omitempty"` - // LastTimestamp - READ-ONLY; The date-time of the latest logged event. - LastTimestamp *date.Time `json:"lastTimestamp,omitempty"` - // Name - READ-ONLY; The event name. - Name *string `json:"name,omitempty"` - // Message - READ-ONLY; The event message. - Message *string `json:"message,omitempty"` - // Type - READ-ONLY; The event type. - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Event. -func (e Event) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GitRepoVolume represents a volume that is populated with the contents of a git repository -type GitRepoVolume struct { - // Directory - Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name. - Directory *string `json:"directory,omitempty"` - // Repository - Repository URL - Repository *string `json:"repository,omitempty"` - // Revision - Commit hash for the specified revision. - Revision *string `json:"revision,omitempty"` -} - -// GpuResource the GPU resource. -type GpuResource struct { - // Count - The count of the GPU resource. - Count *int32 `json:"count,omitempty"` - // Sku - The SKU of the GPU resource. Possible values include: 'GpuSkuK80', 'GpuSkuP100', 'GpuSkuV100' - Sku GpuSku `json:"sku,omitempty"` -} - -// HTTPHeaders the HTTP headers. -type HTTPHeaders struct { - // Name - The header name. - Name *string `json:"name,omitempty"` - // Value - The header value. - Value *string `json:"value,omitempty"` -} - -// ImageRegistryCredential image registry credential. -type ImageRegistryCredential struct { - // Server - The Docker image registry server without a protocol such as "http" and "https". - Server *string `json:"server,omitempty"` - // Username - The username for the private registry. - Username *string `json:"username,omitempty"` - // Password - The password for the private registry. - Password *string `json:"password,omitempty"` -} - -// InitContainerDefinition the init container definition. -type InitContainerDefinition struct { - // Name - The name for the init container. - Name *string `json:"name,omitempty"` - // InitContainerPropertiesDefinition - The properties for the init container. - *InitContainerPropertiesDefinition `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for InitContainerDefinition. -func (icd InitContainerDefinition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if icd.Name != nil { - objectMap["name"] = icd.Name - } - if icd.InitContainerPropertiesDefinition != nil { - objectMap["properties"] = icd.InitContainerPropertiesDefinition - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InitContainerDefinition struct. -func (icd *InitContainerDefinition) 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 - } - icd.Name = &name - } - case "properties": - if v != nil { - var initContainerPropertiesDefinition InitContainerPropertiesDefinition - err = json.Unmarshal(*v, &initContainerPropertiesDefinition) - if err != nil { - return err - } - icd.InitContainerPropertiesDefinition = &initContainerPropertiesDefinition - } - } - } - - return nil -} - -// InitContainerPropertiesDefinition the init container definition properties. -type InitContainerPropertiesDefinition struct { - // Image - The image of the init container. - Image *string `json:"image,omitempty"` - // Command - The command to execute within the init container in exec form. - Command *[]string `json:"command,omitempty"` - // EnvironmentVariables - The environment variables to set in the init container. - EnvironmentVariables *[]EnvironmentVariable `json:"environmentVariables,omitempty"` - // InstanceView - READ-ONLY; The instance view of the init container. Only valid in response. - InstanceView *InitContainerPropertiesDefinitionInstanceView `json:"instanceView,omitempty"` - // VolumeMounts - The volume mounts available to the init container. - VolumeMounts *[]VolumeMount `json:"volumeMounts,omitempty"` -} - -// MarshalJSON is the custom marshaler for InitContainerPropertiesDefinition. -func (icpd InitContainerPropertiesDefinition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if icpd.Image != nil { - objectMap["image"] = icpd.Image - } - if icpd.Command != nil { - objectMap["command"] = icpd.Command - } - if icpd.EnvironmentVariables != nil { - objectMap["environmentVariables"] = icpd.EnvironmentVariables - } - if icpd.VolumeMounts != nil { - objectMap["volumeMounts"] = icpd.VolumeMounts - } - return json.Marshal(objectMap) -} - -// InitContainerPropertiesDefinitionInstanceView the instance view of the init container. Only valid in -// response. -type InitContainerPropertiesDefinitionInstanceView struct { - // RestartCount - READ-ONLY; The number of times that the init container has been restarted. - RestartCount *int32 `json:"restartCount,omitempty"` - // CurrentState - READ-ONLY; The current state of the init container. - CurrentState *ContainerState `json:"currentState,omitempty"` - // PreviousState - READ-ONLY; The previous state of the init container. - PreviousState *ContainerState `json:"previousState,omitempty"` - // Events - READ-ONLY; The events of the init container. - Events *[]Event `json:"events,omitempty"` -} - -// MarshalJSON is the custom marshaler for InitContainerPropertiesDefinitionInstanceView. -func (icpdV InitContainerPropertiesDefinitionInstanceView) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// IPAddress IP address for the container group. -type IPAddress struct { - // Ports - The list of ports exposed on the container group. - Ports *[]Port `json:"ports,omitempty"` - // Type - Specifies if the IP is exposed to the public internet or private VNET. Possible values include: 'ContainerGroupIPAddressTypePublic', 'ContainerGroupIPAddressTypePrivate' - Type ContainerGroupIPAddressType `json:"type,omitempty"` - // IP - The IP exposed to the public internet. - IP *string `json:"ip,omitempty"` - // DNSNameLabel - The Dns name label for the IP. - DNSNameLabel *string `json:"dnsNameLabel,omitempty"` - // Fqdn - READ-ONLY; The FQDN for the IP. - Fqdn *string `json:"fqdn,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPAddress. -func (ia IPAddress) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ia.Ports != nil { - objectMap["ports"] = ia.Ports - } - if ia.Type != "" { - objectMap["type"] = ia.Type - } - if ia.IP != nil { - objectMap["ip"] = ia.IP - } - if ia.DNSNameLabel != nil { - objectMap["dnsNameLabel"] = ia.DNSNameLabel - } - return json.Marshal(objectMap) -} - -// LogAnalytics container group log analytics information. -type LogAnalytics struct { - // WorkspaceID - The workspace id for log analytics - WorkspaceID *string `json:"workspaceId,omitempty"` - // WorkspaceKey - The workspace key for log analytics - WorkspaceKey *string `json:"workspaceKey,omitempty"` - // LogType - The log type to be used. Possible values include: 'LogAnalyticsLogTypeContainerInsights', 'LogAnalyticsLogTypeContainerInstanceLogs' - LogType LogAnalyticsLogType `json:"logType,omitempty"` - // Metadata - Metadata for log analytics. - Metadata map[string]*string `json:"metadata"` - // WorkspaceResourceID - The workspace resource id for log analytics - WorkspaceResourceID map[string]*string `json:"workspaceResourceId"` -} - -// MarshalJSON is the custom marshaler for LogAnalytics. -func (la LogAnalytics) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if la.WorkspaceID != nil { - objectMap["workspaceId"] = la.WorkspaceID - } - if la.WorkspaceKey != nil { - objectMap["workspaceKey"] = la.WorkspaceKey - } - if la.LogType != "" { - objectMap["logType"] = la.LogType - } - if la.Metadata != nil { - objectMap["metadata"] = la.Metadata - } - if la.WorkspaceResourceID != nil { - objectMap["workspaceResourceId"] = la.WorkspaceResourceID - } - return json.Marshal(objectMap) -} - -// Logs the logs. -type Logs struct { - autorest.Response `json:"-"` - // Content - The content of the log. - Content *string `json:"content,omitempty"` -} - -// Operation an operation for Azure Container Instance service. -type Operation struct { - // Name - The name of the operation. - Name *string `json:"name,omitempty"` - // Display - The display information of the operation. - Display *OperationDisplay `json:"display,omitempty"` - // Properties - The additional properties. - Properties interface{} `json:"properties,omitempty"` - // Origin - The intended executor of the operation. Possible values include: 'OperationsOriginUser', 'OperationsOriginSystem' - Origin OperationsOrigin `json:"origin,omitempty"` -} - -// OperationDisplay the display information of the operation. -type OperationDisplay struct { - // Provider - The name of the provider of the operation. - Provider *string `json:"provider,omitempty"` - // Resource - The name of the resource type of the operation. - Resource *string `json:"resource,omitempty"` - // Operation - The friendly name of the operation. - Operation *string `json:"operation,omitempty"` - // Description - The description of the operation. - Description *string `json:"description,omitempty"` -} - -// OperationListResult the operation list response that contains all operations for Azure Container -// Instance service. -type OperationListResult struct { - autorest.Response `json:"-"` - // Value - The list of operations. - Value *[]Operation `json:"value,omitempty"` - // NextLink - The URI to fetch the next page of operations. - NextLink *string `json:"nextLink,omitempty"` -} - -// OperationListResultIterator provides access to a complete listing of Operation values. -type OperationListResultIterator struct { - i int - page OperationListResultPage -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *OperationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the OperationListResultIterator type. -func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator { - return OperationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (olr OperationListResult) IsEmpty() bool { - return olr.Value == nil || len(*olr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (olr OperationListResult) hasNextLink() bool { - return olr.NextLink != nil && len(*olr.NextLink) != 0 -} - -// operationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (olr OperationListResult) operationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !olr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(olr.NextLink))) -} - -// OperationListResultPage contains a page of Operation values. -type OperationListResultPage struct { - fn func(context.Context, OperationListResult) (OperationListResult, error) - olr OperationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.olr) - if err != nil { - return err - } - page.olr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *OperationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the OperationListResultPage type. -func NewOperationListResultPage(cur OperationListResult, getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage { - return OperationListResultPage{ - fn: getNextPage, - olr: cur, - } -} - -// Port the port exposed on the container group. -type Port struct { - // Protocol - The protocol associated with the port. Possible values include: 'ContainerGroupNetworkProtocolTCP', 'ContainerGroupNetworkProtocolUDP' - Protocol ContainerGroupNetworkProtocol `json:"protocol,omitempty"` - // Port - The port number. - Port *int32 `json:"port,omitempty"` -} - -// Resource the Resource model definition. -type Resource struct { - // ID - READ-ONLY; The resource id. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The resource type. - Type *string `json:"type,omitempty"` - // Location - The resource location. - Location *string `json:"location,omitempty"` - // Tags - The resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.Location != nil { - objectMap["location"] = r.Location - } - if r.Tags != nil { - objectMap["tags"] = r.Tags - } - return json.Marshal(objectMap) -} - -// ResourceLimits the resource limits. -type ResourceLimits struct { - // MemoryInGB - The memory limit in GB of this container instance. - MemoryInGB *float64 `json:"memoryInGB,omitempty"` - // CPU - The CPU limit of this container instance. - CPU *float64 `json:"cpu,omitempty"` - // Gpu - The GPU limit of this container instance. - Gpu *GpuResource `json:"gpu,omitempty"` -} - -// ResourceRequests the resource requests. -type ResourceRequests struct { - // MemoryInGB - The memory request in GB of this container instance. - MemoryInGB *float64 `json:"memoryInGB,omitempty"` - // CPU - The CPU request of this container instance. - CPU *float64 `json:"cpu,omitempty"` - // Gpu - The GPU request of this container instance. - Gpu *GpuResource `json:"gpu,omitempty"` -} - -// ResourceRequirements the resource requirements. -type ResourceRequirements struct { - // Requests - The resource requests of this container instance. - Requests *ResourceRequests `json:"requests,omitempty"` - // Limits - The resource limits of this container instance. - Limits *ResourceLimits `json:"limits,omitempty"` -} - -// Usage a single usage result -type Usage struct { - // Unit - READ-ONLY; Unit of the usage result - Unit *string `json:"unit,omitempty"` - // CurrentValue - READ-ONLY; The current usage of the resource - CurrentValue *int32 `json:"currentValue,omitempty"` - // Limit - READ-ONLY; The maximum permitted usage of the resource. - Limit *int32 `json:"limit,omitempty"` - // Name - READ-ONLY; The name object of the resource - Name *UsageName `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for Usage. -func (u Usage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// UsageListResult the response containing the usage data -type UsageListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; The usage data. - Value *[]Usage `json:"value,omitempty"` -} - -// MarshalJSON is the custom marshaler for UsageListResult. -func (ulr UsageListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// UsageName the name object of the resource -type UsageName struct { - // Value - READ-ONLY; The name of the resource - Value *string `json:"value,omitempty"` - // LocalizedValue - READ-ONLY; The localized name of the resource - LocalizedValue *string `json:"localizedValue,omitempty"` -} - -// MarshalJSON is the custom marshaler for UsageName. -func (u UsageName) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Volume the properties of the volume. -type Volume struct { - // Name - The name of the volume. - Name *string `json:"name,omitempty"` - // AzureFile - The Azure File volume. - AzureFile *AzureFileVolume `json:"azureFile,omitempty"` - // EmptyDir - The empty directory volume. - EmptyDir interface{} `json:"emptyDir,omitempty"` - // Secret - The secret volume. - Secret map[string]*string `json:"secret"` - // GitRepo - The git repo volume. - GitRepo *GitRepoVolume `json:"gitRepo,omitempty"` -} - -// MarshalJSON is the custom marshaler for Volume. -func (vVar Volume) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vVar.Name != nil { - objectMap["name"] = vVar.Name - } - if vVar.AzureFile != nil { - objectMap["azureFile"] = vVar.AzureFile - } - if vVar.EmptyDir != nil { - objectMap["emptyDir"] = vVar.EmptyDir - } - if vVar.Secret != nil { - objectMap["secret"] = vVar.Secret - } - if vVar.GitRepo != nil { - objectMap["gitRepo"] = vVar.GitRepo - } - return json.Marshal(objectMap) -} - -// VolumeMount the properties of the volume mount. -type VolumeMount struct { - // Name - The name of the volume mount. - Name *string `json:"name,omitempty"` - // MountPath - The path within the container where the volume should be mounted. Must not contain colon (:). - MountPath *string `json:"mountPath,omitempty"` - // ReadOnly - The flag indicating whether the volume mount is read-only. - ReadOnly *bool `json:"readOnly,omitempty"` -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/operations.go deleted file mode 100644 index 8fc9d678e100..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/operations.go +++ /dev/null @@ -1,140 +0,0 @@ -package containerinstance - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// OperationsClient is the client for the Operations methods of the Containerinstance service. -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 using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List list the operations for Azure Container Instance service. -func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.olr.Response.Response != nil { - sc = result.olr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.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, "containerinstance.OperationsClient", "List", resp, "Failure sending request") - return - } - - result.olr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.OperationsClient", "List", resp, "Failure responding to request") - return - } - if result.olr.hasNextLink() && result.olr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2021-03-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.ContainerInstance/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 client.Send(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, - 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(ctx context.Context, lastResults OperationListResult) (result OperationListResult, err error) { - req, err := lastResults.operationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "containerinstance.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, "containerinstance.OperationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerinstance.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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/version.go deleted file mode 100644 index 4b1d585d377e..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2021-03-01/containerinstance/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package containerinstance - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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() + " containerinstance/2021-03-01" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/CHANGELOG.md deleted file mode 100644 index 52911e4cc5e4..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/_meta.json deleted file mode 100644 index 396dfe385522..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "a95079cdd7a60c5af0417360b1ee56c8ae845cc4", - "readme": "/_/azure-rest-api-specs/specification/azure-kusto/resource-manager/readme.md", - "tag": "package-2021-08-27", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-2021-08-27 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix /_/azure-rest-api-specs/specification/azure-kusto/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/attacheddatabaseconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/attacheddatabaseconfigurations.go deleted file mode 100644 index af9da01d7883..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/attacheddatabaseconfigurations.go +++ /dev/null @@ -1,449 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AttachedDatabaseConfigurationsClient is the the Azure Kusto management API provides a RESTful set of web services -// that interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, -// update, and delete clusters and databases. -type AttachedDatabaseConfigurationsClient struct { - BaseClient -} - -// NewAttachedDatabaseConfigurationsClient creates an instance of the AttachedDatabaseConfigurationsClient client. -func NewAttachedDatabaseConfigurationsClient(subscriptionID string) AttachedDatabaseConfigurationsClient { - return NewAttachedDatabaseConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAttachedDatabaseConfigurationsClientWithBaseURI creates an instance of the AttachedDatabaseConfigurationsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewAttachedDatabaseConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) AttachedDatabaseConfigurationsClient { - return AttachedDatabaseConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckNameAvailability checks that the attached database configuration resource name is valid and is not already in -// use. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// resourceName - the name of the resource. -func (client AttachedDatabaseConfigurationsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, resourceName AttachedDatabaseConfigurationsCheckNameRequest) (result CheckNameResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceName, - Constraints: []validation.Constraint{{Target: "resourceName.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "resourceName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("kusto.AttachedDatabaseConfigurationsClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, resourceName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client AttachedDatabaseConfigurationsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, resourceName AttachedDatabaseConfigurationsCheckNameRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/attachedDatabaseConfigurationCheckNameAvailability", pathParameters), - autorest.WithJSON(resourceName), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client AttachedDatabaseConfigurationsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client AttachedDatabaseConfigurationsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates an attached database configuration. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// attachedDatabaseConfigurationName - the name of the attached database configuration. -// parameters - the database parameters supplied to the CreateOrUpdate operation. -func (client AttachedDatabaseConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string, parameters AttachedDatabaseConfiguration) (result AttachedDatabaseConfigurationsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.AttachedDatabaseConfigurationProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.AttachedDatabaseConfigurationProperties.DatabaseName", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.AttachedDatabaseConfigurationProperties.ClusterResourceID", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("kusto.AttachedDatabaseConfigurationsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, attachedDatabaseConfigurationName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client AttachedDatabaseConfigurationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string, parameters AttachedDatabaseConfiguration) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "attachedDatabaseConfigurationName": autorest.Encode("path", attachedDatabaseConfigurationName), - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/attachedDatabaseConfigurations/{attachedDatabaseConfigurationName}", 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 AttachedDatabaseConfigurationsClient) CreateOrUpdateSender(req *http.Request) (future AttachedDatabaseConfigurationsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client AttachedDatabaseConfigurationsClient) CreateOrUpdateResponder(resp *http.Response) (result AttachedDatabaseConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the attached database configuration with the given name. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// attachedDatabaseConfigurationName - the name of the attached database configuration. -func (client AttachedDatabaseConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string) (result AttachedDatabaseConfigurationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, attachedDatabaseConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client AttachedDatabaseConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "attachedDatabaseConfigurationName": autorest.Encode("path", attachedDatabaseConfigurationName), - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/attachedDatabaseConfigurations/{attachedDatabaseConfigurationName}", 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 AttachedDatabaseConfigurationsClient) DeleteSender(req *http.Request) (future AttachedDatabaseConfigurationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client AttachedDatabaseConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get returns an attached database configuration. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// attachedDatabaseConfigurationName - the name of the attached database configuration. -func (client AttachedDatabaseConfigurationsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string) (result AttachedDatabaseConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, attachedDatabaseConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client AttachedDatabaseConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, attachedDatabaseConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "attachedDatabaseConfigurationName": autorest.Encode("path", attachedDatabaseConfigurationName), - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/attachedDatabaseConfigurations/{attachedDatabaseConfigurationName}", 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 AttachedDatabaseConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client AttachedDatabaseConfigurationsClient) GetResponder(resp *http.Response) (result AttachedDatabaseConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByCluster returns the list of attached database configurations of the given Kusto cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client AttachedDatabaseConfigurationsClient) ListByCluster(ctx context.Context, resourceGroupName string, clusterName string) (result AttachedDatabaseConfigurationListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AttachedDatabaseConfigurationsClient.ListByCluster") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListByClusterPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "ListByCluster", nil, "Failure preparing request") - return - } - - resp, err := client.ListByClusterSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "ListByCluster", resp, "Failure sending request") - return - } - - result, err = client.ListByClusterResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsClient", "ListByCluster", resp, "Failure responding to request") - return - } - - return -} - -// ListByClusterPreparer prepares the ListByCluster request. -func (client AttachedDatabaseConfigurationsClient) ListByClusterPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/attachedDatabaseConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByClusterSender sends the ListByCluster request. The method will close the -// http.Response Body if it receives an error. -func (client AttachedDatabaseConfigurationsClient) ListByClusterSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByClusterResponder handles the response to the ListByCluster request. The method always -// closes the http.Response Body. -func (client AttachedDatabaseConfigurationsClient) ListByClusterResponder(resp *http.Response) (result AttachedDatabaseConfigurationListResult, err error) { - err = autorest.Respond( - resp, - 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/kusto/mgmt/2021-08-27/kusto/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/client.go deleted file mode 100644 index 01afe5762990..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/client.go +++ /dev/null @@ -1,42 +0,0 @@ -// Package kusto implements the Azure ARM Kusto service API version 2021-08-27. -// -// The Azure Kusto management API provides a RESTful set of web services that interact with Azure Kusto services to -// manage your clusters and databases. The API enables you to create, update, and delete clusters and databases. -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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 Kusto - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Kusto. -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 using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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/kusto/mgmt/2021-08-27/kusto/clusterprincipalassignments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/clusterprincipalassignments.go deleted file mode 100644 index 30661bbda56e..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/clusterprincipalassignments.go +++ /dev/null @@ -1,446 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ClusterPrincipalAssignmentsClient is the the Azure Kusto management API provides a RESTful set of web services that -// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and -// delete clusters and databases. -type ClusterPrincipalAssignmentsClient struct { - BaseClient -} - -// NewClusterPrincipalAssignmentsClient creates an instance of the ClusterPrincipalAssignmentsClient client. -func NewClusterPrincipalAssignmentsClient(subscriptionID string) ClusterPrincipalAssignmentsClient { - return NewClusterPrincipalAssignmentsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewClusterPrincipalAssignmentsClientWithBaseURI creates an instance of the ClusterPrincipalAssignmentsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewClusterPrincipalAssignmentsClientWithBaseURI(baseURI string, subscriptionID string) ClusterPrincipalAssignmentsClient { - return ClusterPrincipalAssignmentsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckNameAvailability checks that the principal assignment name is valid and is not already in use. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// principalAssignmentName - the name of the principal assignment. -func (client ClusterPrincipalAssignmentsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName ClusterPrincipalAssignmentCheckNameRequest) (result CheckNameResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: principalAssignmentName, - Constraints: []validation.Constraint{{Target: "principalAssignmentName.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "principalAssignmentName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("kusto.ClusterPrincipalAssignmentsClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, principalAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client ClusterPrincipalAssignmentsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName ClusterPrincipalAssignmentCheckNameRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/checkPrincipalAssignmentNameAvailability", pathParameters), - autorest.WithJSON(principalAssignmentName), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client ClusterPrincipalAssignmentsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client ClusterPrincipalAssignmentsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate create a Kusto cluster principalAssignment. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// principalAssignmentName - the name of the Kusto principalAssignment. -// parameters - the Kusto cluster principalAssignment's parameters supplied for the operation. -func (client ClusterPrincipalAssignmentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string, parameters ClusterPrincipalAssignment) (result ClusterPrincipalAssignmentsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ClusterPrincipalProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ClusterPrincipalProperties.PrincipalID", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewError("kusto.ClusterPrincipalAssignmentsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, principalAssignmentName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ClusterPrincipalAssignmentsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string, parameters ClusterPrincipalAssignment) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "principalAssignmentName": autorest.Encode("path", principalAssignmentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/principalAssignments/{principalAssignmentName}", 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 ClusterPrincipalAssignmentsClient) CreateOrUpdateSender(req *http.Request) (future ClusterPrincipalAssignmentsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ClusterPrincipalAssignmentsClient) CreateOrUpdateResponder(resp *http.Response) (result ClusterPrincipalAssignment, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a Kusto cluster principalAssignment. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// principalAssignmentName - the name of the Kusto principalAssignment. -func (client ClusterPrincipalAssignmentsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string) (result ClusterPrincipalAssignmentsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, principalAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ClusterPrincipalAssignmentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "principalAssignmentName": autorest.Encode("path", principalAssignmentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/principalAssignments/{principalAssignmentName}", 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 ClusterPrincipalAssignmentsClient) DeleteSender(req *http.Request) (future ClusterPrincipalAssignmentsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ClusterPrincipalAssignmentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a Kusto cluster principalAssignment. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// principalAssignmentName - the name of the Kusto principalAssignment. -func (client ClusterPrincipalAssignmentsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string) (result ClusterPrincipalAssignment, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, principalAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ClusterPrincipalAssignmentsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, principalAssignmentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "principalAssignmentName": autorest.Encode("path", principalAssignmentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/principalAssignments/{principalAssignmentName}", 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 ClusterPrincipalAssignmentsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ClusterPrincipalAssignmentsClient) GetResponder(resp *http.Response) (result ClusterPrincipalAssignment, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all Kusto cluster principalAssignments. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClusterPrincipalAssignmentsClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result ClusterPrincipalAssignmentListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClusterPrincipalAssignmentsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ClusterPrincipalAssignmentsClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/principalAssignments", 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 ClusterPrincipalAssignmentsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ClusterPrincipalAssignmentsClient) ListResponder(resp *http.Response) (result ClusterPrincipalAssignmentListResult, err error) { - err = autorest.Respond( - resp, - 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/kusto/mgmt/2021-08-27/kusto/clusters.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/clusters.go deleted file mode 100644 index bfc46d3fbfa0..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/clusters.go +++ /dev/null @@ -1,1525 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ClustersClient is the the Azure Kusto management API provides a RESTful set of web services that interact with Azure -// Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and -// databases. -type ClustersClient struct { - BaseClient -} - -// NewClustersClient creates an instance of the ClustersClient client. -func NewClustersClient(subscriptionID string) ClustersClient { - return NewClustersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewClustersClientWithBaseURI creates an instance of the ClustersClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewClustersClientWithBaseURI(baseURI string, subscriptionID string) ClustersClient { - return ClustersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// AddLanguageExtensions add a list of language extensions that can run within KQL queries. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// languageExtensionsToAdd - the language extensions to add. -func (client ClustersClient) AddLanguageExtensions(ctx context.Context, resourceGroupName string, clusterName string, languageExtensionsToAdd LanguageExtensionsList) (result ClustersAddLanguageExtensionsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.AddLanguageExtensions") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.AddLanguageExtensionsPreparer(ctx, resourceGroupName, clusterName, languageExtensionsToAdd) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "AddLanguageExtensions", nil, "Failure preparing request") - return - } - - result, err = client.AddLanguageExtensionsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "AddLanguageExtensions", result.Response(), "Failure sending request") - return - } - - return -} - -// AddLanguageExtensionsPreparer prepares the AddLanguageExtensions request. -func (client ClustersClient) AddLanguageExtensionsPreparer(ctx context.Context, resourceGroupName string, clusterName string, languageExtensionsToAdd LanguageExtensionsList) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/addLanguageExtensions", pathParameters), - autorest.WithJSON(languageExtensionsToAdd), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// AddLanguageExtensionsSender sends the AddLanguageExtensions request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) AddLanguageExtensionsSender(req *http.Request) (future ClustersAddLanguageExtensionsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// AddLanguageExtensionsResponder handles the response to the AddLanguageExtensions request. The method always -// closes the http.Response Body. -func (client ClustersClient) AddLanguageExtensionsResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// CheckNameAvailability checks that the cluster name is valid and is not already in use. -// Parameters: -// location - azure location (region) name. -// clusterName - the name of the cluster. -func (client ClustersClient) CheckNameAvailability(ctx context.Context, location string, clusterName ClusterCheckNameRequest) (result CheckNameResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: clusterName, - Constraints: []validation.Constraint{{Target: "clusterName.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "clusterName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("kusto.ClustersClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, location, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client ClustersClient) CheckNameAvailabilityPreparer(ctx context.Context, location string, clusterName ClusterCheckNameRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/locations/{location}/checkNameAvailability", pathParameters), - autorest.WithJSON(clusterName), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client ClustersClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate create or update a Kusto cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// parameters - the Kusto cluster parameters supplied to the CreateOrUpdate operation. -// ifMatch - the ETag of the cluster. Omit this value to always overwrite the current cluster. Specify the -// last-seen ETag value to prevent accidentally overwriting concurrent changes. -// ifNoneMatch - set to '*' to allow a new cluster to be created, but to prevent updating an existing cluster. -// Other values will result in a 412 Pre-condition Failed response. -func (client ClustersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, parameters Cluster, ifMatch string, ifNoneMatch string) (result ClustersCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Sku", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ClusterProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.OptimizedAutoscale", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.OptimizedAutoscale.Version", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ClusterProperties.OptimizedAutoscale.IsEnabled", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ClusterProperties.OptimizedAutoscale.Minimum", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ClusterProperties.OptimizedAutoscale.Maximum", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "parameters.ClusterProperties.VirtualNetworkConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.VirtualNetworkConfiguration.SubnetID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ClusterProperties.VirtualNetworkConfiguration.EnginePublicIPID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ClusterProperties.VirtualNetworkConfiguration.DataManagementPublicIPID", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("kusto.ClustersClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, parameters, ifMatch, ifNoneMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ClustersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, parameters Cluster, ifMatch string, ifNoneMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - if len(ifNoneMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-None-Match", autorest.String(ifNoneMatch))) - } - 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 ClustersClient) CreateOrUpdateSender(req *http.Request) (future ClustersCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ClustersClient) CreateOrUpdateResponder(resp *http.Response) (result Cluster, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a Kusto cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClustersClient) Delete(ctx context.Context, resourceGroupName string, clusterName string) (result ClustersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ClustersClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}", 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 ClustersClient) DeleteSender(req *http.Request) (future ClustersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ClustersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// DetachFollowerDatabases detaches all followers of a database owned by this cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// followerDatabaseToRemove - the follower databases properties to remove. -func (client ClustersClient) DetachFollowerDatabases(ctx context.Context, resourceGroupName string, clusterName string, followerDatabaseToRemove FollowerDatabaseDefinition) (result ClustersDetachFollowerDatabasesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.DetachFollowerDatabases") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: followerDatabaseToRemove, - Constraints: []validation.Constraint{{Target: "followerDatabaseToRemove.ClusterResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "followerDatabaseToRemove.AttachedDatabaseConfigurationName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("kusto.ClustersClient", "DetachFollowerDatabases", err.Error()) - } - - req, err := client.DetachFollowerDatabasesPreparer(ctx, resourceGroupName, clusterName, followerDatabaseToRemove) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "DetachFollowerDatabases", nil, "Failure preparing request") - return - } - - result, err = client.DetachFollowerDatabasesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "DetachFollowerDatabases", result.Response(), "Failure sending request") - return - } - - return -} - -// DetachFollowerDatabasesPreparer prepares the DetachFollowerDatabases request. -func (client ClustersClient) DetachFollowerDatabasesPreparer(ctx context.Context, resourceGroupName string, clusterName string, followerDatabaseToRemove FollowerDatabaseDefinition) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - followerDatabaseToRemove.DatabaseName = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/detachFollowerDatabases", pathParameters), - autorest.WithJSON(followerDatabaseToRemove), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DetachFollowerDatabasesSender sends the DetachFollowerDatabases request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) DetachFollowerDatabasesSender(req *http.Request) (future ClustersDetachFollowerDatabasesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DetachFollowerDatabasesResponder handles the response to the DetachFollowerDatabases request. The method always -// closes the http.Response Body. -func (client ClustersClient) DetachFollowerDatabasesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// DiagnoseVirtualNetwork diagnoses network connectivity status for external resources on which the service is -// dependent on. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClustersClient) DiagnoseVirtualNetwork(ctx context.Context, resourceGroupName string, clusterName string) (result ClustersDiagnoseVirtualNetworkFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.DiagnoseVirtualNetwork") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DiagnoseVirtualNetworkPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "DiagnoseVirtualNetwork", nil, "Failure preparing request") - return - } - - result, err = client.DiagnoseVirtualNetworkSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "DiagnoseVirtualNetwork", result.Response(), "Failure sending request") - return - } - - return -} - -// DiagnoseVirtualNetworkPreparer prepares the DiagnoseVirtualNetwork request. -func (client ClustersClient) DiagnoseVirtualNetworkPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/diagnoseVirtualNetwork", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DiagnoseVirtualNetworkSender sends the DiagnoseVirtualNetwork request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) DiagnoseVirtualNetworkSender(req *http.Request) (future ClustersDiagnoseVirtualNetworkFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DiagnoseVirtualNetworkResponder handles the response to the DiagnoseVirtualNetwork request. The method always -// closes the http.Response Body. -func (client ClustersClient) DiagnoseVirtualNetworkResponder(resp *http.Response) (result DiagnoseVirtualNetworkResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get gets a Kusto cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClustersClient) Get(ctx context.Context, resourceGroupName string, clusterName string) (result Cluster, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ClustersClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}", 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 ClustersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ClustersClient) GetResponder(resp *http.Response) (result Cluster, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all Kusto clusters within a subscription. -func (client ClustersClient) List(ctx context.Context) (result ClusterListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ClustersClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Kusto/clusters", 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 ClustersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ClustersClient) ListResponder(resp *http.Response) (result ClusterListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByResourceGroup lists all Kusto clusters within a resource group. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -func (client ClustersClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ClusterListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ClustersClient) 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 = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters", 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 ClustersClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ClustersClient) ListByResourceGroupResponder(resp *http.Response) (result ClusterListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListFollowerDatabases returns a list of databases that are owned by this cluster and were followed by another -// cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClustersClient) ListFollowerDatabases(ctx context.Context, resourceGroupName string, clusterName string) (result FollowerDatabaseListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListFollowerDatabases") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListFollowerDatabasesPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListFollowerDatabases", nil, "Failure preparing request") - return - } - - resp, err := client.ListFollowerDatabasesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListFollowerDatabases", resp, "Failure sending request") - return - } - - result, err = client.ListFollowerDatabasesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListFollowerDatabases", resp, "Failure responding to request") - return - } - - return -} - -// ListFollowerDatabasesPreparer prepares the ListFollowerDatabases request. -func (client ClustersClient) ListFollowerDatabasesPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/listFollowerDatabases", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListFollowerDatabasesSender sends the ListFollowerDatabases request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) ListFollowerDatabasesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListFollowerDatabasesResponder handles the response to the ListFollowerDatabases request. The method always -// closes the http.Response Body. -func (client ClustersClient) ListFollowerDatabasesResponder(resp *http.Response) (result FollowerDatabaseListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListLanguageExtensions returns a list of language extensions that can run within KQL queries. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClustersClient) ListLanguageExtensions(ctx context.Context, resourceGroupName string, clusterName string) (result LanguageExtensionsList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListLanguageExtensions") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListLanguageExtensionsPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListLanguageExtensions", nil, "Failure preparing request") - return - } - - resp, err := client.ListLanguageExtensionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListLanguageExtensions", resp, "Failure sending request") - return - } - - result, err = client.ListLanguageExtensionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListLanguageExtensions", resp, "Failure responding to request") - return - } - - return -} - -// ListLanguageExtensionsPreparer prepares the ListLanguageExtensions request. -func (client ClustersClient) ListLanguageExtensionsPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/listLanguageExtensions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListLanguageExtensionsSender sends the ListLanguageExtensions request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) ListLanguageExtensionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListLanguageExtensionsResponder handles the response to the ListLanguageExtensions request. The method always -// closes the http.Response Body. -func (client ClustersClient) ListLanguageExtensionsResponder(resp *http.Response) (result LanguageExtensionsList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListOutboundNetworkDependenciesEndpoints gets the network endpoints of all outbound dependencies of a Kusto cluster -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClustersClient) ListOutboundNetworkDependenciesEndpoints(ctx context.Context, resourceGroupName string, clusterName string) (result OutboundNetworkDependenciesEndpointListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListOutboundNetworkDependenciesEndpoints") - defer func() { - sc := -1 - if result.ondelr.Response.Response != nil { - sc = result.ondelr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listOutboundNetworkDependenciesEndpointsNextResults - req, err := client.ListOutboundNetworkDependenciesEndpointsPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListOutboundNetworkDependenciesEndpoints", nil, "Failure preparing request") - return - } - - resp, err := client.ListOutboundNetworkDependenciesEndpointsSender(req) - if err != nil { - result.ondelr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListOutboundNetworkDependenciesEndpoints", resp, "Failure sending request") - return - } - - result.ondelr, err = client.ListOutboundNetworkDependenciesEndpointsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListOutboundNetworkDependenciesEndpoints", resp, "Failure responding to request") - return - } - if result.ondelr.hasNextLink() && result.ondelr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListOutboundNetworkDependenciesEndpointsPreparer prepares the ListOutboundNetworkDependenciesEndpoints request. -func (client ClustersClient) ListOutboundNetworkDependenciesEndpointsPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/outboundNetworkDependenciesEndpoints", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListOutboundNetworkDependenciesEndpointsSender sends the ListOutboundNetworkDependenciesEndpoints request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) ListOutboundNetworkDependenciesEndpointsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListOutboundNetworkDependenciesEndpointsResponder handles the response to the ListOutboundNetworkDependenciesEndpoints request. The method always -// closes the http.Response Body. -func (client ClustersClient) ListOutboundNetworkDependenciesEndpointsResponder(resp *http.Response) (result OutboundNetworkDependenciesEndpointListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listOutboundNetworkDependenciesEndpointsNextResults retrieves the next set of results, if any. -func (client ClustersClient) listOutboundNetworkDependenciesEndpointsNextResults(ctx context.Context, lastResults OutboundNetworkDependenciesEndpointListResult) (result OutboundNetworkDependenciesEndpointListResult, err error) { - req, err := lastResults.outboundNetworkDependenciesEndpointListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "kusto.ClustersClient", "listOutboundNetworkDependenciesEndpointsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListOutboundNetworkDependenciesEndpointsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "kusto.ClustersClient", "listOutboundNetworkDependenciesEndpointsNextResults", resp, "Failure sending next results request") - } - result, err = client.ListOutboundNetworkDependenciesEndpointsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "listOutboundNetworkDependenciesEndpointsNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListOutboundNetworkDependenciesEndpointsComplete enumerates all values, automatically crossing page boundaries as required. -func (client ClustersClient) ListOutboundNetworkDependenciesEndpointsComplete(ctx context.Context, resourceGroupName string, clusterName string) (result OutboundNetworkDependenciesEndpointListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListOutboundNetworkDependenciesEndpoints") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListOutboundNetworkDependenciesEndpoints(ctx, resourceGroupName, clusterName) - return -} - -// ListSkus lists eligible SKUs for Kusto resource provider. -func (client ClustersClient) ListSkus(ctx context.Context) (result SkuDescriptionList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListSkus") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListSkusPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkus", nil, "Failure preparing request") - return - } - - resp, err := client.ListSkusSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkus", resp, "Failure sending request") - return - } - - result, err = client.ListSkusResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkus", resp, "Failure responding to request") - return - } - - return -} - -// ListSkusPreparer prepares the ListSkus request. -func (client ClustersClient) ListSkusPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Kusto/skus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSkusSender sends the ListSkus request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) ListSkusSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListSkusResponder handles the response to the ListSkus request. The method always -// closes the http.Response Body. -func (client ClustersClient) ListSkusResponder(resp *http.Response) (result SkuDescriptionList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListSkusByResource returns the SKUs available for the provided resource. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClustersClient) ListSkusByResource(ctx context.Context, resourceGroupName string, clusterName string) (result ListResourceSkusResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.ListSkusByResource") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListSkusByResourcePreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkusByResource", nil, "Failure preparing request") - return - } - - resp, err := client.ListSkusByResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkusByResource", resp, "Failure sending request") - return - } - - result, err = client.ListSkusByResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "ListSkusByResource", resp, "Failure responding to request") - return - } - - return -} - -// ListSkusByResourcePreparer prepares the ListSkusByResource request. -func (client ClustersClient) ListSkusByResourcePreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/skus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSkusByResourceSender sends the ListSkusByResource request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) ListSkusByResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListSkusByResourceResponder handles the response to the ListSkusByResource request. The method always -// closes the http.Response Body. -func (client ClustersClient) ListSkusByResourceResponder(resp *http.Response) (result ListResourceSkusResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// RemoveLanguageExtensions remove a list of language extensions that can run within KQL queries. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// languageExtensionsToRemove - the language extensions to remove. -func (client ClustersClient) RemoveLanguageExtensions(ctx context.Context, resourceGroupName string, clusterName string, languageExtensionsToRemove LanguageExtensionsList) (result ClustersRemoveLanguageExtensionsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.RemoveLanguageExtensions") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RemoveLanguageExtensionsPreparer(ctx, resourceGroupName, clusterName, languageExtensionsToRemove) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "RemoveLanguageExtensions", nil, "Failure preparing request") - return - } - - result, err = client.RemoveLanguageExtensionsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "RemoveLanguageExtensions", result.Response(), "Failure sending request") - return - } - - return -} - -// RemoveLanguageExtensionsPreparer prepares the RemoveLanguageExtensions request. -func (client ClustersClient) RemoveLanguageExtensionsPreparer(ctx context.Context, resourceGroupName string, clusterName string, languageExtensionsToRemove LanguageExtensionsList) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/removeLanguageExtensions", pathParameters), - autorest.WithJSON(languageExtensionsToRemove), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RemoveLanguageExtensionsSender sends the RemoveLanguageExtensions request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) RemoveLanguageExtensionsSender(req *http.Request) (future ClustersRemoveLanguageExtensionsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RemoveLanguageExtensionsResponder handles the response to the RemoveLanguageExtensions request. The method always -// closes the http.Response Body. -func (client ClustersClient) RemoveLanguageExtensionsResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Start starts a Kusto cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClustersClient) Start(ctx context.Context, resourceGroupName string, clusterName string) (result ClustersStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client ClustersClient) StartPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) StartSender(req *http.Request) (future ClustersStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client ClustersClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Stop stops a Kusto cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ClustersClient) Stop(ctx context.Context, resourceGroupName string, clusterName string) (result ClustersStopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Stop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Stop", nil, "Failure preparing request") - return - } - - result, err = client.StopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Stop", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client ClustersClient) StopPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/stop", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopSender sends the Stop request. The method will close the -// http.Response Body if it receives an error. -func (client ClustersClient) StopSender(req *http.Request) (future ClustersStopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopResponder handles the response to the Stop request. The method always -// closes the http.Response Body. -func (client ClustersClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update update a Kusto cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// parameters - the Kusto cluster parameters supplied to the Update operation. -// ifMatch - the ETag of the cluster. Omit this value to always overwrite the current cluster. Specify the -// last-seen ETag value to prevent accidentally overwriting concurrent changes. -func (client ClustersClient) Update(ctx context.Context, resourceGroupName string, clusterName string, parameters ClusterUpdate, ifMatch string) (result ClustersUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ClustersClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, parameters, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ClustersClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, parameters ClusterUpdate, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - 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 ClustersClient) UpdateSender(req *http.Request) (future ClustersUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ClustersClient) UpdateResponder(resp *http.Response) (result Cluster, err error) { - err = autorest.Respond( - resp, - 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/kusto/mgmt/2021-08-27/kusto/databaseprincipalassignments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/databaseprincipalassignments.go deleted file mode 100644 index c1371fcd4d6e..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/databaseprincipalassignments.go +++ /dev/null @@ -1,456 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DatabasePrincipalAssignmentsClient is the the Azure Kusto management API provides a RESTful set of web services that -// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and -// delete clusters and databases. -type DatabasePrincipalAssignmentsClient struct { - BaseClient -} - -// NewDatabasePrincipalAssignmentsClient creates an instance of the DatabasePrincipalAssignmentsClient client. -func NewDatabasePrincipalAssignmentsClient(subscriptionID string) DatabasePrincipalAssignmentsClient { - return NewDatabasePrincipalAssignmentsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDatabasePrincipalAssignmentsClientWithBaseURI creates an instance of the DatabasePrincipalAssignmentsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewDatabasePrincipalAssignmentsClientWithBaseURI(baseURI string, subscriptionID string) DatabasePrincipalAssignmentsClient { - return DatabasePrincipalAssignmentsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckNameAvailability checks that the database principal assignment is valid and is not already in use. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// principalAssignmentName - the name of the resource. -func (client DatabasePrincipalAssignmentsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName DatabasePrincipalAssignmentCheckNameRequest) (result CheckNameResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: principalAssignmentName, - Constraints: []validation.Constraint{{Target: "principalAssignmentName.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "principalAssignmentName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("kusto.DatabasePrincipalAssignmentsClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, databaseName, principalAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client DatabasePrincipalAssignmentsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName DatabasePrincipalAssignmentCheckNameRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}/checkPrincipalAssignmentNameAvailability", pathParameters), - autorest.WithJSON(principalAssignmentName), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client DatabasePrincipalAssignmentsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client DatabasePrincipalAssignmentsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates a Kusto cluster database principalAssignment. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// principalAssignmentName - the name of the Kusto principalAssignment. -// parameters - the Kusto principalAssignments parameters supplied for the operation. -func (client DatabasePrincipalAssignmentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string, parameters DatabasePrincipalAssignment) (result DatabasePrincipalAssignmentsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.DatabasePrincipalProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.DatabasePrincipalProperties.PrincipalID", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewError("kusto.DatabasePrincipalAssignmentsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, principalAssignmentName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DatabasePrincipalAssignmentsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string, parameters DatabasePrincipalAssignment) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "principalAssignmentName": autorest.Encode("path", principalAssignmentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}", 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 DatabasePrincipalAssignmentsClient) CreateOrUpdateSender(req *http.Request) (future DatabasePrincipalAssignmentsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DatabasePrincipalAssignmentsClient) CreateOrUpdateResponder(resp *http.Response) (result DatabasePrincipalAssignment, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a Kusto principalAssignment. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// principalAssignmentName - the name of the Kusto principalAssignment. -func (client DatabasePrincipalAssignmentsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string) (result DatabasePrincipalAssignmentsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName, principalAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DatabasePrincipalAssignmentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "principalAssignmentName": autorest.Encode("path", principalAssignmentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}", 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 DatabasePrincipalAssignmentsClient) DeleteSender(req *http.Request) (future DatabasePrincipalAssignmentsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DatabasePrincipalAssignmentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a Kusto cluster database principalAssignment. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// principalAssignmentName - the name of the Kusto principalAssignment. -func (client DatabasePrincipalAssignmentsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string) (result DatabasePrincipalAssignment, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName, principalAssignmentName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DatabasePrincipalAssignmentsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, principalAssignmentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "principalAssignmentName": autorest.Encode("path", principalAssignmentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments/{principalAssignmentName}", 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 DatabasePrincipalAssignmentsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DatabasePrincipalAssignmentsClient) GetResponder(resp *http.Response) (result DatabasePrincipalAssignment, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all Kusto cluster database principalAssignments. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -func (client DatabasePrincipalAssignmentsClient) List(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DatabasePrincipalAssignmentListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasePrincipalAssignmentsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, clusterName, databaseName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client DatabasePrincipalAssignmentsClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/principalAssignments", 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 DatabasePrincipalAssignmentsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client DatabasePrincipalAssignmentsClient) ListResponder(resp *http.Response) (result DatabasePrincipalAssignmentListResult, err error) { - err = autorest.Respond( - resp, - 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/kusto/mgmt/2021-08-27/kusto/databases.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/databases.go deleted file mode 100644 index 31f3dbe0bc56..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/databases.go +++ /dev/null @@ -1,761 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DatabasesClient is the the Azure Kusto management API provides a RESTful set of web services that interact with -// Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete -// clusters and databases. -type DatabasesClient struct { - BaseClient -} - -// NewDatabasesClient creates an instance of the DatabasesClient client. -func NewDatabasesClient(subscriptionID string) DatabasesClient { - return NewDatabasesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDatabasesClientWithBaseURI creates an instance of the DatabasesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewDatabasesClientWithBaseURI(baseURI string, subscriptionID string) DatabasesClient { - return DatabasesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// AddPrincipals add Database principals permissions. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// databasePrincipalsToAdd - list of database principals to add. -func (client DatabasesClient) AddPrincipals(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, databasePrincipalsToAdd DatabasePrincipalListRequest) (result DatabasePrincipalListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.AddPrincipals") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.AddPrincipalsPreparer(ctx, resourceGroupName, clusterName, databaseName, databasePrincipalsToAdd) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "AddPrincipals", nil, "Failure preparing request") - return - } - - resp, err := client.AddPrincipalsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "AddPrincipals", resp, "Failure sending request") - return - } - - result, err = client.AddPrincipalsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "AddPrincipals", resp, "Failure responding to request") - return - } - - return -} - -// AddPrincipalsPreparer prepares the AddPrincipals request. -func (client DatabasesClient) AddPrincipalsPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, databasePrincipalsToAdd DatabasePrincipalListRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}/addPrincipals", pathParameters), - autorest.WithJSON(databasePrincipalsToAdd), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// AddPrincipalsSender sends the AddPrincipals request. The method will close the -// http.Response Body if it receives an error. -func (client DatabasesClient) AddPrincipalsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// AddPrincipalsResponder handles the response to the AddPrincipals request. The method always -// closes the http.Response Body. -func (client DatabasesClient) AddPrincipalsResponder(resp *http.Response) (result DatabasePrincipalListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CheckNameAvailability checks that the databases resource name is valid and is not already in use. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// resourceName - the name of the resource. -func (client DatabasesClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, resourceName CheckNameRequest) (result CheckNameResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceName, - Constraints: []validation.Constraint{{Target: "resourceName.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("kusto.DatabasesClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, resourceName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client DatabasesClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, resourceName CheckNameRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/checkNameAvailability", pathParameters), - autorest.WithJSON(resourceName), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client DatabasesClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client DatabasesClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates a database. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// parameters - the database parameters supplied to the CreateOrUpdate operation. -func (client DatabasesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters BasicDatabase) (result DatabasesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DatabasesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters BasicDatabase) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}", 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 DatabasesClient) CreateOrUpdateSender(req *http.Request) (future DatabasesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DatabasesClient) CreateOrUpdateResponder(resp *http.Response) (result DatabaseModel, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the database with the given name. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -func (client DatabasesClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DatabasesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DatabasesClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}", 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 DatabasesClient) DeleteSender(req *http.Request) (future DatabasesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DatabasesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get returns a database. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -func (client DatabasesClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DatabaseModel, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DatabasesClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}", 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 DatabasesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DatabasesClient) GetResponder(resp *http.Response) (result DatabaseModel, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByCluster returns the list of databases of the given Kusto cluster. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client DatabasesClient) ListByCluster(ctx context.Context, resourceGroupName string, clusterName string) (result DatabaseListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.ListByCluster") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListByClusterPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListByCluster", nil, "Failure preparing request") - return - } - - resp, err := client.ListByClusterSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListByCluster", resp, "Failure sending request") - return - } - - result, err = client.ListByClusterResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListByCluster", resp, "Failure responding to request") - return - } - - return -} - -// ListByClusterPreparer prepares the ListByCluster request. -func (client DatabasesClient) ListByClusterPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByClusterSender sends the ListByCluster request. The method will close the -// http.Response Body if it receives an error. -func (client DatabasesClient) ListByClusterSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByClusterResponder handles the response to the ListByCluster request. The method always -// closes the http.Response Body. -func (client DatabasesClient) ListByClusterResponder(resp *http.Response) (result DatabaseListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListPrincipals returns a list of database principals of the given Kusto cluster and database. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -func (client DatabasesClient) ListPrincipals(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DatabasePrincipalListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.ListPrincipals") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPrincipalsPreparer(ctx, resourceGroupName, clusterName, databaseName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListPrincipals", nil, "Failure preparing request") - return - } - - resp, err := client.ListPrincipalsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListPrincipals", resp, "Failure sending request") - return - } - - result, err = client.ListPrincipalsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "ListPrincipals", resp, "Failure responding to request") - return - } - - return -} - -// ListPrincipalsPreparer prepares the ListPrincipals request. -func (client DatabasesClient) ListPrincipalsPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/listPrincipals", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListPrincipalsSender sends the ListPrincipals request. The method will close the -// http.Response Body if it receives an error. -func (client DatabasesClient) ListPrincipalsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListPrincipalsResponder handles the response to the ListPrincipals request. The method always -// closes the http.Response Body. -func (client DatabasesClient) ListPrincipalsResponder(resp *http.Response) (result DatabasePrincipalListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// RemovePrincipals remove Database principals permissions. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// databasePrincipalsToRemove - list of database principals to remove. -func (client DatabasesClient) RemovePrincipals(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, databasePrincipalsToRemove DatabasePrincipalListRequest) (result DatabasePrincipalListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.RemovePrincipals") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RemovePrincipalsPreparer(ctx, resourceGroupName, clusterName, databaseName, databasePrincipalsToRemove) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "RemovePrincipals", nil, "Failure preparing request") - return - } - - resp, err := client.RemovePrincipalsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "RemovePrincipals", resp, "Failure sending request") - return - } - - result, err = client.RemovePrincipalsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "RemovePrincipals", resp, "Failure responding to request") - return - } - - return -} - -// RemovePrincipalsPreparer prepares the RemovePrincipals request. -func (client DatabasesClient) RemovePrincipalsPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, databasePrincipalsToRemove DatabasePrincipalListRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}/removePrincipals", pathParameters), - autorest.WithJSON(databasePrincipalsToRemove), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RemovePrincipalsSender sends the RemovePrincipals request. The method will close the -// http.Response Body if it receives an error. -func (client DatabasesClient) RemovePrincipalsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// RemovePrincipalsResponder handles the response to the RemovePrincipals request. The method always -// closes the http.Response Body. -func (client DatabasesClient) RemovePrincipalsResponder(resp *http.Response) (result DatabasePrincipalListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Update updates a database. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// parameters - the database parameters supplied to the Update operation. -func (client DatabasesClient) Update(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters BasicDatabase) (result DatabasesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DatabasesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client DatabasesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters BasicDatabase) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}", 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 DatabasesClient) UpdateSender(req *http.Request) (future DatabasesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client DatabasesClient) UpdateResponder(resp *http.Response) (result DatabaseModel, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/dataconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/dataconnections.go deleted file mode 100644 index eac77967d8f9..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/dataconnections.go +++ /dev/null @@ -1,618 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DataConnectionsClient is the the Azure Kusto management API provides a RESTful set of web services that interact -// with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete -// clusters and databases. -type DataConnectionsClient struct { - BaseClient -} - -// NewDataConnectionsClient creates an instance of the DataConnectionsClient client. -func NewDataConnectionsClient(subscriptionID string) DataConnectionsClient { - return NewDataConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDataConnectionsClientWithBaseURI creates an instance of the DataConnectionsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewDataConnectionsClientWithBaseURI(baseURI string, subscriptionID string) DataConnectionsClient { - return DataConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckNameAvailability checks that the data connection name is valid and is not already in use. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// dataConnectionName - the name of the data connection. -func (client DataConnectionsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName DataConnectionCheckNameRequest) (result CheckNameResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: dataConnectionName, - Constraints: []validation.Constraint{{Target: "dataConnectionName.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "dataConnectionName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("kusto.DataConnectionsClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client DataConnectionsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName DataConnectionCheckNameRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}/checkNameAvailability", pathParameters), - autorest.WithJSON(dataConnectionName), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client DataConnectionsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client DataConnectionsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates a data connection. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// dataConnectionName - the name of the data connection. -// parameters - the data connection parameters supplied to the CreateOrUpdate operation. -func (client DataConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (result DataConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DataConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "dataConnectionName": autorest.Encode("path", dataConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", 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 DataConnectionsClient) CreateOrUpdateSender(req *http.Request) (future DataConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DataConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result DataConnectionModel, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DataConnectionValidationMethod checks that the data connection parameters are valid. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// parameters - the data connection parameters supplied to the CreateOrUpdate operation. -func (client DataConnectionsClient) DataConnectionValidationMethod(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters DataConnectionValidation) (result DataConnectionsDataConnectionValidationMethodFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.DataConnectionValidationMethod") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DataConnectionValidationMethodPreparer(ctx, resourceGroupName, clusterName, databaseName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", nil, "Failure preparing request") - return - } - - result, err = client.DataConnectionValidationMethodSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "DataConnectionValidationMethod", result.Response(), "Failure sending request") - return - } - - return -} - -// DataConnectionValidationMethodPreparer prepares the DataConnectionValidationMethod request. -func (client DataConnectionsClient) DataConnectionValidationMethodPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, parameters DataConnectionValidation) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnectionValidation", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DataConnectionValidationMethodSender sends the DataConnectionValidationMethod request. The method will close the -// http.Response Body if it receives an error. -func (client DataConnectionsClient) DataConnectionValidationMethodSender(req *http.Request) (future DataConnectionsDataConnectionValidationMethodFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DataConnectionValidationMethodResponder handles the response to the DataConnectionValidationMethod request. The method always -// closes the http.Response Body. -func (client DataConnectionsClient) DataConnectionValidationMethodResponder(resp *http.Response) (result DataConnectionValidationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the data connection with the given name. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// dataConnectionName - the name of the data connection. -func (client DataConnectionsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (result DataConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DataConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "dataConnectionName": autorest.Encode("path", dataConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", 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 DataConnectionsClient) DeleteSender(req *http.Request) (future DataConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DataConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get returns a data connection. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// dataConnectionName - the name of the data connection. -func (client DataConnectionsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (result DataConnectionModel, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DataConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "dataConnectionName": autorest.Encode("path", dataConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", 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 DataConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DataConnectionsClient) GetResponder(resp *http.Response) (result DataConnectionModel, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByDatabase returns the list of data connections of the given Kusto database. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -func (client DataConnectionsClient) ListByDatabase(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result DataConnectionListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.ListByDatabase") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, clusterName, databaseName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", nil, "Failure preparing request") - return - } - - resp, err := client.ListByDatabaseSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", resp, "Failure sending request") - return - } - - result, err = client.ListByDatabaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "ListByDatabase", resp, "Failure responding to request") - return - } - - return -} - -// ListByDatabasePreparer prepares the ListByDatabase request. -func (client DataConnectionsClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByDatabaseSender sends the ListByDatabase request. The method will close the -// http.Response Body if it receives an error. -func (client DataConnectionsClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByDatabaseResponder handles the response to the ListByDatabase request. The method always -// closes the http.Response Body. -func (client DataConnectionsClient) ListByDatabaseResponder(resp *http.Response) (result DataConnectionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Update updates a data connection. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// dataConnectionName - the name of the data connection. -// parameters - the data connection parameters supplied to the Update operation. -func (client DataConnectionsClient) Update(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (result DataConnectionsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DataConnectionsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, dataConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client DataConnectionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, dataConnectionName string, parameters BasicDataConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "dataConnectionName": autorest.Encode("path", dataConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", 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 DataConnectionsClient) UpdateSender(req *http.Request) (future DataConnectionsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client DataConnectionsClient) UpdateResponder(resp *http.Response) (result DataConnectionModel, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/enums.go deleted file mode 100644 index 9c32a1042bf4..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/enums.go +++ /dev/null @@ -1,600 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// AzureScaleType enumerates the values for azure scale type. -type AzureScaleType string - -const ( - // AzureScaleTypeAutomatic ... - AzureScaleTypeAutomatic AzureScaleType = "automatic" - // AzureScaleTypeManual ... - AzureScaleTypeManual AzureScaleType = "manual" - // AzureScaleTypeNone ... - AzureScaleTypeNone AzureScaleType = "none" -) - -// PossibleAzureScaleTypeValues returns an array of possible values for the AzureScaleType const type. -func PossibleAzureScaleTypeValues() []AzureScaleType { - return []AzureScaleType{AzureScaleTypeAutomatic, AzureScaleTypeManual, AzureScaleTypeNone} -} - -// AzureSkuName enumerates the values for azure sku name. -type AzureSkuName string - -const ( - // AzureSkuNameDevNoSLAStandardD11V2 ... - AzureSkuNameDevNoSLAStandardD11V2 AzureSkuName = "Dev(No SLA)_Standard_D11_v2" - // AzureSkuNameDevNoSLAStandardE2aV4 ... - AzureSkuNameDevNoSLAStandardE2aV4 AzureSkuName = "Dev(No SLA)_Standard_E2a_v4" - // AzureSkuNameStandardD11V2 ... - AzureSkuNameStandardD11V2 AzureSkuName = "Standard_D11_v2" - // AzureSkuNameStandardD12V2 ... - AzureSkuNameStandardD12V2 AzureSkuName = "Standard_D12_v2" - // AzureSkuNameStandardD13V2 ... - AzureSkuNameStandardD13V2 AzureSkuName = "Standard_D13_v2" - // AzureSkuNameStandardD14V2 ... - AzureSkuNameStandardD14V2 AzureSkuName = "Standard_D14_v2" - // AzureSkuNameStandardDS13V21TBPS ... - AzureSkuNameStandardDS13V21TBPS AzureSkuName = "Standard_DS13_v2+1TB_PS" - // AzureSkuNameStandardDS13V22TBPS ... - AzureSkuNameStandardDS13V22TBPS AzureSkuName = "Standard_DS13_v2+2TB_PS" - // AzureSkuNameStandardDS14V23TBPS ... - AzureSkuNameStandardDS14V23TBPS AzureSkuName = "Standard_DS14_v2+3TB_PS" - // AzureSkuNameStandardDS14V24TBPS ... - AzureSkuNameStandardDS14V24TBPS AzureSkuName = "Standard_DS14_v2+4TB_PS" - // AzureSkuNameStandardE16asV43TBPS ... - AzureSkuNameStandardE16asV43TBPS AzureSkuName = "Standard_E16as_v4+3TB_PS" - // AzureSkuNameStandardE16asV44TBPS ... - AzureSkuNameStandardE16asV44TBPS AzureSkuName = "Standard_E16as_v4+4TB_PS" - // AzureSkuNameStandardE16aV4 ... - AzureSkuNameStandardE16aV4 AzureSkuName = "Standard_E16a_v4" - // AzureSkuNameStandardE2aV4 ... - AzureSkuNameStandardE2aV4 AzureSkuName = "Standard_E2a_v4" - // AzureSkuNameStandardE4aV4 ... - AzureSkuNameStandardE4aV4 AzureSkuName = "Standard_E4a_v4" - // AzureSkuNameStandardE64iV3 ... - AzureSkuNameStandardE64iV3 AzureSkuName = "Standard_E64i_v3" - // AzureSkuNameStandardE80idsV4 ... - AzureSkuNameStandardE80idsV4 AzureSkuName = "Standard_E80ids_v4" - // AzureSkuNameStandardE8asV41TBPS ... - AzureSkuNameStandardE8asV41TBPS AzureSkuName = "Standard_E8as_v4+1TB_PS" - // AzureSkuNameStandardE8asV42TBPS ... - AzureSkuNameStandardE8asV42TBPS AzureSkuName = "Standard_E8as_v4+2TB_PS" - // AzureSkuNameStandardE8aV4 ... - AzureSkuNameStandardE8aV4 AzureSkuName = "Standard_E8a_v4" - // AzureSkuNameStandardL16s ... - AzureSkuNameStandardL16s AzureSkuName = "Standard_L16s" - // AzureSkuNameStandardL16sV2 ... - AzureSkuNameStandardL16sV2 AzureSkuName = "Standard_L16s_v2" - // AzureSkuNameStandardL4s ... - AzureSkuNameStandardL4s AzureSkuName = "Standard_L4s" - // AzureSkuNameStandardL8s ... - AzureSkuNameStandardL8s AzureSkuName = "Standard_L8s" - // AzureSkuNameStandardL8sV2 ... - AzureSkuNameStandardL8sV2 AzureSkuName = "Standard_L8s_v2" -) - -// PossibleAzureSkuNameValues returns an array of possible values for the AzureSkuName const type. -func PossibleAzureSkuNameValues() []AzureSkuName { - return []AzureSkuName{AzureSkuNameDevNoSLAStandardD11V2, AzureSkuNameDevNoSLAStandardE2aV4, AzureSkuNameStandardD11V2, AzureSkuNameStandardD12V2, AzureSkuNameStandardD13V2, AzureSkuNameStandardD14V2, AzureSkuNameStandardDS13V21TBPS, AzureSkuNameStandardDS13V22TBPS, AzureSkuNameStandardDS14V23TBPS, AzureSkuNameStandardDS14V24TBPS, AzureSkuNameStandardE16asV43TBPS, AzureSkuNameStandardE16asV44TBPS, AzureSkuNameStandardE16aV4, AzureSkuNameStandardE2aV4, AzureSkuNameStandardE4aV4, AzureSkuNameStandardE64iV3, AzureSkuNameStandardE80idsV4, AzureSkuNameStandardE8asV41TBPS, AzureSkuNameStandardE8asV42TBPS, AzureSkuNameStandardE8aV4, AzureSkuNameStandardL16s, AzureSkuNameStandardL16sV2, AzureSkuNameStandardL4s, AzureSkuNameStandardL8s, AzureSkuNameStandardL8sV2} -} - -// AzureSkuTier enumerates the values for azure sku tier. -type AzureSkuTier string - -const ( - // AzureSkuTierBasic ... - AzureSkuTierBasic AzureSkuTier = "Basic" - // AzureSkuTierStandard ... - AzureSkuTierStandard AzureSkuTier = "Standard" -) - -// PossibleAzureSkuTierValues returns an array of possible values for the AzureSkuTier const type. -func PossibleAzureSkuTierValues() []AzureSkuTier { - return []AzureSkuTier{AzureSkuTierBasic, AzureSkuTierStandard} -} - -// BlobStorageEventType enumerates the values for blob storage event type. -type BlobStorageEventType string - -const ( - // BlobStorageEventTypeMicrosoftStorageBlobCreated ... - BlobStorageEventTypeMicrosoftStorageBlobCreated BlobStorageEventType = "Microsoft.Storage.BlobCreated" - // BlobStorageEventTypeMicrosoftStorageBlobRenamed ... - BlobStorageEventTypeMicrosoftStorageBlobRenamed BlobStorageEventType = "Microsoft.Storage.BlobRenamed" -) - -// PossibleBlobStorageEventTypeValues returns an array of possible values for the BlobStorageEventType const type. -func PossibleBlobStorageEventTypeValues() []BlobStorageEventType { - return []BlobStorageEventType{BlobStorageEventTypeMicrosoftStorageBlobCreated, BlobStorageEventTypeMicrosoftStorageBlobRenamed} -} - -// ClusterNetworkAccessFlag enumerates the values for cluster network access flag. -type ClusterNetworkAccessFlag string - -const ( - // ClusterNetworkAccessFlagDisabled ... - ClusterNetworkAccessFlagDisabled ClusterNetworkAccessFlag = "Disabled" - // ClusterNetworkAccessFlagEnabled ... - ClusterNetworkAccessFlagEnabled ClusterNetworkAccessFlag = "Enabled" -) - -// PossibleClusterNetworkAccessFlagValues returns an array of possible values for the ClusterNetworkAccessFlag const type. -func PossibleClusterNetworkAccessFlagValues() []ClusterNetworkAccessFlag { - return []ClusterNetworkAccessFlag{ClusterNetworkAccessFlagDisabled, ClusterNetworkAccessFlagEnabled} -} - -// ClusterPrincipalRole enumerates the values for cluster principal role. -type ClusterPrincipalRole string - -const ( - // ClusterPrincipalRoleAllDatabasesAdmin ... - ClusterPrincipalRoleAllDatabasesAdmin ClusterPrincipalRole = "AllDatabasesAdmin" - // ClusterPrincipalRoleAllDatabasesViewer ... - ClusterPrincipalRoleAllDatabasesViewer ClusterPrincipalRole = "AllDatabasesViewer" -) - -// PossibleClusterPrincipalRoleValues returns an array of possible values for the ClusterPrincipalRole const type. -func PossibleClusterPrincipalRoleValues() []ClusterPrincipalRole { - return []ClusterPrincipalRole{ClusterPrincipalRoleAllDatabasesAdmin, ClusterPrincipalRoleAllDatabasesViewer} -} - -// Compression enumerates the values for compression. -type Compression string - -const ( - // CompressionGZip ... - CompressionGZip Compression = "GZip" - // CompressionNone ... - CompressionNone Compression = "None" -) - -// PossibleCompressionValues returns an array of possible values for the Compression const type. -func PossibleCompressionValues() []Compression { - return []Compression{CompressionGZip, CompressionNone} -} - -// CreatedByType enumerates the values for created by type. -type CreatedByType string - -const ( - // CreatedByTypeApplication ... - CreatedByTypeApplication CreatedByType = "Application" - // CreatedByTypeKey ... - CreatedByTypeKey CreatedByType = "Key" - // CreatedByTypeManagedIdentity ... - CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" - // CreatedByTypeUser ... - CreatedByTypeUser CreatedByType = "User" -) - -// PossibleCreatedByTypeValues returns an array of possible values for the CreatedByType const type. -func PossibleCreatedByTypeValues() []CreatedByType { - return []CreatedByType{CreatedByTypeApplication, CreatedByTypeKey, CreatedByTypeManagedIdentity, CreatedByTypeUser} -} - -// DatabasePrincipalRole enumerates the values for database principal role. -type DatabasePrincipalRole string - -const ( - // DatabasePrincipalRoleAdmin ... - DatabasePrincipalRoleAdmin DatabasePrincipalRole = "Admin" - // DatabasePrincipalRoleIngestor ... - DatabasePrincipalRoleIngestor DatabasePrincipalRole = "Ingestor" - // DatabasePrincipalRoleMonitor ... - DatabasePrincipalRoleMonitor DatabasePrincipalRole = "Monitor" - // DatabasePrincipalRoleUnrestrictedViewer ... - DatabasePrincipalRoleUnrestrictedViewer DatabasePrincipalRole = "UnrestrictedViewer" - // DatabasePrincipalRoleUser ... - DatabasePrincipalRoleUser DatabasePrincipalRole = "User" - // DatabasePrincipalRoleViewer ... - DatabasePrincipalRoleViewer DatabasePrincipalRole = "Viewer" -) - -// PossibleDatabasePrincipalRoleValues returns an array of possible values for the DatabasePrincipalRole const type. -func PossibleDatabasePrincipalRoleValues() []DatabasePrincipalRole { - return []DatabasePrincipalRole{DatabasePrincipalRoleAdmin, DatabasePrincipalRoleIngestor, DatabasePrincipalRoleMonitor, DatabasePrincipalRoleUnrestrictedViewer, DatabasePrincipalRoleUser, DatabasePrincipalRoleViewer} -} - -// DatabasePrincipalType enumerates the values for database principal type. -type DatabasePrincipalType string - -const ( - // DatabasePrincipalTypeApp ... - DatabasePrincipalTypeApp DatabasePrincipalType = "App" - // DatabasePrincipalTypeGroup ... - DatabasePrincipalTypeGroup DatabasePrincipalType = "Group" - // DatabasePrincipalTypeUser ... - DatabasePrincipalTypeUser DatabasePrincipalType = "User" -) - -// PossibleDatabasePrincipalTypeValues returns an array of possible values for the DatabasePrincipalType const type. -func PossibleDatabasePrincipalTypeValues() []DatabasePrincipalType { - return []DatabasePrincipalType{DatabasePrincipalTypeApp, DatabasePrincipalTypeGroup, DatabasePrincipalTypeUser} -} - -// DefaultPrincipalsModificationKind enumerates the values for default principals modification kind. -type DefaultPrincipalsModificationKind string - -const ( - // DefaultPrincipalsModificationKindNone ... - DefaultPrincipalsModificationKindNone DefaultPrincipalsModificationKind = "None" - // DefaultPrincipalsModificationKindReplace ... - DefaultPrincipalsModificationKindReplace DefaultPrincipalsModificationKind = "Replace" - // DefaultPrincipalsModificationKindUnion ... - DefaultPrincipalsModificationKindUnion DefaultPrincipalsModificationKind = "Union" -) - -// PossibleDefaultPrincipalsModificationKindValues returns an array of possible values for the DefaultPrincipalsModificationKind const type. -func PossibleDefaultPrincipalsModificationKindValues() []DefaultPrincipalsModificationKind { - return []DefaultPrincipalsModificationKind{DefaultPrincipalsModificationKindNone, DefaultPrincipalsModificationKindReplace, DefaultPrincipalsModificationKindUnion} -} - -// EngineType enumerates the values for engine type. -type EngineType string - -const ( - // EngineTypeV2 ... - EngineTypeV2 EngineType = "V2" - // EngineTypeV3 ... - EngineTypeV3 EngineType = "V3" -) - -// PossibleEngineTypeValues returns an array of possible values for the EngineType const type. -func PossibleEngineTypeValues() []EngineType { - return []EngineType{EngineTypeV2, EngineTypeV3} -} - -// EventGridDataFormat enumerates the values for event grid data format. -type EventGridDataFormat string - -const ( - // EventGridDataFormatAPACHEAVRO ... - EventGridDataFormatAPACHEAVRO EventGridDataFormat = "APACHEAVRO" - // EventGridDataFormatAVRO ... - EventGridDataFormatAVRO EventGridDataFormat = "AVRO" - // EventGridDataFormatCSV ... - EventGridDataFormatCSV EventGridDataFormat = "CSV" - // EventGridDataFormatJSON ... - EventGridDataFormatJSON EventGridDataFormat = "JSON" - // EventGridDataFormatMULTIJSON ... - EventGridDataFormatMULTIJSON EventGridDataFormat = "MULTIJSON" - // EventGridDataFormatORC ... - EventGridDataFormatORC EventGridDataFormat = "ORC" - // EventGridDataFormatPARQUET ... - EventGridDataFormatPARQUET EventGridDataFormat = "PARQUET" - // EventGridDataFormatPSV ... - EventGridDataFormatPSV EventGridDataFormat = "PSV" - // EventGridDataFormatRAW ... - EventGridDataFormatRAW EventGridDataFormat = "RAW" - // EventGridDataFormatSCSV ... - EventGridDataFormatSCSV EventGridDataFormat = "SCSV" - // EventGridDataFormatSINGLEJSON ... - EventGridDataFormatSINGLEJSON EventGridDataFormat = "SINGLEJSON" - // EventGridDataFormatSOHSV ... - EventGridDataFormatSOHSV EventGridDataFormat = "SOHSV" - // EventGridDataFormatTSV ... - EventGridDataFormatTSV EventGridDataFormat = "TSV" - // EventGridDataFormatTSVE ... - EventGridDataFormatTSVE EventGridDataFormat = "TSVE" - // EventGridDataFormatTXT ... - EventGridDataFormatTXT EventGridDataFormat = "TXT" - // EventGridDataFormatW3CLOGFILE ... - EventGridDataFormatW3CLOGFILE EventGridDataFormat = "W3CLOGFILE" -) - -// PossibleEventGridDataFormatValues returns an array of possible values for the EventGridDataFormat const type. -func PossibleEventGridDataFormatValues() []EventGridDataFormat { - return []EventGridDataFormat{EventGridDataFormatAPACHEAVRO, EventGridDataFormatAVRO, EventGridDataFormatCSV, EventGridDataFormatJSON, EventGridDataFormatMULTIJSON, EventGridDataFormatORC, EventGridDataFormatPARQUET, EventGridDataFormatPSV, EventGridDataFormatRAW, EventGridDataFormatSCSV, EventGridDataFormatSINGLEJSON, EventGridDataFormatSOHSV, EventGridDataFormatTSV, EventGridDataFormatTSVE, EventGridDataFormatTXT, EventGridDataFormatW3CLOGFILE} -} - -// EventHubDataFormat enumerates the values for event hub data format. -type EventHubDataFormat string - -const ( - // EventHubDataFormatAPACHEAVRO ... - EventHubDataFormatAPACHEAVRO EventHubDataFormat = "APACHEAVRO" - // EventHubDataFormatAVRO ... - EventHubDataFormatAVRO EventHubDataFormat = "AVRO" - // EventHubDataFormatCSV ... - EventHubDataFormatCSV EventHubDataFormat = "CSV" - // EventHubDataFormatJSON ... - EventHubDataFormatJSON EventHubDataFormat = "JSON" - // EventHubDataFormatMULTIJSON ... - EventHubDataFormatMULTIJSON EventHubDataFormat = "MULTIJSON" - // EventHubDataFormatORC ... - EventHubDataFormatORC EventHubDataFormat = "ORC" - // EventHubDataFormatPARQUET ... - EventHubDataFormatPARQUET EventHubDataFormat = "PARQUET" - // EventHubDataFormatPSV ... - EventHubDataFormatPSV EventHubDataFormat = "PSV" - // EventHubDataFormatRAW ... - EventHubDataFormatRAW EventHubDataFormat = "RAW" - // EventHubDataFormatSCSV ... - EventHubDataFormatSCSV EventHubDataFormat = "SCSV" - // EventHubDataFormatSINGLEJSON ... - EventHubDataFormatSINGLEJSON EventHubDataFormat = "SINGLEJSON" - // EventHubDataFormatSOHSV ... - EventHubDataFormatSOHSV EventHubDataFormat = "SOHSV" - // EventHubDataFormatTSV ... - EventHubDataFormatTSV EventHubDataFormat = "TSV" - // EventHubDataFormatTSVE ... - EventHubDataFormatTSVE EventHubDataFormat = "TSVE" - // EventHubDataFormatTXT ... - EventHubDataFormatTXT EventHubDataFormat = "TXT" - // EventHubDataFormatW3CLOGFILE ... - EventHubDataFormatW3CLOGFILE EventHubDataFormat = "W3CLOGFILE" -) - -// PossibleEventHubDataFormatValues returns an array of possible values for the EventHubDataFormat const type. -func PossibleEventHubDataFormatValues() []EventHubDataFormat { - return []EventHubDataFormat{EventHubDataFormatAPACHEAVRO, EventHubDataFormatAVRO, EventHubDataFormatCSV, EventHubDataFormatJSON, EventHubDataFormatMULTIJSON, EventHubDataFormatORC, EventHubDataFormatPARQUET, EventHubDataFormatPSV, EventHubDataFormatRAW, EventHubDataFormatSCSV, EventHubDataFormatSINGLEJSON, EventHubDataFormatSOHSV, EventHubDataFormatTSV, EventHubDataFormatTSVE, EventHubDataFormatTXT, EventHubDataFormatW3CLOGFILE} -} - -// IdentityType enumerates the values for identity type. -type IdentityType string - -const ( - // IdentityTypeNone ... - IdentityTypeNone IdentityType = "None" - // IdentityTypeSystemAssigned ... - IdentityTypeSystemAssigned IdentityType = "SystemAssigned" - // IdentityTypeSystemAssignedUserAssigned ... - IdentityTypeSystemAssignedUserAssigned IdentityType = "SystemAssigned, UserAssigned" - // IdentityTypeUserAssigned ... - IdentityTypeUserAssigned IdentityType = "UserAssigned" -) - -// PossibleIdentityTypeValues returns an array of possible values for the IdentityType const type. -func PossibleIdentityTypeValues() []IdentityType { - return []IdentityType{IdentityTypeNone, IdentityTypeSystemAssigned, IdentityTypeSystemAssignedUserAssigned, IdentityTypeUserAssigned} -} - -// IotHubDataFormat enumerates the values for iot hub data format. -type IotHubDataFormat string - -const ( - // IotHubDataFormatAPACHEAVRO ... - IotHubDataFormatAPACHEAVRO IotHubDataFormat = "APACHEAVRO" - // IotHubDataFormatAVRO ... - IotHubDataFormatAVRO IotHubDataFormat = "AVRO" - // IotHubDataFormatCSV ... - IotHubDataFormatCSV IotHubDataFormat = "CSV" - // IotHubDataFormatJSON ... - IotHubDataFormatJSON IotHubDataFormat = "JSON" - // IotHubDataFormatMULTIJSON ... - IotHubDataFormatMULTIJSON IotHubDataFormat = "MULTIJSON" - // IotHubDataFormatORC ... - IotHubDataFormatORC IotHubDataFormat = "ORC" - // IotHubDataFormatPARQUET ... - IotHubDataFormatPARQUET IotHubDataFormat = "PARQUET" - // IotHubDataFormatPSV ... - IotHubDataFormatPSV IotHubDataFormat = "PSV" - // IotHubDataFormatRAW ... - IotHubDataFormatRAW IotHubDataFormat = "RAW" - // IotHubDataFormatSCSV ... - IotHubDataFormatSCSV IotHubDataFormat = "SCSV" - // IotHubDataFormatSINGLEJSON ... - IotHubDataFormatSINGLEJSON IotHubDataFormat = "SINGLEJSON" - // IotHubDataFormatSOHSV ... - IotHubDataFormatSOHSV IotHubDataFormat = "SOHSV" - // IotHubDataFormatTSV ... - IotHubDataFormatTSV IotHubDataFormat = "TSV" - // IotHubDataFormatTSVE ... - IotHubDataFormatTSVE IotHubDataFormat = "TSVE" - // IotHubDataFormatTXT ... - IotHubDataFormatTXT IotHubDataFormat = "TXT" - // IotHubDataFormatW3CLOGFILE ... - IotHubDataFormatW3CLOGFILE IotHubDataFormat = "W3CLOGFILE" -) - -// PossibleIotHubDataFormatValues returns an array of possible values for the IotHubDataFormat const type. -func PossibleIotHubDataFormatValues() []IotHubDataFormat { - return []IotHubDataFormat{IotHubDataFormatAPACHEAVRO, IotHubDataFormatAVRO, IotHubDataFormatCSV, IotHubDataFormatJSON, IotHubDataFormatMULTIJSON, IotHubDataFormatORC, IotHubDataFormatPARQUET, IotHubDataFormatPSV, IotHubDataFormatRAW, IotHubDataFormatSCSV, IotHubDataFormatSINGLEJSON, IotHubDataFormatSOHSV, IotHubDataFormatTSV, IotHubDataFormatTSVE, IotHubDataFormatTXT, IotHubDataFormatW3CLOGFILE} -} - -// Kind enumerates the values for kind. -type Kind string - -const ( - // KindDatabase ... - KindDatabase Kind = "Database" - // KindReadOnlyFollowing ... - KindReadOnlyFollowing Kind = "ReadOnlyFollowing" - // KindReadWrite ... - KindReadWrite Kind = "ReadWrite" -) - -// PossibleKindValues returns an array of possible values for the Kind const type. -func PossibleKindValues() []Kind { - return []Kind{KindDatabase, KindReadOnlyFollowing, KindReadWrite} -} - -// KindBasicDataConnection enumerates the values for kind basic data connection. -type KindBasicDataConnection string - -const ( - // KindBasicDataConnectionKindDataConnection ... - KindBasicDataConnectionKindDataConnection KindBasicDataConnection = "DataConnection" - // KindBasicDataConnectionKindEventGrid ... - KindBasicDataConnectionKindEventGrid KindBasicDataConnection = "EventGrid" - // KindBasicDataConnectionKindEventHub ... - KindBasicDataConnectionKindEventHub KindBasicDataConnection = "EventHub" - // KindBasicDataConnectionKindIotHub ... - KindBasicDataConnectionKindIotHub KindBasicDataConnection = "IotHub" -) - -// PossibleKindBasicDataConnectionValues returns an array of possible values for the KindBasicDataConnection const type. -func PossibleKindBasicDataConnectionValues() []KindBasicDataConnection { - return []KindBasicDataConnection{KindBasicDataConnectionKindDataConnection, KindBasicDataConnectionKindEventGrid, KindBasicDataConnectionKindEventHub, KindBasicDataConnectionKindIotHub} -} - -// LanguageExtensionName enumerates the values for language extension name. -type LanguageExtensionName string - -const ( - // LanguageExtensionNamePYTHON ... - LanguageExtensionNamePYTHON LanguageExtensionName = "PYTHON" - // LanguageExtensionNameR ... - LanguageExtensionNameR LanguageExtensionName = "R" -) - -// PossibleLanguageExtensionNameValues returns an array of possible values for the LanguageExtensionName const type. -func PossibleLanguageExtensionNameValues() []LanguageExtensionName { - return []LanguageExtensionName{LanguageExtensionNamePYTHON, LanguageExtensionNameR} -} - -// PrincipalsModificationKind enumerates the values for principals modification kind. -type PrincipalsModificationKind string - -const ( - // PrincipalsModificationKindNone ... - PrincipalsModificationKindNone PrincipalsModificationKind = "None" - // PrincipalsModificationKindReplace ... - PrincipalsModificationKindReplace PrincipalsModificationKind = "Replace" - // PrincipalsModificationKindUnion ... - PrincipalsModificationKindUnion PrincipalsModificationKind = "Union" -) - -// PossiblePrincipalsModificationKindValues returns an array of possible values for the PrincipalsModificationKind const type. -func PossiblePrincipalsModificationKindValues() []PrincipalsModificationKind { - return []PrincipalsModificationKind{PrincipalsModificationKindNone, PrincipalsModificationKindReplace, PrincipalsModificationKindUnion} -} - -// PrincipalType enumerates the values for principal type. -type PrincipalType string - -const ( - // PrincipalTypeApp ... - PrincipalTypeApp PrincipalType = "App" - // PrincipalTypeGroup ... - PrincipalTypeGroup PrincipalType = "Group" - // PrincipalTypeUser ... - PrincipalTypeUser PrincipalType = "User" -) - -// PossiblePrincipalTypeValues returns an array of possible values for the PrincipalType const type. -func PossiblePrincipalTypeValues() []PrincipalType { - return []PrincipalType{PrincipalTypeApp, PrincipalTypeGroup, PrincipalTypeUser} -} - -// ProvisioningState enumerates the values for provisioning state. -type ProvisioningState string - -const ( - // ProvisioningStateCreating ... - ProvisioningStateCreating ProvisioningState = "Creating" - // ProvisioningStateDeleting ... - ProvisioningStateDeleting ProvisioningState = "Deleting" - // ProvisioningStateFailed ... - ProvisioningStateFailed ProvisioningState = "Failed" - // ProvisioningStateMoving ... - ProvisioningStateMoving ProvisioningState = "Moving" - // ProvisioningStateRunning ... - ProvisioningStateRunning ProvisioningState = "Running" - // ProvisioningStateSucceeded ... - ProvisioningStateSucceeded ProvisioningState = "Succeeded" -) - -// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. -func PossibleProvisioningStateValues() []ProvisioningState { - return []ProvisioningState{ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateMoving, ProvisioningStateRunning, ProvisioningStateSucceeded} -} - -// PublicNetworkAccess enumerates the values for public network access. -type PublicNetworkAccess string - -const ( - // PublicNetworkAccessDisabled ... - PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" - // PublicNetworkAccessEnabled ... - PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" -) - -// PossiblePublicNetworkAccessValues returns an array of possible values for the PublicNetworkAccess const type. -func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { - return []PublicNetworkAccess{PublicNetworkAccessDisabled, PublicNetworkAccessEnabled} -} - -// Reason enumerates the values for reason. -type Reason string - -const ( - // ReasonAlreadyExists ... - ReasonAlreadyExists Reason = "AlreadyExists" - // ReasonInvalid ... - ReasonInvalid Reason = "Invalid" -) - -// PossibleReasonValues returns an array of possible values for the Reason const type. -func PossibleReasonValues() []Reason { - return []Reason{ReasonAlreadyExists, ReasonInvalid} -} - -// State enumerates the values for state. -type State string - -const ( - // StateCreating ... - StateCreating State = "Creating" - // StateDeleted ... - StateDeleted State = "Deleted" - // StateDeleting ... - StateDeleting State = "Deleting" - // StateRunning ... - StateRunning State = "Running" - // StateStarting ... - StateStarting State = "Starting" - // StateStopped ... - StateStopped State = "Stopped" - // StateStopping ... - StateStopping State = "Stopping" - // StateUnavailable ... - StateUnavailable State = "Unavailable" - // StateUpdating ... - StateUpdating State = "Updating" -) - -// PossibleStateValues returns an array of possible values for the State const type. -func PossibleStateValues() []State { - return []State{StateCreating, StateDeleted, StateDeleting, StateRunning, StateStarting, StateStopped, StateStopping, StateUnavailable, StateUpdating} -} - -// Status enumerates the values for status. -type Status string - -const ( - // StatusCanceled ... - StatusCanceled Status = "Canceled" - // StatusFailed ... - StatusFailed Status = "Failed" - // StatusRunning ... - StatusRunning Status = "Running" - // StatusSucceeded ... - StatusSucceeded Status = "Succeeded" -) - -// PossibleStatusValues returns an array of possible values for the Status const type. -func PossibleStatusValues() []Status { - return []Status{StatusCanceled, StatusFailed, StatusRunning, StatusSucceeded} -} - -// Type enumerates the values for type. -type Type string - -const ( - // TypeMicrosoftKustoclustersattachedDatabaseConfigurations ... - TypeMicrosoftKustoclustersattachedDatabaseConfigurations Type = "Microsoft.Kusto/clusters/attachedDatabaseConfigurations" - // TypeMicrosoftKustoclustersdatabases ... - TypeMicrosoftKustoclustersdatabases Type = "Microsoft.Kusto/clusters/databases" -) - -// PossibleTypeValues returns an array of possible values for the Type const type. -func PossibleTypeValues() []Type { - return []Type{TypeMicrosoftKustoclustersattachedDatabaseConfigurations, TypeMicrosoftKustoclustersdatabases} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/managedprivateendpoints.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/managedprivateendpoints.go deleted file mode 100644 index 323b6a05744f..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/managedprivateendpoints.go +++ /dev/null @@ -1,534 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ManagedPrivateEndpointsClient is the the Azure Kusto management API provides a RESTful set of web services that -// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and -// delete clusters and databases. -type ManagedPrivateEndpointsClient struct { - BaseClient -} - -// NewManagedPrivateEndpointsClient creates an instance of the ManagedPrivateEndpointsClient client. -func NewManagedPrivateEndpointsClient(subscriptionID string) ManagedPrivateEndpointsClient { - return NewManagedPrivateEndpointsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewManagedPrivateEndpointsClientWithBaseURI creates an instance of the ManagedPrivateEndpointsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewManagedPrivateEndpointsClientWithBaseURI(baseURI string, subscriptionID string) ManagedPrivateEndpointsClient { - return ManagedPrivateEndpointsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckNameAvailability checks that the managed private endpoints resource name is valid and is not already in use. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// resourceName - the name of the resource. -func (client ManagedPrivateEndpointsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, resourceName ManagedPrivateEndpointsCheckNameRequest) (result CheckNameResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceName, - Constraints: []validation.Constraint{{Target: "resourceName.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "resourceName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("kusto.ManagedPrivateEndpointsClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, resourceName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client ManagedPrivateEndpointsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, resourceName ManagedPrivateEndpointsCheckNameRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/managedPrivateEndpointsCheckNameAvailability", pathParameters), - autorest.WithJSON(resourceName), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client ManagedPrivateEndpointsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client ManagedPrivateEndpointsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates a managed private endpoint. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// managedPrivateEndpointName - the name of the managed private endpoint. -// parameters - the managed private endpoint parameters. -func (client ManagedPrivateEndpointsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string, parameters ManagedPrivateEndpoint) (result ManagedPrivateEndpointsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ManagedPrivateEndpointProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ManagedPrivateEndpointProperties.PrivateLinkResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ManagedPrivateEndpointProperties.GroupID", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("kusto.ManagedPrivateEndpointsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, managedPrivateEndpointName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ManagedPrivateEndpointsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string, parameters ManagedPrivateEndpoint) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "managedPrivateEndpointName": autorest.Encode("path", managedPrivateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/managedPrivateEndpoints/{managedPrivateEndpointName}", 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 ManagedPrivateEndpointsClient) CreateOrUpdateSender(req *http.Request) (future ManagedPrivateEndpointsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ManagedPrivateEndpointsClient) CreateOrUpdateResponder(resp *http.Response) (result ManagedPrivateEndpoint, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a managed private endpoint. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// managedPrivateEndpointName - the name of the managed private endpoint. -func (client ManagedPrivateEndpointsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string) (result ManagedPrivateEndpointsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, managedPrivateEndpointName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ManagedPrivateEndpointsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "managedPrivateEndpointName": autorest.Encode("path", managedPrivateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/managedPrivateEndpoints/{managedPrivateEndpointName}", 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 ManagedPrivateEndpointsClient) DeleteSender(req *http.Request) (future ManagedPrivateEndpointsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ManagedPrivateEndpointsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a managed private endpoint. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// managedPrivateEndpointName - the name of the managed private endpoint. -func (client ManagedPrivateEndpointsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string) (result ManagedPrivateEndpoint, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, managedPrivateEndpointName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ManagedPrivateEndpointsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "managedPrivateEndpointName": autorest.Encode("path", managedPrivateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/managedPrivateEndpoints/{managedPrivateEndpointName}", 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 ManagedPrivateEndpointsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ManagedPrivateEndpointsClient) GetResponder(resp *http.Response) (result ManagedPrivateEndpoint, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List returns the list of managed private endpoints. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client ManagedPrivateEndpointsClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result ManagedPrivateEndpointListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ManagedPrivateEndpointsClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/managedPrivateEndpoints", 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 ManagedPrivateEndpointsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ManagedPrivateEndpointsClient) ListResponder(resp *http.Response) (result ManagedPrivateEndpointListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Update updates a managed private endpoint. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// managedPrivateEndpointName - the name of the managed private endpoint. -// parameters - the managed private endpoint parameters. -func (client ManagedPrivateEndpointsClient) Update(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string, parameters ManagedPrivateEndpoint) (result ManagedPrivateEndpointsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagedPrivateEndpointsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, managedPrivateEndpointName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ManagedPrivateEndpointsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, managedPrivateEndpointName string, parameters ManagedPrivateEndpoint) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "managedPrivateEndpointName": autorest.Encode("path", managedPrivateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/managedPrivateEndpoints/{managedPrivateEndpointName}", 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 ManagedPrivateEndpointsClient) UpdateSender(req *http.Request) (future ManagedPrivateEndpointsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ManagedPrivateEndpointsClient) UpdateResponder(resp *http.Response) (result ManagedPrivateEndpoint, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/kusto/mgmt/2021-08-27/kusto/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/models.go deleted file mode 100644 index f6f5a0285777..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/models.go +++ /dev/null @@ -1,4761 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto" - -// AcceptedAudiences represents an accepted audience trusted by the cluster. -type AcceptedAudiences struct { - // Value - GUID or valid URL representing an accepted audience. - Value *string `json:"value,omitempty"` -} - -// AttachedDatabaseConfiguration class representing an attached database configuration. -type AttachedDatabaseConfiguration struct { - autorest.Response `json:"-"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // AttachedDatabaseConfigurationProperties - The properties of the attached database configuration. - *AttachedDatabaseConfigurationProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for AttachedDatabaseConfiguration. -func (adc AttachedDatabaseConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if adc.Location != nil { - objectMap["location"] = adc.Location - } - if adc.AttachedDatabaseConfigurationProperties != nil { - objectMap["properties"] = adc.AttachedDatabaseConfigurationProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AttachedDatabaseConfiguration struct. -func (adc *AttachedDatabaseConfiguration) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - adc.Location = &location - } - case "properties": - if v != nil { - var attachedDatabaseConfigurationProperties AttachedDatabaseConfigurationProperties - err = json.Unmarshal(*v, &attachedDatabaseConfigurationProperties) - if err != nil { - return err - } - adc.AttachedDatabaseConfigurationProperties = &attachedDatabaseConfigurationProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - adc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - adc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - adc.Type = &typeVar - } - } - } - - return nil -} - -// AttachedDatabaseConfigurationListResult the list attached database configurations operation response. -type AttachedDatabaseConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - The list of attached database configurations. - Value *[]AttachedDatabaseConfiguration `json:"value,omitempty"` -} - -// AttachedDatabaseConfigurationProperties class representing the an attached database configuration -// properties of kind specific. -type AttachedDatabaseConfigurationProperties struct { - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // DatabaseName - The name of the database which you would like to attach, use * if you want to follow all current and future databases. - DatabaseName *string `json:"databaseName,omitempty"` - // ClusterResourceID - The resource id of the cluster where the databases you would like to attach reside. - ClusterResourceID *string `json:"clusterResourceId,omitempty"` - // AttachedDatabaseNames - READ-ONLY; The list of databases from the clusterResourceId which are currently attached to the cluster. - AttachedDatabaseNames *[]string `json:"attachedDatabaseNames,omitempty"` - // DefaultPrincipalsModificationKind - The default principals modification kind. Possible values include: 'DefaultPrincipalsModificationKindUnion', 'DefaultPrincipalsModificationKindReplace', 'DefaultPrincipalsModificationKindNone' - DefaultPrincipalsModificationKind DefaultPrincipalsModificationKind `json:"defaultPrincipalsModificationKind,omitempty"` - // TableLevelSharingProperties - Table level sharing specifications - TableLevelSharingProperties *TableLevelSharingProperties `json:"tableLevelSharingProperties,omitempty"` -} - -// MarshalJSON is the custom marshaler for AttachedDatabaseConfigurationProperties. -func (adcp AttachedDatabaseConfigurationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if adcp.DatabaseName != nil { - objectMap["databaseName"] = adcp.DatabaseName - } - if adcp.ClusterResourceID != nil { - objectMap["clusterResourceId"] = adcp.ClusterResourceID - } - if adcp.DefaultPrincipalsModificationKind != "" { - objectMap["defaultPrincipalsModificationKind"] = adcp.DefaultPrincipalsModificationKind - } - if adcp.TableLevelSharingProperties != nil { - objectMap["tableLevelSharingProperties"] = adcp.TableLevelSharingProperties - } - return json.Marshal(objectMap) -} - -// AttachedDatabaseConfigurationsCheckNameRequest the result returned from a AttachedDatabaseConfigurations -// check name availability request. -type AttachedDatabaseConfigurationsCheckNameRequest struct { - // Name - Attached database resource name. - Name *string `json:"name,omitempty"` - // Type - The type of resource, for instance Microsoft.Kusto/clusters/attachedDatabaseConfigurations. - Type *string `json:"type,omitempty"` -} - -// AttachedDatabaseConfigurationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type AttachedDatabaseConfigurationsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AttachedDatabaseConfigurationsClient) (AttachedDatabaseConfiguration, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AttachedDatabaseConfigurationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AttachedDatabaseConfigurationsCreateOrUpdateFuture.Result. -func (future *AttachedDatabaseConfigurationsCreateOrUpdateFuture) result(client AttachedDatabaseConfigurationsClient) (adc AttachedDatabaseConfiguration, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - adc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.AttachedDatabaseConfigurationsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if adc.Response.Response, err = future.GetResult(sender); err == nil && adc.Response.Response.StatusCode != http.StatusNoContent { - adc, err = client.CreateOrUpdateResponder(adc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsCreateOrUpdateFuture", "Result", adc.Response.Response, "Failure responding to request") - } - } - return -} - -// AttachedDatabaseConfigurationsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type AttachedDatabaseConfigurationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AttachedDatabaseConfigurationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AttachedDatabaseConfigurationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AttachedDatabaseConfigurationsDeleteFuture.Result. -func (future *AttachedDatabaseConfigurationsDeleteFuture) result(client AttachedDatabaseConfigurationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.AttachedDatabaseConfigurationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.AttachedDatabaseConfigurationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// AzureCapacity azure capacity definition. -type AzureCapacity struct { - // ScaleType - Scale type. Possible values include: 'AzureScaleTypeAutomatic', 'AzureScaleTypeManual', 'AzureScaleTypeNone' - ScaleType AzureScaleType `json:"scaleType,omitempty"` - // Minimum - Minimum allowed capacity. - Minimum *int32 `json:"minimum,omitempty"` - // Maximum - Maximum allowed capacity. - Maximum *int32 `json:"maximum,omitempty"` - // Default - The default capacity that would be used. - Default *int32 `json:"default,omitempty"` -} - -// AzureEntityResource the resource model definition for an Azure Resource Manager resource with an etag. -type AzureEntityResource struct { - // Etag - READ-ONLY; Resource Etag. - Etag *string `json:"etag,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureEntityResource. -func (aer AzureEntityResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// AzureResourceSku azure resource SKU definition. -type AzureResourceSku struct { - // ResourceType - Resource Namespace and Type. - ResourceType *string `json:"resourceType,omitempty"` - // Sku - The SKU details. - Sku *AzureSku `json:"sku,omitempty"` - // Capacity - The number of instances of the cluster. - Capacity *AzureCapacity `json:"capacity,omitempty"` -} - -// AzureSku azure SKU definition. -type AzureSku struct { - // Name - SKU name. Possible values include: 'AzureSkuNameStandardDS13V21TBPS', 'AzureSkuNameStandardDS13V22TBPS', 'AzureSkuNameStandardDS14V23TBPS', 'AzureSkuNameStandardDS14V24TBPS', 'AzureSkuNameStandardD13V2', 'AzureSkuNameStandardD14V2', 'AzureSkuNameStandardL8s', 'AzureSkuNameStandardL16s', 'AzureSkuNameStandardL8sV2', 'AzureSkuNameStandardL16sV2', 'AzureSkuNameStandardD11V2', 'AzureSkuNameStandardD12V2', 'AzureSkuNameStandardL4s', 'AzureSkuNameDevNoSLAStandardD11V2', 'AzureSkuNameStandardE64iV3', 'AzureSkuNameStandardE80idsV4', 'AzureSkuNameStandardE2aV4', 'AzureSkuNameStandardE4aV4', 'AzureSkuNameStandardE8aV4', 'AzureSkuNameStandardE16aV4', 'AzureSkuNameStandardE8asV41TBPS', 'AzureSkuNameStandardE8asV42TBPS', 'AzureSkuNameStandardE16asV43TBPS', 'AzureSkuNameStandardE16asV44TBPS', 'AzureSkuNameDevNoSLAStandardE2aV4' - Name AzureSkuName `json:"name,omitempty"` - // Capacity - The number of instances of the cluster. - Capacity *int32 `json:"capacity,omitempty"` - // Tier - SKU tier. Possible values include: 'AzureSkuTierBasic', 'AzureSkuTierStandard' - Tier AzureSkuTier `json:"tier,omitempty"` -} - -// CheckNameRequest the result returned from a database check name availability request. -type CheckNameRequest struct { - // Name - Resource name. - Name *string `json:"name,omitempty"` - // Type - The type of resource, for instance Microsoft.Kusto/clusters/databases. Possible values include: 'TypeMicrosoftKustoclustersdatabases', 'TypeMicrosoftKustoclustersattachedDatabaseConfigurations' - Type Type `json:"type,omitempty"` -} - -// CheckNameResult the result returned from a check name availability request. -type CheckNameResult struct { - autorest.Response `json:"-"` - // NameAvailable - Specifies a Boolean value that indicates if the name is available. - NameAvailable *bool `json:"nameAvailable,omitempty"` - // Name - The name that was checked. - Name *string `json:"name,omitempty"` - // Message - Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. - Message *string `json:"message,omitempty"` - // Reason - Message providing the reason why the given name is invalid. Possible values include: 'ReasonInvalid', 'ReasonAlreadyExists' - Reason Reason `json:"reason,omitempty"` -} - -// CloudError an error response from Kusto. -type CloudError struct { - // Error - An error response from Kusto. - Error *CloudErrorBody `json:"error,omitempty"` -} - -// CloudErrorBody an error response from Kusto. -type CloudErrorBody struct { - // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. - Code *string `json:"code,omitempty"` - // Message - A message describing the error, intended to be suitable for displaying in a user interface. - Message *string `json:"message,omitempty"` - // Target - The target of the particular error. For example, the name of the property in error. - Target *string `json:"target,omitempty"` - // Details - A list of additional details about the error. - Details *[]CloudErrorBody `json:"details,omitempty"` -} - -// Cluster class representing a Kusto cluster. -type Cluster struct { - autorest.Response `json:"-"` - // Sku - The SKU of the cluster. - Sku *AzureSku `json:"sku,omitempty"` - // SystemData - READ-ONLY - SystemData *SystemData `json:"systemData,omitempty"` - // Zones - The availability zones of the cluster. - Zones *[]string `json:"zones,omitempty"` - // Identity - The identity of the cluster, if configured. - Identity *Identity `json:"identity,omitempty"` - // ClusterProperties - The cluster properties. - *ClusterProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` - // Location - The geo-location where the resource lives - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Cluster. -func (c Cluster) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if c.Sku != nil { - objectMap["sku"] = c.Sku - } - if c.Zones != nil { - objectMap["zones"] = c.Zones - } - if c.Identity != nil { - objectMap["identity"] = c.Identity - } - if c.ClusterProperties != nil { - objectMap["properties"] = c.ClusterProperties - } - if c.Tags != nil { - objectMap["tags"] = c.Tags - } - if c.Location != nil { - objectMap["location"] = c.Location - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Cluster struct. -func (c *Cluster) 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 AzureSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - c.Sku = &sku - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - c.SystemData = &systemData - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - c.Zones = &zones - } - case "identity": - if v != nil { - var identity Identity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - c.Identity = &identity - } - case "properties": - if v != nil { - var clusterProperties ClusterProperties - err = json.Unmarshal(*v, &clusterProperties) - if err != nil { - return err - } - c.ClusterProperties = &clusterProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - c.Etag = &etag - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - c.Tags = tags - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - c.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - c.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - c.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - c.Type = &typeVar - } - } - } - - return nil -} - -// ClusterCheckNameRequest the result returned from a cluster check name availability request. -type ClusterCheckNameRequest struct { - // Name - Cluster name. - Name *string `json:"name,omitempty"` - // Type - The type of resource, Microsoft.Kusto/clusters. - Type *string `json:"type,omitempty"` -} - -// ClusterListResult the list Kusto clusters operation response. -type ClusterListResult struct { - autorest.Response `json:"-"` - // Value - The list of Kusto clusters. - Value *[]Cluster `json:"value,omitempty"` -} - -// ClusterPrincipalAssignment class representing a cluster principal assignment. -type ClusterPrincipalAssignment struct { - autorest.Response `json:"-"` - // ClusterPrincipalProperties - The cluster principal. - *ClusterPrincipalProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ClusterPrincipalAssignment. -func (cpa ClusterPrincipalAssignment) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cpa.ClusterPrincipalProperties != nil { - objectMap["properties"] = cpa.ClusterPrincipalProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ClusterPrincipalAssignment struct. -func (cpa *ClusterPrincipalAssignment) 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 clusterPrincipalProperties ClusterPrincipalProperties - err = json.Unmarshal(*v, &clusterPrincipalProperties) - if err != nil { - return err - } - cpa.ClusterPrincipalProperties = &clusterPrincipalProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cpa.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cpa.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cpa.Type = &typeVar - } - } - } - - return nil -} - -// ClusterPrincipalAssignmentCheckNameRequest a principal assignment check name availability request. -type ClusterPrincipalAssignmentCheckNameRequest struct { - // Name - Principal Assignment resource name. - Name *string `json:"name,omitempty"` - // Type - The type of resource, Microsoft.Kusto/clusters/principalAssignments. - Type *string `json:"type,omitempty"` -} - -// ClusterPrincipalAssignmentListResult the list Kusto cluster principal assignments operation response. -type ClusterPrincipalAssignmentListResult struct { - autorest.Response `json:"-"` - // Value - The list of Kusto cluster principal assignments. - Value *[]ClusterPrincipalAssignment `json:"value,omitempty"` -} - -// ClusterPrincipalAssignmentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ClusterPrincipalAssignmentsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClusterPrincipalAssignmentsClient) (ClusterPrincipalAssignment, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClusterPrincipalAssignmentsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClusterPrincipalAssignmentsCreateOrUpdateFuture.Result. -func (future *ClusterPrincipalAssignmentsCreateOrUpdateFuture) result(client ClusterPrincipalAssignmentsClient) (cpa ClusterPrincipalAssignment, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cpa.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClusterPrincipalAssignmentsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cpa.Response.Response, err = future.GetResult(sender); err == nil && cpa.Response.Response.StatusCode != http.StatusNoContent { - cpa, err = client.CreateOrUpdateResponder(cpa.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsCreateOrUpdateFuture", "Result", cpa.Response.Response, "Failure responding to request") - } - } - return -} - -// ClusterPrincipalAssignmentsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ClusterPrincipalAssignmentsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClusterPrincipalAssignmentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClusterPrincipalAssignmentsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClusterPrincipalAssignmentsDeleteFuture.Result. -func (future *ClusterPrincipalAssignmentsDeleteFuture) result(client ClusterPrincipalAssignmentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClusterPrincipalAssignmentsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClusterPrincipalAssignmentsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ClusterPrincipalProperties a class representing cluster principal property. -type ClusterPrincipalProperties struct { - // PrincipalID - The principal ID assigned to the cluster principal. It can be a user email, application ID, or security group name. - PrincipalID *string `json:"principalId,omitempty"` - // Role - Cluster principal role. Possible values include: 'ClusterPrincipalRoleAllDatabasesAdmin', 'ClusterPrincipalRoleAllDatabasesViewer' - Role ClusterPrincipalRole `json:"role,omitempty"` - // TenantID - The tenant id of the principal - TenantID *string `json:"tenantId,omitempty"` - // PrincipalType - Principal type. Possible values include: 'PrincipalTypeApp', 'PrincipalTypeGroup', 'PrincipalTypeUser' - PrincipalType PrincipalType `json:"principalType,omitempty"` - // TenantName - READ-ONLY; The tenant name of the principal - TenantName *string `json:"tenantName,omitempty"` - // PrincipalName - READ-ONLY; The principal name - PrincipalName *string `json:"principalName,omitempty"` - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ClusterPrincipalProperties. -func (cpp ClusterPrincipalProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cpp.PrincipalID != nil { - objectMap["principalId"] = cpp.PrincipalID - } - if cpp.Role != "" { - objectMap["role"] = cpp.Role - } - if cpp.TenantID != nil { - objectMap["tenantId"] = cpp.TenantID - } - if cpp.PrincipalType != "" { - objectMap["principalType"] = cpp.PrincipalType - } - return json.Marshal(objectMap) -} - -// ClusterProperties class representing the Kusto cluster properties. -type ClusterProperties struct { - // State - READ-ONLY; The state of the resource. Possible values include: 'StateCreating', 'StateUnavailable', 'StateRunning', 'StateDeleting', 'StateDeleted', 'StateStopping', 'StateStopped', 'StateStarting', 'StateUpdating' - State State `json:"state,omitempty"` - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // URI - READ-ONLY; The cluster URI. - URI *string `json:"uri,omitempty"` - // DataIngestionURI - READ-ONLY; The cluster data ingestion URI. - DataIngestionURI *string `json:"dataIngestionUri,omitempty"` - // StateReason - READ-ONLY; The reason for the cluster's current state. - StateReason *string `json:"stateReason,omitempty"` - // TrustedExternalTenants - The cluster's external tenants. - TrustedExternalTenants *[]TrustedExternalTenant `json:"trustedExternalTenants,omitempty"` - // OptimizedAutoscale - Optimized auto scale definition. - OptimizedAutoscale *OptimizedAutoscale `json:"optimizedAutoscale,omitempty"` - // EnableDiskEncryption - A boolean value that indicates if the cluster's disks are encrypted. - EnableDiskEncryption *bool `json:"enableDiskEncryption,omitempty"` - // EnableStreamingIngest - A boolean value that indicates if the streaming ingest is enabled. - EnableStreamingIngest *bool `json:"enableStreamingIngest,omitempty"` - // VirtualNetworkConfiguration - Virtual network definition. - VirtualNetworkConfiguration *VirtualNetworkConfiguration `json:"virtualNetworkConfiguration,omitempty"` - // KeyVaultProperties - KeyVault properties for the cluster encryption. - KeyVaultProperties *KeyVaultProperties `json:"keyVaultProperties,omitempty"` - // EnablePurge - A boolean value that indicates if the purge operations are enabled. - EnablePurge *bool `json:"enablePurge,omitempty"` - // LanguageExtensions - READ-ONLY; List of the cluster's language extensions. - LanguageExtensions *LanguageExtensionsList `json:"languageExtensions,omitempty"` - // EnableDoubleEncryption - A boolean value that indicates if double encryption is enabled. - EnableDoubleEncryption *bool `json:"enableDoubleEncryption,omitempty"` - // PublicNetworkAccess - Public network access to the cluster is enabled by default. When disabled, only private endpoint connection to the cluster is allowed. Possible values include: 'PublicNetworkAccessEnabled', 'PublicNetworkAccessDisabled' - PublicNetworkAccess PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` - // AllowedIPRangeList - The list of ips in the format of CIDR allowed to connect to the cluster. - AllowedIPRangeList *[]string `json:"allowedIpRangeList,omitempty"` - // EngineType - The engine type. Possible values include: 'EngineTypeV2', 'EngineTypeV3' - EngineType EngineType `json:"engineType,omitempty"` - // AcceptedAudiences - The cluster's accepted audiences. - AcceptedAudiences *[]AcceptedAudiences `json:"acceptedAudiences,omitempty"` - // EnableAutoStop - A boolean value that indicates if the cluster could be automatically stopped (due to lack of data or no activity for many days). - EnableAutoStop *bool `json:"enableAutoStop,omitempty"` - // RestrictOutboundNetworkAccess - Whether or not to restrict outbound network access. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: 'ClusterNetworkAccessFlagEnabled', 'ClusterNetworkAccessFlagDisabled' - RestrictOutboundNetworkAccess ClusterNetworkAccessFlag `json:"restrictOutboundNetworkAccess,omitempty"` - // AllowedFqdnList - List of allowed FQDNs(Fully Qualified Domain Name) for egress from Cluster. - AllowedFqdnList *[]string `json:"allowedFqdnList,omitempty"` -} - -// MarshalJSON is the custom marshaler for ClusterProperties. -func (cp ClusterProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cp.TrustedExternalTenants != nil { - objectMap["trustedExternalTenants"] = cp.TrustedExternalTenants - } - if cp.OptimizedAutoscale != nil { - objectMap["optimizedAutoscale"] = cp.OptimizedAutoscale - } - if cp.EnableDiskEncryption != nil { - objectMap["enableDiskEncryption"] = cp.EnableDiskEncryption - } - if cp.EnableStreamingIngest != nil { - objectMap["enableStreamingIngest"] = cp.EnableStreamingIngest - } - if cp.VirtualNetworkConfiguration != nil { - objectMap["virtualNetworkConfiguration"] = cp.VirtualNetworkConfiguration - } - if cp.KeyVaultProperties != nil { - objectMap["keyVaultProperties"] = cp.KeyVaultProperties - } - if cp.EnablePurge != nil { - objectMap["enablePurge"] = cp.EnablePurge - } - if cp.EnableDoubleEncryption != nil { - objectMap["enableDoubleEncryption"] = cp.EnableDoubleEncryption - } - if cp.PublicNetworkAccess != "" { - objectMap["publicNetworkAccess"] = cp.PublicNetworkAccess - } - if cp.AllowedIPRangeList != nil { - objectMap["allowedIpRangeList"] = cp.AllowedIPRangeList - } - if cp.EngineType != "" { - objectMap["engineType"] = cp.EngineType - } - if cp.AcceptedAudiences != nil { - objectMap["acceptedAudiences"] = cp.AcceptedAudiences - } - if cp.EnableAutoStop != nil { - objectMap["enableAutoStop"] = cp.EnableAutoStop - } - if cp.RestrictOutboundNetworkAccess != "" { - objectMap["restrictOutboundNetworkAccess"] = cp.RestrictOutboundNetworkAccess - } - if cp.AllowedFqdnList != nil { - objectMap["allowedFqdnList"] = cp.AllowedFqdnList - } - return json.Marshal(objectMap) -} - -// ClustersAddLanguageExtensionsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ClustersAddLanguageExtensionsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClustersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClustersAddLanguageExtensionsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClustersAddLanguageExtensionsFuture.Result. -func (future *ClustersAddLanguageExtensionsFuture) result(client ClustersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersAddLanguageExtensionsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClustersAddLanguageExtensionsFuture") - return - } - ar.Response = future.Response() - return -} - -// ClustersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ClustersCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClustersClient) (Cluster, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClustersCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClustersCreateOrUpdateFuture.Result. -func (future *ClustersCreateOrUpdateFuture) result(client ClustersClient) (c Cluster, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - c.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClustersCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if c.Response.Response, err = future.GetResult(sender); err == nil && c.Response.Response.StatusCode != http.StatusNoContent { - c, err = client.CreateOrUpdateResponder(c.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersCreateOrUpdateFuture", "Result", c.Response.Response, "Failure responding to request") - } - } - return -} - -// ClustersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ClustersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClustersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClustersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClustersDeleteFuture.Result. -func (future *ClustersDeleteFuture) result(client ClustersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClustersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ClustersDetachFollowerDatabasesFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ClustersDetachFollowerDatabasesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClustersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClustersDetachFollowerDatabasesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClustersDetachFollowerDatabasesFuture.Result. -func (future *ClustersDetachFollowerDatabasesFuture) result(client ClustersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersDetachFollowerDatabasesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClustersDetachFollowerDatabasesFuture") - return - } - ar.Response = future.Response() - return -} - -// ClustersDiagnoseVirtualNetworkFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ClustersDiagnoseVirtualNetworkFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClustersClient) (DiagnoseVirtualNetworkResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClustersDiagnoseVirtualNetworkFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClustersDiagnoseVirtualNetworkFuture.Result. -func (future *ClustersDiagnoseVirtualNetworkFuture) result(client ClustersClient) (dvnr DiagnoseVirtualNetworkResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersDiagnoseVirtualNetworkFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dvnr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClustersDiagnoseVirtualNetworkFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dvnr.Response.Response, err = future.GetResult(sender); err == nil && dvnr.Response.Response.StatusCode != http.StatusNoContent { - dvnr, err = client.DiagnoseVirtualNetworkResponder(dvnr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersDiagnoseVirtualNetworkFuture", "Result", dvnr.Response.Response, "Failure responding to request") - } - } - return -} - -// ClustersRemoveLanguageExtensionsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ClustersRemoveLanguageExtensionsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClustersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClustersRemoveLanguageExtensionsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClustersRemoveLanguageExtensionsFuture.Result. -func (future *ClustersRemoveLanguageExtensionsFuture) result(client ClustersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersRemoveLanguageExtensionsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClustersRemoveLanguageExtensionsFuture") - return - } - ar.Response = future.Response() - return -} - -// ClustersStartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ClustersStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClustersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClustersStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClustersStartFuture.Result. -func (future *ClustersStartFuture) result(client ClustersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClustersStartFuture") - return - } - ar.Response = future.Response() - return -} - -// ClustersStopFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type ClustersStopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClustersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClustersStopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClustersStopFuture.Result. -func (future *ClustersStopFuture) result(client ClustersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersStopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClustersStopFuture") - return - } - ar.Response = future.Response() - return -} - -// ClustersUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ClustersUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ClustersClient) (Cluster, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ClustersUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ClustersUpdateFuture.Result. -func (future *ClustersUpdateFuture) result(client ClustersClient) (c Cluster, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - c.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ClustersUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if c.Response.Response, err = future.GetResult(sender); err == nil && c.Response.Response.StatusCode != http.StatusNoContent { - c, err = client.UpdateResponder(c.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ClustersUpdateFuture", "Result", c.Response.Response, "Failure responding to request") - } - } - return -} - -// ClusterUpdate class representing an update to a Kusto cluster. -type ClusterUpdate struct { - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Sku - The SKU of the cluster. - Sku *AzureSku `json:"sku,omitempty"` - // Identity - The identity of the cluster, if configured. - Identity *Identity `json:"identity,omitempty"` - // ClusterProperties - The cluster properties. - *ClusterProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ClusterUpdate. -func (cu ClusterUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cu.Tags != nil { - objectMap["tags"] = cu.Tags - } - if cu.Location != nil { - objectMap["location"] = cu.Location - } - if cu.Sku != nil { - objectMap["sku"] = cu.Sku - } - if cu.Identity != nil { - objectMap["identity"] = cu.Identity - } - if cu.ClusterProperties != nil { - objectMap["properties"] = cu.ClusterProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ClusterUpdate struct. -func (cu *ClusterUpdate) 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 "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cu.Tags = tags - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cu.Location = &location - } - case "sku": - if v != nil { - var sku AzureSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - cu.Sku = &sku - } - case "identity": - if v != nil { - var identity Identity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - cu.Identity = &identity - } - case "properties": - if v != nil { - var clusterProperties ClusterProperties - err = json.Unmarshal(*v, &clusterProperties) - if err != nil { - return err - } - cu.ClusterProperties = &clusterProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cu.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cu.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cu.Type = &typeVar - } - } - } - - return nil -} - -// BasicDatabase class representing a Kusto database. -type BasicDatabase interface { - AsReadWriteDatabase() (*ReadWriteDatabase, bool) - AsReadOnlyFollowingDatabase() (*ReadOnlyFollowingDatabase, bool) - AsDatabase() (*Database, bool) -} - -// Database class representing a Kusto database. -type Database struct { - autorest.Response `json:"-"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Kind - Possible values include: 'KindDatabase', 'KindReadWrite', 'KindReadOnlyFollowing' - Kind Kind `json:"kind,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -func unmarshalBasicDatabase(body []byte) (BasicDatabase, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["kind"] { - case string(KindReadWrite): - var rwd ReadWriteDatabase - err := json.Unmarshal(body, &rwd) - return rwd, err - case string(KindReadOnlyFollowing): - var rofd ReadOnlyFollowingDatabase - err := json.Unmarshal(body, &rofd) - return rofd, err - default: - var d Database - err := json.Unmarshal(body, &d) - return d, err - } -} -func unmarshalBasicDatabaseArray(body []byte) ([]BasicDatabase, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - dArray := make([]BasicDatabase, len(rawMessages)) - - for index, rawMessage := range rawMessages { - d, err := unmarshalBasicDatabase(*rawMessage) - if err != nil { - return nil, err - } - dArray[index] = d - } - return dArray, nil -} - -// MarshalJSON is the custom marshaler for Database. -func (d Database) MarshalJSON() ([]byte, error) { - d.Kind = KindDatabase - objectMap := make(map[string]interface{}) - if d.Location != nil { - objectMap["location"] = d.Location - } - if d.Kind != "" { - objectMap["kind"] = d.Kind - } - return json.Marshal(objectMap) -} - -// AsReadWriteDatabase is the BasicDatabase implementation for Database. -func (d Database) AsReadWriteDatabase() (*ReadWriteDatabase, bool) { - return nil, false -} - -// AsReadOnlyFollowingDatabase is the BasicDatabase implementation for Database. -func (d Database) AsReadOnlyFollowingDatabase() (*ReadOnlyFollowingDatabase, bool) { - return nil, false -} - -// AsDatabase is the BasicDatabase implementation for Database. -func (d Database) AsDatabase() (*Database, bool) { - return &d, true -} - -// AsBasicDatabase is the BasicDatabase implementation for Database. -func (d Database) AsBasicDatabase() (BasicDatabase, bool) { - return &d, true -} - -// DatabaseListResult the list Kusto databases operation response. -type DatabaseListResult struct { - autorest.Response `json:"-"` - // Value - The list of Kusto databases. - Value *[]BasicDatabase `json:"value,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for DatabaseListResult struct. -func (dlr *DatabaseListResult) 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 "value": - if v != nil { - value, err := unmarshalBasicDatabaseArray(*v) - if err != nil { - return err - } - dlr.Value = &value - } - } - } - - return nil -} - -// DatabaseModel ... -type DatabaseModel struct { - autorest.Response `json:"-"` - Value BasicDatabase `json:"value,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for DatabaseModel struct. -func (dm *DatabaseModel) UnmarshalJSON(body []byte) error { - d, err := unmarshalBasicDatabase(body) - if err != nil { - return err - } - dm.Value = d - - return nil -} - -// DatabasePrincipal a class representing database principal entity. -type DatabasePrincipal struct { - // Role - Database principal role. Possible values include: 'DatabasePrincipalRoleAdmin', 'DatabasePrincipalRoleIngestor', 'DatabasePrincipalRoleMonitor', 'DatabasePrincipalRoleUser', 'DatabasePrincipalRoleUnrestrictedViewer', 'DatabasePrincipalRoleViewer' - Role DatabasePrincipalRole `json:"role,omitempty"` - // Name - Database principal name. - Name *string `json:"name,omitempty"` - // Type - Database principal type. Possible values include: 'DatabasePrincipalTypeApp', 'DatabasePrincipalTypeGroup', 'DatabasePrincipalTypeUser' - Type DatabasePrincipalType `json:"type,omitempty"` - // Fqn - Database principal fully qualified name. - Fqn *string `json:"fqn,omitempty"` - // Email - Database principal email if exists. - Email *string `json:"email,omitempty"` - // AppID - Application id - relevant only for application principal type. - AppID *string `json:"appId,omitempty"` - // TenantName - READ-ONLY; The tenant name of the principal - TenantName *string `json:"tenantName,omitempty"` -} - -// MarshalJSON is the custom marshaler for DatabasePrincipal. -func (dp DatabasePrincipal) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dp.Role != "" { - objectMap["role"] = dp.Role - } - if dp.Name != nil { - objectMap["name"] = dp.Name - } - if dp.Type != "" { - objectMap["type"] = dp.Type - } - if dp.Fqn != nil { - objectMap["fqn"] = dp.Fqn - } - if dp.Email != nil { - objectMap["email"] = dp.Email - } - if dp.AppID != nil { - objectMap["appId"] = dp.AppID - } - return json.Marshal(objectMap) -} - -// DatabasePrincipalAssignment class representing a database principal assignment. -type DatabasePrincipalAssignment struct { - autorest.Response `json:"-"` - // DatabasePrincipalProperties - The database principal. - *DatabasePrincipalProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for DatabasePrincipalAssignment. -func (dpa DatabasePrincipalAssignment) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dpa.DatabasePrincipalProperties != nil { - objectMap["properties"] = dpa.DatabasePrincipalProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for DatabasePrincipalAssignment struct. -func (dpa *DatabasePrincipalAssignment) 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 databasePrincipalProperties DatabasePrincipalProperties - err = json.Unmarshal(*v, &databasePrincipalProperties) - if err != nil { - return err - } - dpa.DatabasePrincipalProperties = &databasePrincipalProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - dpa.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - dpa.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - dpa.Type = &typeVar - } - } - } - - return nil -} - -// DatabasePrincipalAssignmentCheckNameRequest a principal assignment check name availability request. -type DatabasePrincipalAssignmentCheckNameRequest struct { - // Name - Principal Assignment resource name. - Name *string `json:"name,omitempty"` - // Type - The type of resource, Microsoft.Kusto/clusters/databases/principalAssignments. - Type *string `json:"type,omitempty"` -} - -// DatabasePrincipalAssignmentListResult the list Kusto database principal assignments operation response. -type DatabasePrincipalAssignmentListResult struct { - autorest.Response `json:"-"` - // Value - The list of Kusto database principal assignments. - Value *[]DatabasePrincipalAssignment `json:"value,omitempty"` -} - -// DatabasePrincipalAssignmentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type DatabasePrincipalAssignmentsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DatabasePrincipalAssignmentsClient) (DatabasePrincipalAssignment, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DatabasePrincipalAssignmentsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DatabasePrincipalAssignmentsCreateOrUpdateFuture.Result. -func (future *DatabasePrincipalAssignmentsCreateOrUpdateFuture) result(client DatabasePrincipalAssignmentsClient) (dpa DatabasePrincipalAssignment, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dpa.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.DatabasePrincipalAssignmentsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dpa.Response.Response, err = future.GetResult(sender); err == nil && dpa.Response.Response.StatusCode != http.StatusNoContent { - dpa, err = client.CreateOrUpdateResponder(dpa.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsCreateOrUpdateFuture", "Result", dpa.Response.Response, "Failure responding to request") - } - } - return -} - -// DatabasePrincipalAssignmentsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DatabasePrincipalAssignmentsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DatabasePrincipalAssignmentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DatabasePrincipalAssignmentsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DatabasePrincipalAssignmentsDeleteFuture.Result. -func (future *DatabasePrincipalAssignmentsDeleteFuture) result(client DatabasePrincipalAssignmentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasePrincipalAssignmentsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.DatabasePrincipalAssignmentsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// DatabasePrincipalListRequest the list Kusto database principals operation request. -type DatabasePrincipalListRequest struct { - // Value - The list of Kusto database principals. - Value *[]DatabasePrincipal `json:"value,omitempty"` -} - -// DatabasePrincipalListResult the list Kusto database principals operation response. -type DatabasePrincipalListResult struct { - autorest.Response `json:"-"` - // Value - The list of Kusto database principals. - Value *[]DatabasePrincipal `json:"value,omitempty"` -} - -// DatabasePrincipalProperties a class representing database principal property. -type DatabasePrincipalProperties struct { - // PrincipalID - The principal ID assigned to the database principal. It can be a user email, application ID, or security group name. - PrincipalID *string `json:"principalId,omitempty"` - // Role - Database principal role. Possible values include: 'DatabasePrincipalRoleAdmin', 'DatabasePrincipalRoleIngestor', 'DatabasePrincipalRoleMonitor', 'DatabasePrincipalRoleUser', 'DatabasePrincipalRoleUnrestrictedViewer', 'DatabasePrincipalRoleViewer' - Role DatabasePrincipalRole `json:"role,omitempty"` - // TenantID - The tenant id of the principal - TenantID *string `json:"tenantId,omitempty"` - // PrincipalType - Principal type. Possible values include: 'PrincipalTypeApp', 'PrincipalTypeGroup', 'PrincipalTypeUser' - PrincipalType PrincipalType `json:"principalType,omitempty"` - // TenantName - READ-ONLY; The tenant name of the principal - TenantName *string `json:"tenantName,omitempty"` - // PrincipalName - READ-ONLY; The principal name - PrincipalName *string `json:"principalName,omitempty"` - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for DatabasePrincipalProperties. -func (dpp DatabasePrincipalProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dpp.PrincipalID != nil { - objectMap["principalId"] = dpp.PrincipalID - } - if dpp.Role != "" { - objectMap["role"] = dpp.Role - } - if dpp.TenantID != nil { - objectMap["tenantId"] = dpp.TenantID - } - if dpp.PrincipalType != "" { - objectMap["principalType"] = dpp.PrincipalType - } - return json.Marshal(objectMap) -} - -// DatabasesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DatabasesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DatabasesClient) (DatabaseModel, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DatabasesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DatabasesCreateOrUpdateFuture.Result. -func (future *DatabasesCreateOrUpdateFuture) result(client DatabasesClient) (dm DatabaseModel, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dm.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.DatabasesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dm.Response.Response, err = future.GetResult(sender); err == nil && dm.Response.Response.StatusCode != http.StatusNoContent { - dm, err = client.CreateOrUpdateResponder(dm.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesCreateOrUpdateFuture", "Result", dm.Response.Response, "Failure responding to request") - } - } - return -} - -// DatabasesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DatabasesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DatabasesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DatabasesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DatabasesDeleteFuture.Result. -func (future *DatabasesDeleteFuture) result(client DatabasesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.DatabasesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// DatabaseStatistics a class that contains database statistics information. -type DatabaseStatistics struct { - // Size - The database size - the total size of compressed data and index in bytes. - Size *float64 `json:"size,omitempty"` -} - -// DatabasesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DatabasesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DatabasesClient) (DatabaseModel, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DatabasesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DatabasesUpdateFuture.Result. -func (future *DatabasesUpdateFuture) result(client DatabasesClient) (dm DatabaseModel, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dm.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.DatabasesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dm.Response.Response, err = future.GetResult(sender); err == nil && dm.Response.Response.StatusCode != http.StatusNoContent { - dm, err = client.UpdateResponder(dm.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DatabasesUpdateFuture", "Result", dm.Response.Response, "Failure responding to request") - } - } - return -} - -// BasicDataConnection class representing an data connection. -type BasicDataConnection interface { - AsEventHubDataConnection() (*EventHubDataConnection, bool) - AsIotHubDataConnection() (*IotHubDataConnection, bool) - AsEventGridDataConnection() (*EventGridDataConnection, bool) - AsDataConnection() (*DataConnection, bool) -} - -// DataConnection class representing an data connection. -type DataConnection struct { - autorest.Response `json:"-"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Kind - Possible values include: 'KindBasicDataConnectionKindDataConnection', 'KindBasicDataConnectionKindEventHub', 'KindBasicDataConnectionKindIotHub', 'KindBasicDataConnectionKindEventGrid' - Kind KindBasicDataConnection `json:"kind,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -func unmarshalBasicDataConnection(body []byte) (BasicDataConnection, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["kind"] { - case string(KindBasicDataConnectionKindEventHub): - var ehdc EventHubDataConnection - err := json.Unmarshal(body, &ehdc) - return ehdc, err - case string(KindBasicDataConnectionKindIotHub): - var ihdc IotHubDataConnection - err := json.Unmarshal(body, &ihdc) - return ihdc, err - case string(KindBasicDataConnectionKindEventGrid): - var egdc EventGridDataConnection - err := json.Unmarshal(body, &egdc) - return egdc, err - default: - var dc DataConnection - err := json.Unmarshal(body, &dc) - return dc, err - } -} -func unmarshalBasicDataConnectionArray(body []byte) ([]BasicDataConnection, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - dcArray := make([]BasicDataConnection, len(rawMessages)) - - for index, rawMessage := range rawMessages { - dc, err := unmarshalBasicDataConnection(*rawMessage) - if err != nil { - return nil, err - } - dcArray[index] = dc - } - return dcArray, nil -} - -// MarshalJSON is the custom marshaler for DataConnection. -func (dc DataConnection) MarshalJSON() ([]byte, error) { - dc.Kind = KindBasicDataConnectionKindDataConnection - objectMap := make(map[string]interface{}) - if dc.Location != nil { - objectMap["location"] = dc.Location - } - if dc.Kind != "" { - objectMap["kind"] = dc.Kind - } - return json.Marshal(objectMap) -} - -// AsEventHubDataConnection is the BasicDataConnection implementation for DataConnection. -func (dc DataConnection) AsEventHubDataConnection() (*EventHubDataConnection, bool) { - return nil, false -} - -// AsIotHubDataConnection is the BasicDataConnection implementation for DataConnection. -func (dc DataConnection) AsIotHubDataConnection() (*IotHubDataConnection, bool) { - return nil, false -} - -// AsEventGridDataConnection is the BasicDataConnection implementation for DataConnection. -func (dc DataConnection) AsEventGridDataConnection() (*EventGridDataConnection, bool) { - return nil, false -} - -// AsDataConnection is the BasicDataConnection implementation for DataConnection. -func (dc DataConnection) AsDataConnection() (*DataConnection, bool) { - return &dc, true -} - -// AsBasicDataConnection is the BasicDataConnection implementation for DataConnection. -func (dc DataConnection) AsBasicDataConnection() (BasicDataConnection, bool) { - return &dc, true -} - -// DataConnectionCheckNameRequest a data connection check name availability request. -type DataConnectionCheckNameRequest struct { - // Name - Data Connection name. - Name *string `json:"name,omitempty"` - // Type - The type of resource, Microsoft.Kusto/clusters/databases/dataConnections. - Type *string `json:"type,omitempty"` -} - -// DataConnectionListResult the list Kusto data connections operation response. -type DataConnectionListResult struct { - autorest.Response `json:"-"` - // Value - The list of Kusto data connections. - Value *[]BasicDataConnection `json:"value,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for DataConnectionListResult struct. -func (dclr *DataConnectionListResult) 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 "value": - if v != nil { - value, err := unmarshalBasicDataConnectionArray(*v) - if err != nil { - return err - } - dclr.Value = &value - } - } - } - - return nil -} - -// DataConnectionModel ... -type DataConnectionModel struct { - autorest.Response `json:"-"` - Value BasicDataConnection `json:"value,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for DataConnectionModel struct. -func (dcm *DataConnectionModel) UnmarshalJSON(body []byte) error { - dc, err := unmarshalBasicDataConnection(body) - if err != nil { - return err - } - dcm.Value = dc - - return nil -} - -// DataConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DataConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DataConnectionsClient) (DataConnectionModel, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DataConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DataConnectionsCreateOrUpdateFuture.Result. -func (future *DataConnectionsCreateOrUpdateFuture) result(client DataConnectionsClient) (dcm DataConnectionModel, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dcm.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.DataConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dcm.Response.Response, err = future.GetResult(sender); err == nil && dcm.Response.Response.StatusCode != http.StatusNoContent { - dcm, err = client.CreateOrUpdateResponder(dcm.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsCreateOrUpdateFuture", "Result", dcm.Response.Response, "Failure responding to request") - } - } - return -} - -// DataConnectionsDataConnectionValidationMethodFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type DataConnectionsDataConnectionValidationMethodFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DataConnectionsClient) (DataConnectionValidationListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DataConnectionsDataConnectionValidationMethodFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DataConnectionsDataConnectionValidationMethodFuture.Result. -func (future *DataConnectionsDataConnectionValidationMethodFuture) result(client DataConnectionsClient) (dcvlr DataConnectionValidationListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsDataConnectionValidationMethodFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dcvlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.DataConnectionsDataConnectionValidationMethodFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dcvlr.Response.Response, err = future.GetResult(sender); err == nil && dcvlr.Response.Response.StatusCode != http.StatusNoContent { - dcvlr, err = client.DataConnectionValidationMethodResponder(dcvlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsDataConnectionValidationMethodFuture", "Result", dcvlr.Response.Response, "Failure responding to request") - } - } - return -} - -// DataConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DataConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DataConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DataConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DataConnectionsDeleteFuture.Result. -func (future *DataConnectionsDeleteFuture) result(client DataConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.DataConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// DataConnectionsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DataConnectionsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DataConnectionsClient) (DataConnectionModel, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DataConnectionsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DataConnectionsUpdateFuture.Result. -func (future *DataConnectionsUpdateFuture) result(client DataConnectionsClient) (dcm DataConnectionModel, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dcm.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.DataConnectionsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dcm.Response.Response, err = future.GetResult(sender); err == nil && dcm.Response.Response.StatusCode != http.StatusNoContent { - dcm, err = client.UpdateResponder(dcm.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.DataConnectionsUpdateFuture", "Result", dcm.Response.Response, "Failure responding to request") - } - } - return -} - -// DataConnectionValidation class representing an data connection validation. -type DataConnectionValidation struct { - // DataConnectionName - The name of the data connection. - DataConnectionName *string `json:"dataConnectionName,omitempty"` - // Properties - The data connection properties to validate. - Properties BasicDataConnection `json:"properties,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for DataConnectionValidation struct. -func (dcv *DataConnectionValidation) 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 "dataConnectionName": - if v != nil { - var dataConnectionName string - err = json.Unmarshal(*v, &dataConnectionName) - if err != nil { - return err - } - dcv.DataConnectionName = &dataConnectionName - } - case "properties": - if v != nil { - properties, err := unmarshalBasicDataConnection(*v) - if err != nil { - return err - } - dcv.Properties = properties - } - } - } - - return nil -} - -// DataConnectionValidationListResult the list Kusto data connection validation result. -type DataConnectionValidationListResult struct { - autorest.Response `json:"-"` - // Value - The list of Kusto data connection validation errors. - Value *[]DataConnectionValidationResult `json:"value,omitempty"` -} - -// DataConnectionValidationResult the result returned from a data connection validation request. -type DataConnectionValidationResult struct { - // ErrorMessage - A message which indicates a problem in data connection validation. - ErrorMessage *string `json:"errorMessage,omitempty"` -} - -// DiagnoseVirtualNetworkResult ... -type DiagnoseVirtualNetworkResult struct { - autorest.Response `json:"-"` - // Findings - The list of network connectivity diagnostic finding - Findings *[]string `json:"findings,omitempty"` -} - -// EndpointDependency a domain name that a service is reached at, including details of the current -// connection status. -type EndpointDependency struct { - // DomainName - The domain name of the dependency. - DomainName *string `json:"domainName,omitempty"` - // EndpointDetails - The ports used when connecting to DomainName. - EndpointDetails *[]EndpointDetail `json:"endpointDetails,omitempty"` -} - -// EndpointDetail current TCP connectivity information from the Kusto cluster to a single endpoint. -type EndpointDetail struct { - // Port - The port an endpoint is connected to. - Port *int32 `json:"port,omitempty"` -} - -// EventGridConnectionProperties class representing the Kusto event grid connection properties. -type EventGridConnectionProperties struct { - // StorageAccountResourceID - The resource ID of the storage account where the data resides. - StorageAccountResourceID *string `json:"storageAccountResourceId,omitempty"` - // EventHubResourceID - The resource ID where the event grid is configured to send events. - EventHubResourceID *string `json:"eventHubResourceId,omitempty"` - // ConsumerGroup - The event hub consumer group. - ConsumerGroup *string `json:"consumerGroup,omitempty"` - // TableName - The table where the data should be ingested. Optionally the table information can be added to each message. - TableName *string `json:"tableName,omitempty"` - // MappingRuleName - The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. - MappingRuleName *string `json:"mappingRuleName,omitempty"` - // DataFormat - The data format of the message. Optionally the data format can be added to each message. Possible values include: 'EventGridDataFormatMULTIJSON', 'EventGridDataFormatJSON', 'EventGridDataFormatCSV', 'EventGridDataFormatTSV', 'EventGridDataFormatSCSV', 'EventGridDataFormatSOHSV', 'EventGridDataFormatPSV', 'EventGridDataFormatTXT', 'EventGridDataFormatRAW', 'EventGridDataFormatSINGLEJSON', 'EventGridDataFormatAVRO', 'EventGridDataFormatTSVE', 'EventGridDataFormatPARQUET', 'EventGridDataFormatORC', 'EventGridDataFormatAPACHEAVRO', 'EventGridDataFormatW3CLOGFILE' - DataFormat EventGridDataFormat `json:"dataFormat,omitempty"` - // IgnoreFirstRecord - A Boolean value that, if set to true, indicates that ingestion should ignore the first record of every file - IgnoreFirstRecord *bool `json:"ignoreFirstRecord,omitempty"` - // BlobStorageEventType - The name of blob storage event type to process. Possible values include: 'BlobStorageEventTypeMicrosoftStorageBlobCreated', 'BlobStorageEventTypeMicrosoftStorageBlobRenamed' - BlobStorageEventType BlobStorageEventType `json:"blobStorageEventType,omitempty"` - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for EventGridConnectionProperties. -func (egcp EventGridConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if egcp.StorageAccountResourceID != nil { - objectMap["storageAccountResourceId"] = egcp.StorageAccountResourceID - } - if egcp.EventHubResourceID != nil { - objectMap["eventHubResourceId"] = egcp.EventHubResourceID - } - if egcp.ConsumerGroup != nil { - objectMap["consumerGroup"] = egcp.ConsumerGroup - } - if egcp.TableName != nil { - objectMap["tableName"] = egcp.TableName - } - if egcp.MappingRuleName != nil { - objectMap["mappingRuleName"] = egcp.MappingRuleName - } - if egcp.DataFormat != "" { - objectMap["dataFormat"] = egcp.DataFormat - } - if egcp.IgnoreFirstRecord != nil { - objectMap["ignoreFirstRecord"] = egcp.IgnoreFirstRecord - } - if egcp.BlobStorageEventType != "" { - objectMap["blobStorageEventType"] = egcp.BlobStorageEventType - } - return json.Marshal(objectMap) -} - -// EventGridDataConnection class representing an Event Grid data connection. -type EventGridDataConnection struct { - // EventGridConnectionProperties - The properties of the Event Grid data connection. - *EventGridConnectionProperties `json:"properties,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Kind - Possible values include: 'KindBasicDataConnectionKindDataConnection', 'KindBasicDataConnectionKindEventHub', 'KindBasicDataConnectionKindIotHub', 'KindBasicDataConnectionKindEventGrid' - Kind KindBasicDataConnection `json:"kind,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for EventGridDataConnection. -func (egdc EventGridDataConnection) MarshalJSON() ([]byte, error) { - egdc.Kind = KindBasicDataConnectionKindEventGrid - objectMap := make(map[string]interface{}) - if egdc.EventGridConnectionProperties != nil { - objectMap["properties"] = egdc.EventGridConnectionProperties - } - if egdc.Location != nil { - objectMap["location"] = egdc.Location - } - if egdc.Kind != "" { - objectMap["kind"] = egdc.Kind - } - return json.Marshal(objectMap) -} - -// AsEventHubDataConnection is the BasicDataConnection implementation for EventGridDataConnection. -func (egdc EventGridDataConnection) AsEventHubDataConnection() (*EventHubDataConnection, bool) { - return nil, false -} - -// AsIotHubDataConnection is the BasicDataConnection implementation for EventGridDataConnection. -func (egdc EventGridDataConnection) AsIotHubDataConnection() (*IotHubDataConnection, bool) { - return nil, false -} - -// AsEventGridDataConnection is the BasicDataConnection implementation for EventGridDataConnection. -func (egdc EventGridDataConnection) AsEventGridDataConnection() (*EventGridDataConnection, bool) { - return &egdc, true -} - -// AsDataConnection is the BasicDataConnection implementation for EventGridDataConnection. -func (egdc EventGridDataConnection) AsDataConnection() (*DataConnection, bool) { - return nil, false -} - -// AsBasicDataConnection is the BasicDataConnection implementation for EventGridDataConnection. -func (egdc EventGridDataConnection) AsBasicDataConnection() (BasicDataConnection, bool) { - return &egdc, true -} - -// UnmarshalJSON is the custom unmarshaler for EventGridDataConnection struct. -func (egdc *EventGridDataConnection) 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 eventGridConnectionProperties EventGridConnectionProperties - err = json.Unmarshal(*v, &eventGridConnectionProperties) - if err != nil { - return err - } - egdc.EventGridConnectionProperties = &eventGridConnectionProperties - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - egdc.Location = &location - } - case "kind": - if v != nil { - var kind KindBasicDataConnection - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - egdc.Kind = kind - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - egdc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - egdc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - egdc.Type = &typeVar - } - } - } - - return nil -} - -// EventHubConnectionProperties class representing the Kusto event hub connection properties. -type EventHubConnectionProperties struct { - // EventHubResourceID - The resource ID of the event hub to be used to create a data connection. - EventHubResourceID *string `json:"eventHubResourceId,omitempty"` - // ConsumerGroup - The event hub consumer group. - ConsumerGroup *string `json:"consumerGroup,omitempty"` - // TableName - The table where the data should be ingested. Optionally the table information can be added to each message. - TableName *string `json:"tableName,omitempty"` - // MappingRuleName - The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. - MappingRuleName *string `json:"mappingRuleName,omitempty"` - // DataFormat - The data format of the message. Optionally the data format can be added to each message. Possible values include: 'EventHubDataFormatMULTIJSON', 'EventHubDataFormatJSON', 'EventHubDataFormatCSV', 'EventHubDataFormatTSV', 'EventHubDataFormatSCSV', 'EventHubDataFormatSOHSV', 'EventHubDataFormatPSV', 'EventHubDataFormatTXT', 'EventHubDataFormatRAW', 'EventHubDataFormatSINGLEJSON', 'EventHubDataFormatAVRO', 'EventHubDataFormatTSVE', 'EventHubDataFormatPARQUET', 'EventHubDataFormatORC', 'EventHubDataFormatAPACHEAVRO', 'EventHubDataFormatW3CLOGFILE' - DataFormat EventHubDataFormat `json:"dataFormat,omitempty"` - // EventSystemProperties - System properties of the event hub - EventSystemProperties *[]string `json:"eventSystemProperties,omitempty"` - // Compression - The event hub messages compression type. Possible values include: 'CompressionNone', 'CompressionGZip' - Compression Compression `json:"compression,omitempty"` - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ManagedIdentityResourceID - The resource ID of a managed identity (system or user assigned) to be used to authenticate with event hub. - ManagedIdentityResourceID *string `json:"managedIdentityResourceId,omitempty"` -} - -// MarshalJSON is the custom marshaler for EventHubConnectionProperties. -func (ehcp EventHubConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ehcp.EventHubResourceID != nil { - objectMap["eventHubResourceId"] = ehcp.EventHubResourceID - } - if ehcp.ConsumerGroup != nil { - objectMap["consumerGroup"] = ehcp.ConsumerGroup - } - if ehcp.TableName != nil { - objectMap["tableName"] = ehcp.TableName - } - if ehcp.MappingRuleName != nil { - objectMap["mappingRuleName"] = ehcp.MappingRuleName - } - if ehcp.DataFormat != "" { - objectMap["dataFormat"] = ehcp.DataFormat - } - if ehcp.EventSystemProperties != nil { - objectMap["eventSystemProperties"] = ehcp.EventSystemProperties - } - if ehcp.Compression != "" { - objectMap["compression"] = ehcp.Compression - } - if ehcp.ManagedIdentityResourceID != nil { - objectMap["managedIdentityResourceId"] = ehcp.ManagedIdentityResourceID - } - return json.Marshal(objectMap) -} - -// EventHubDataConnection class representing an event hub data connection. -type EventHubDataConnection struct { - // EventHubConnectionProperties - The Event Hub data connection properties to validate. - *EventHubConnectionProperties `json:"properties,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Kind - Possible values include: 'KindBasicDataConnectionKindDataConnection', 'KindBasicDataConnectionKindEventHub', 'KindBasicDataConnectionKindIotHub', 'KindBasicDataConnectionKindEventGrid' - Kind KindBasicDataConnection `json:"kind,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for EventHubDataConnection. -func (ehdc EventHubDataConnection) MarshalJSON() ([]byte, error) { - ehdc.Kind = KindBasicDataConnectionKindEventHub - objectMap := make(map[string]interface{}) - if ehdc.EventHubConnectionProperties != nil { - objectMap["properties"] = ehdc.EventHubConnectionProperties - } - if ehdc.Location != nil { - objectMap["location"] = ehdc.Location - } - if ehdc.Kind != "" { - objectMap["kind"] = ehdc.Kind - } - return json.Marshal(objectMap) -} - -// AsEventHubDataConnection is the BasicDataConnection implementation for EventHubDataConnection. -func (ehdc EventHubDataConnection) AsEventHubDataConnection() (*EventHubDataConnection, bool) { - return &ehdc, true -} - -// AsIotHubDataConnection is the BasicDataConnection implementation for EventHubDataConnection. -func (ehdc EventHubDataConnection) AsIotHubDataConnection() (*IotHubDataConnection, bool) { - return nil, false -} - -// AsEventGridDataConnection is the BasicDataConnection implementation for EventHubDataConnection. -func (ehdc EventHubDataConnection) AsEventGridDataConnection() (*EventGridDataConnection, bool) { - return nil, false -} - -// AsDataConnection is the BasicDataConnection implementation for EventHubDataConnection. -func (ehdc EventHubDataConnection) AsDataConnection() (*DataConnection, bool) { - return nil, false -} - -// AsBasicDataConnection is the BasicDataConnection implementation for EventHubDataConnection. -func (ehdc EventHubDataConnection) AsBasicDataConnection() (BasicDataConnection, bool) { - return &ehdc, true -} - -// UnmarshalJSON is the custom unmarshaler for EventHubDataConnection struct. -func (ehdc *EventHubDataConnection) 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 eventHubConnectionProperties EventHubConnectionProperties - err = json.Unmarshal(*v, &eventHubConnectionProperties) - if err != nil { - return err - } - ehdc.EventHubConnectionProperties = &eventHubConnectionProperties - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ehdc.Location = &location - } - case "kind": - if v != nil { - var kind KindBasicDataConnection - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - ehdc.Kind = kind - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ehdc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ehdc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ehdc.Type = &typeVar - } - } - } - - return nil -} - -// FollowerDatabaseDefinition a class representing follower database request. -type FollowerDatabaseDefinition struct { - // ClusterResourceID - Resource id of the cluster that follows a database owned by this cluster. - ClusterResourceID *string `json:"clusterResourceId,omitempty"` - // AttachedDatabaseConfigurationName - Resource name of the attached database configuration in the follower cluster. - AttachedDatabaseConfigurationName *string `json:"attachedDatabaseConfigurationName,omitempty"` - // DatabaseName - READ-ONLY; The database name owned by this cluster that was followed. * in case following all databases. - DatabaseName *string `json:"databaseName,omitempty"` -} - -// MarshalJSON is the custom marshaler for FollowerDatabaseDefinition. -func (fdd FollowerDatabaseDefinition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fdd.ClusterResourceID != nil { - objectMap["clusterResourceId"] = fdd.ClusterResourceID - } - if fdd.AttachedDatabaseConfigurationName != nil { - objectMap["attachedDatabaseConfigurationName"] = fdd.AttachedDatabaseConfigurationName - } - return json.Marshal(objectMap) -} - -// FollowerDatabaseListResult the list Kusto database principals operation response. -type FollowerDatabaseListResult struct { - autorest.Response `json:"-"` - // Value - The list of follower database result. - Value *[]FollowerDatabaseDefinition `json:"value,omitempty"` -} - -// Identity identity for the resource. -type Identity struct { - // PrincipalID - READ-ONLY; The principal ID of resource identity. - PrincipalID *string `json:"principalId,omitempty"` - // TenantID - READ-ONLY; The tenant ID of resource. - TenantID *string `json:"tenantId,omitempty"` - // Type - The type of managed identity used. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user-assigned identities. The type 'None' will remove all identities. Possible values include: 'IdentityTypeNone', 'IdentityTypeSystemAssigned', 'IdentityTypeUserAssigned', 'IdentityTypeSystemAssignedUserAssigned' - Type IdentityType `json:"type,omitempty"` - // UserAssignedIdentities - The list of user identities associated with the Kusto cluster. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - UserAssignedIdentities map[string]*IdentityUserAssignedIdentitiesValue `json:"userAssignedIdentities"` -} - -// MarshalJSON is the custom marshaler for Identity. -func (i Identity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if i.Type != "" { - objectMap["type"] = i.Type - } - if i.UserAssignedIdentities != nil { - objectMap["userAssignedIdentities"] = i.UserAssignedIdentities - } - return json.Marshal(objectMap) -} - -// IdentityUserAssignedIdentitiesValue ... -type IdentityUserAssignedIdentitiesValue struct { - // PrincipalID - READ-ONLY; The principal id of user assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // ClientID - READ-ONLY; The client id of user assigned identity. - ClientID *string `json:"clientId,omitempty"` -} - -// MarshalJSON is the custom marshaler for IdentityUserAssignedIdentitiesValue. -func (iAiv IdentityUserAssignedIdentitiesValue) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// IotHubConnectionProperties class representing the Kusto Iot hub connection properties. -type IotHubConnectionProperties struct { - // IotHubResourceID - The resource ID of the Iot hub to be used to create a data connection. - IotHubResourceID *string `json:"iotHubResourceId,omitempty"` - // ConsumerGroup - The iot hub consumer group. - ConsumerGroup *string `json:"consumerGroup,omitempty"` - // TableName - The table where the data should be ingested. Optionally the table information can be added to each message. - TableName *string `json:"tableName,omitempty"` - // MappingRuleName - The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. - MappingRuleName *string `json:"mappingRuleName,omitempty"` - // DataFormat - The data format of the message. Optionally the data format can be added to each message. Possible values include: 'IotHubDataFormatMULTIJSON', 'IotHubDataFormatJSON', 'IotHubDataFormatCSV', 'IotHubDataFormatTSV', 'IotHubDataFormatSCSV', 'IotHubDataFormatSOHSV', 'IotHubDataFormatPSV', 'IotHubDataFormatTXT', 'IotHubDataFormatRAW', 'IotHubDataFormatSINGLEJSON', 'IotHubDataFormatAVRO', 'IotHubDataFormatTSVE', 'IotHubDataFormatPARQUET', 'IotHubDataFormatORC', 'IotHubDataFormatAPACHEAVRO', 'IotHubDataFormatW3CLOGFILE' - DataFormat IotHubDataFormat `json:"dataFormat,omitempty"` - // EventSystemProperties - System properties of the iot hub - EventSystemProperties *[]string `json:"eventSystemProperties,omitempty"` - // SharedAccessPolicyName - The name of the share access policy - SharedAccessPolicyName *string `json:"sharedAccessPolicyName,omitempty"` - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for IotHubConnectionProperties. -func (ihcp IotHubConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ihcp.IotHubResourceID != nil { - objectMap["iotHubResourceId"] = ihcp.IotHubResourceID - } - if ihcp.ConsumerGroup != nil { - objectMap["consumerGroup"] = ihcp.ConsumerGroup - } - if ihcp.TableName != nil { - objectMap["tableName"] = ihcp.TableName - } - if ihcp.MappingRuleName != nil { - objectMap["mappingRuleName"] = ihcp.MappingRuleName - } - if ihcp.DataFormat != "" { - objectMap["dataFormat"] = ihcp.DataFormat - } - if ihcp.EventSystemProperties != nil { - objectMap["eventSystemProperties"] = ihcp.EventSystemProperties - } - if ihcp.SharedAccessPolicyName != nil { - objectMap["sharedAccessPolicyName"] = ihcp.SharedAccessPolicyName - } - return json.Marshal(objectMap) -} - -// IotHubDataConnection class representing an iot hub data connection. -type IotHubDataConnection struct { - // IotHubConnectionProperties - The Iot Hub data connection properties. - *IotHubConnectionProperties `json:"properties,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Kind - Possible values include: 'KindBasicDataConnectionKindDataConnection', 'KindBasicDataConnectionKindEventHub', 'KindBasicDataConnectionKindIotHub', 'KindBasicDataConnectionKindEventGrid' - Kind KindBasicDataConnection `json:"kind,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for IotHubDataConnection. -func (ihdc IotHubDataConnection) MarshalJSON() ([]byte, error) { - ihdc.Kind = KindBasicDataConnectionKindIotHub - objectMap := make(map[string]interface{}) - if ihdc.IotHubConnectionProperties != nil { - objectMap["properties"] = ihdc.IotHubConnectionProperties - } - if ihdc.Location != nil { - objectMap["location"] = ihdc.Location - } - if ihdc.Kind != "" { - objectMap["kind"] = ihdc.Kind - } - return json.Marshal(objectMap) -} - -// AsEventHubDataConnection is the BasicDataConnection implementation for IotHubDataConnection. -func (ihdc IotHubDataConnection) AsEventHubDataConnection() (*EventHubDataConnection, bool) { - return nil, false -} - -// AsIotHubDataConnection is the BasicDataConnection implementation for IotHubDataConnection. -func (ihdc IotHubDataConnection) AsIotHubDataConnection() (*IotHubDataConnection, bool) { - return &ihdc, true -} - -// AsEventGridDataConnection is the BasicDataConnection implementation for IotHubDataConnection. -func (ihdc IotHubDataConnection) AsEventGridDataConnection() (*EventGridDataConnection, bool) { - return nil, false -} - -// AsDataConnection is the BasicDataConnection implementation for IotHubDataConnection. -func (ihdc IotHubDataConnection) AsDataConnection() (*DataConnection, bool) { - return nil, false -} - -// AsBasicDataConnection is the BasicDataConnection implementation for IotHubDataConnection. -func (ihdc IotHubDataConnection) AsBasicDataConnection() (BasicDataConnection, bool) { - return &ihdc, true -} - -// UnmarshalJSON is the custom unmarshaler for IotHubDataConnection struct. -func (ihdc *IotHubDataConnection) 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 iotHubConnectionProperties IotHubConnectionProperties - err = json.Unmarshal(*v, &iotHubConnectionProperties) - if err != nil { - return err - } - ihdc.IotHubConnectionProperties = &iotHubConnectionProperties - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ihdc.Location = &location - } - case "kind": - if v != nil { - var kind KindBasicDataConnection - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - ihdc.Kind = kind - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ihdc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ihdc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ihdc.Type = &typeVar - } - } - } - - return nil -} - -// KeyVaultProperties properties of the key vault. -type KeyVaultProperties struct { - // KeyName - The name of the key vault key. - KeyName *string `json:"keyName,omitempty"` - // KeyVersion - The version of the key vault key. - KeyVersion *string `json:"keyVersion,omitempty"` - // KeyVaultURI - The Uri of the key vault. - KeyVaultURI *string `json:"keyVaultUri,omitempty"` - // UserIdentity - The user assigned identity (ARM resource id) that has access to the key. - UserIdentity *string `json:"userIdentity,omitempty"` -} - -// LanguageExtension the language extension object. -type LanguageExtension struct { - // LanguageExtensionName - The language extension name. Possible values include: 'LanguageExtensionNamePYTHON', 'LanguageExtensionNameR' - LanguageExtensionName LanguageExtensionName `json:"languageExtensionName,omitempty"` -} - -// LanguageExtensionsList the list of language extension objects. -type LanguageExtensionsList struct { - autorest.Response `json:"-"` - // Value - The list of language extensions. - Value *[]LanguageExtension `json:"value,omitempty"` -} - -// ListResourceSkusResult list of available SKUs for a Kusto Cluster. -type ListResourceSkusResult struct { - autorest.Response `json:"-"` - // Value - The collection of available SKUs for an existing resource. - Value *[]AzureResourceSku `json:"value,omitempty"` -} - -// ManagedPrivateEndpoint class representing a managed private endpoint. -type ManagedPrivateEndpoint struct { - autorest.Response `json:"-"` - // ManagedPrivateEndpointProperties - A managed private endpoint. - *ManagedPrivateEndpointProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ManagedPrivateEndpoint. -func (mpe ManagedPrivateEndpoint) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mpe.ManagedPrivateEndpointProperties != nil { - objectMap["properties"] = mpe.ManagedPrivateEndpointProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ManagedPrivateEndpoint struct. -func (mpe *ManagedPrivateEndpoint) 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 managedPrivateEndpointProperties ManagedPrivateEndpointProperties - err = json.Unmarshal(*v, &managedPrivateEndpointProperties) - if err != nil { - return err - } - mpe.ManagedPrivateEndpointProperties = &managedPrivateEndpointProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - mpe.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - mpe.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - mpe.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - mpe.Type = &typeVar - } - } - } - - return nil -} - -// ManagedPrivateEndpointListResult the list managed private endpoints operation response. -type ManagedPrivateEndpointListResult struct { - autorest.Response `json:"-"` - // Value - The list of managed private endpoints. - Value *[]ManagedPrivateEndpoint `json:"value,omitempty"` -} - -// ManagedPrivateEndpointProperties a class representing the properties of a managed private endpoint -// object. -type ManagedPrivateEndpointProperties struct { - // PrivateLinkResourceID - The ARM resource ID of the resource for which the managed private endpoint is created. - PrivateLinkResourceID *string `json:"privateLinkResourceId,omitempty"` - // PrivateLinkResourceRegion - The region of the resource to which the managed private endpoint is created. - PrivateLinkResourceRegion *string `json:"privateLinkResourceRegion,omitempty"` - // GroupID - The groupId in which the managed private endpoint is created. - GroupID *string `json:"groupId,omitempty"` - // RequestMessage - The user request message. - RequestMessage *string `json:"requestMessage,omitempty"` - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ManagedPrivateEndpointProperties. -func (mpep ManagedPrivateEndpointProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mpep.PrivateLinkResourceID != nil { - objectMap["privateLinkResourceId"] = mpep.PrivateLinkResourceID - } - if mpep.PrivateLinkResourceRegion != nil { - objectMap["privateLinkResourceRegion"] = mpep.PrivateLinkResourceRegion - } - if mpep.GroupID != nil { - objectMap["groupId"] = mpep.GroupID - } - if mpep.RequestMessage != nil { - objectMap["requestMessage"] = mpep.RequestMessage - } - return json.Marshal(objectMap) -} - -// ManagedPrivateEndpointsCheckNameRequest the result returned from a managedPrivateEndpoints check name -// availability request. -type ManagedPrivateEndpointsCheckNameRequest struct { - // Name - Managed private endpoint resource name. - Name *string `json:"name,omitempty"` - // Type - The type of resource, for instance Microsoft.Kusto/clusters/managedPrivateEndpoints. - Type *string `json:"type,omitempty"` -} - -// ManagedPrivateEndpointsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type ManagedPrivateEndpointsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ManagedPrivateEndpointsClient) (ManagedPrivateEndpoint, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ManagedPrivateEndpointsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ManagedPrivateEndpointsCreateOrUpdateFuture.Result. -func (future *ManagedPrivateEndpointsCreateOrUpdateFuture) result(client ManagedPrivateEndpointsClient) (mpe ManagedPrivateEndpoint, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - mpe.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ManagedPrivateEndpointsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if mpe.Response.Response, err = future.GetResult(sender); err == nil && mpe.Response.Response.StatusCode != http.StatusNoContent { - mpe, err = client.CreateOrUpdateResponder(mpe.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsCreateOrUpdateFuture", "Result", mpe.Response.Response, "Failure responding to request") - } - } - return -} - -// ManagedPrivateEndpointsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ManagedPrivateEndpointsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ManagedPrivateEndpointsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ManagedPrivateEndpointsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ManagedPrivateEndpointsDeleteFuture.Result. -func (future *ManagedPrivateEndpointsDeleteFuture) result(client ManagedPrivateEndpointsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ManagedPrivateEndpointsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ManagedPrivateEndpointsUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ManagedPrivateEndpointsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ManagedPrivateEndpointsClient) (ManagedPrivateEndpoint, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ManagedPrivateEndpointsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ManagedPrivateEndpointsUpdateFuture.Result. -func (future *ManagedPrivateEndpointsUpdateFuture) result(client ManagedPrivateEndpointsClient) (mpe ManagedPrivateEndpoint, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - mpe.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ManagedPrivateEndpointsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if mpe.Response.Response, err = future.GetResult(sender); err == nil && mpe.Response.Response.StatusCode != http.StatusNoContent { - mpe, err = client.UpdateResponder(mpe.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ManagedPrivateEndpointsUpdateFuture", "Result", mpe.Response.Response, "Failure responding to request") - } - } - return -} - -// Operation ... -type Operation struct { - // Name - This is of the format {provider}/{resource}/{operation}. - Name *string `json:"name,omitempty"` - Display *OperationDisplay `json:"display,omitempty"` - Origin *string `json:"origin,omitempty"` - Properties interface{} `json:"properties,omitempty"` -} - -// OperationDisplay ... -type OperationDisplay struct { - Provider *string `json:"provider,omitempty"` - // Operation - For example: read, write, delete. - Operation *string `json:"operation,omitempty"` - Resource *string `json:"resource,omitempty"` - Description *string `json:"description,omitempty"` -} - -// OperationListResult ... -type OperationListResult struct { - autorest.Response `json:"-"` - Value *[]Operation `json:"value,omitempty"` - NextLink *string `json:"nextLink,omitempty"` -} - -// OperationListResultIterator provides access to a complete listing of Operation values. -type OperationListResultIterator struct { - i int - page OperationListResultPage -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *OperationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the OperationListResultIterator type. -func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator { - return OperationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (olr OperationListResult) IsEmpty() bool { - return olr.Value == nil || len(*olr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (olr OperationListResult) hasNextLink() bool { - return olr.NextLink != nil && len(*olr.NextLink) != 0 -} - -// operationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (olr OperationListResult) operationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !olr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(olr.NextLink))) -} - -// OperationListResultPage contains a page of Operation values. -type OperationListResultPage struct { - fn func(context.Context, OperationListResult) (OperationListResult, error) - olr OperationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.olr) - if err != nil { - return err - } - page.olr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *OperationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the OperationListResultPage type. -func NewOperationListResultPage(cur OperationListResult, getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage { - return OperationListResultPage{ - fn: getNextPage, - olr: cur, - } -} - -// OperationResult operation Result Entity. -type OperationResult struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; ID of the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Name of the resource. - Name *string `json:"name,omitempty"` - // Status - status of the Operation result. Possible values include: 'StatusSucceeded', 'StatusCanceled', 'StatusFailed', 'StatusRunning' - Status Status `json:"status,omitempty"` - // StartTime - The operation start time - StartTime *date.Time `json:"startTime,omitempty"` - // EndTime - The operation end time - EndTime *date.Time `json:"endTime,omitempty"` - // PercentComplete - Percentage completed. - PercentComplete *float64 `json:"percentComplete,omitempty"` - // OperationResultProperties - Properties of the operation results - *OperationResultProperties `json:"properties,omitempty"` - // OperationResultErrorProperties - Object that contains the error code and message if the operation failed. - *OperationResultErrorProperties `json:"error,omitempty"` -} - -// MarshalJSON is the custom marshaler for OperationResult. -func (or OperationResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if or.Status != "" { - objectMap["status"] = or.Status - } - if or.StartTime != nil { - objectMap["startTime"] = or.StartTime - } - if or.EndTime != nil { - objectMap["endTime"] = or.EndTime - } - if or.PercentComplete != nil { - objectMap["percentComplete"] = or.PercentComplete - } - if or.OperationResultProperties != nil { - objectMap["properties"] = or.OperationResultProperties - } - if or.OperationResultErrorProperties != nil { - objectMap["error"] = or.OperationResultErrorProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for OperationResult struct. -func (or *OperationResult) 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 "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - or.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - or.Name = &name - } - case "status": - if v != nil { - var status Status - err = json.Unmarshal(*v, &status) - if err != nil { - return err - } - or.Status = status - } - case "startTime": - if v != nil { - var startTime date.Time - err = json.Unmarshal(*v, &startTime) - if err != nil { - return err - } - or.StartTime = &startTime - } - case "endTime": - if v != nil { - var endTime date.Time - err = json.Unmarshal(*v, &endTime) - if err != nil { - return err - } - or.EndTime = &endTime - } - case "percentComplete": - if v != nil { - var percentComplete float64 - err = json.Unmarshal(*v, &percentComplete) - if err != nil { - return err - } - or.PercentComplete = &percentComplete - } - case "properties": - if v != nil { - var operationResultProperties OperationResultProperties - err = json.Unmarshal(*v, &operationResultProperties) - if err != nil { - return err - } - or.OperationResultProperties = &operationResultProperties - } - case "error": - if v != nil { - var operationResultErrorProperties OperationResultErrorProperties - err = json.Unmarshal(*v, &operationResultErrorProperties) - if err != nil { - return err - } - or.OperationResultErrorProperties = &operationResultErrorProperties - } - } - } - - return nil -} - -// OperationResultErrorProperties operation result error properties -type OperationResultErrorProperties struct { - // Code - The code of the error. - Code *string `json:"code,omitempty"` - // Message - The error message. - Message *string `json:"message,omitempty"` -} - -// OperationResultProperties operation result properties -type OperationResultProperties struct { - // OperationKind - The kind of the operation. - OperationKind *string `json:"operationKind,omitempty"` - // OperationState - The state of the operation. - OperationState *string `json:"operationState,omitempty"` -} - -// OptimizedAutoscale a class that contains the optimized auto scale definition. -type OptimizedAutoscale struct { - // Version - The version of the template defined, for instance 1. - Version *int32 `json:"version,omitempty"` - // IsEnabled - A boolean value that indicate if the optimized autoscale feature is enabled or not. - IsEnabled *bool `json:"isEnabled,omitempty"` - // Minimum - Minimum allowed instances count. - Minimum *int32 `json:"minimum,omitempty"` - // Maximum - Maximum allowed instances count. - Maximum *int32 `json:"maximum,omitempty"` -} - -// OutboundNetworkDependenciesEndpoint endpoints accessed for a common purpose that the Kusto Service -// Environment requires outbound network access to. -type OutboundNetworkDependenciesEndpoint struct { - // OutboundNetworkDependenciesEndpointProperties - The outbound environment endpoint properties. - *OutboundNetworkDependenciesEndpointProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for OutboundNetworkDependenciesEndpoint. -func (onde OutboundNetworkDependenciesEndpoint) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if onde.OutboundNetworkDependenciesEndpointProperties != nil { - objectMap["properties"] = onde.OutboundNetworkDependenciesEndpointProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for OutboundNetworkDependenciesEndpoint struct. -func (onde *OutboundNetworkDependenciesEndpoint) 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 outboundNetworkDependenciesEndpointProperties OutboundNetworkDependenciesEndpointProperties - err = json.Unmarshal(*v, &outboundNetworkDependenciesEndpointProperties) - if err != nil { - return err - } - onde.OutboundNetworkDependenciesEndpointProperties = &outboundNetworkDependenciesEndpointProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - onde.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - onde.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - onde.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - onde.Type = &typeVar - } - } - } - - return nil -} - -// OutboundNetworkDependenciesEndpointListResult collection of Outbound Environment Endpoints -type OutboundNetworkDependenciesEndpointListResult struct { - autorest.Response `json:"-"` - // Value - Collection of resources. - Value *[]OutboundNetworkDependenciesEndpoint `json:"value,omitempty"` - // NextLink - READ-ONLY; Link to next page of resources. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for OutboundNetworkDependenciesEndpointListResult. -func (ondelr OutboundNetworkDependenciesEndpointListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ondelr.Value != nil { - objectMap["value"] = ondelr.Value - } - return json.Marshal(objectMap) -} - -// OutboundNetworkDependenciesEndpointListResultIterator provides access to a complete listing of -// OutboundNetworkDependenciesEndpoint values. -type OutboundNetworkDependenciesEndpointListResultIterator struct { - i int - page OutboundNetworkDependenciesEndpointListResultPage -} - -// NextWithContext 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 *OutboundNetworkDependenciesEndpointListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OutboundNetworkDependenciesEndpointListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *OutboundNetworkDependenciesEndpointListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter OutboundNetworkDependenciesEndpointListResultIterator) 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 OutboundNetworkDependenciesEndpointListResultIterator) Response() OutboundNetworkDependenciesEndpointListResult { - 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 OutboundNetworkDependenciesEndpointListResultIterator) Value() OutboundNetworkDependenciesEndpoint { - if !iter.page.NotDone() { - return OutboundNetworkDependenciesEndpoint{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the OutboundNetworkDependenciesEndpointListResultIterator type. -func NewOutboundNetworkDependenciesEndpointListResultIterator(page OutboundNetworkDependenciesEndpointListResultPage) OutboundNetworkDependenciesEndpointListResultIterator { - return OutboundNetworkDependenciesEndpointListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ondelr OutboundNetworkDependenciesEndpointListResult) IsEmpty() bool { - return ondelr.Value == nil || len(*ondelr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ondelr OutboundNetworkDependenciesEndpointListResult) hasNextLink() bool { - return ondelr.NextLink != nil && len(*ondelr.NextLink) != 0 -} - -// outboundNetworkDependenciesEndpointListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ondelr OutboundNetworkDependenciesEndpointListResult) outboundNetworkDependenciesEndpointListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ondelr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ondelr.NextLink))) -} - -// OutboundNetworkDependenciesEndpointListResultPage contains a page of OutboundNetworkDependenciesEndpoint -// values. -type OutboundNetworkDependenciesEndpointListResultPage struct { - fn func(context.Context, OutboundNetworkDependenciesEndpointListResult) (OutboundNetworkDependenciesEndpointListResult, error) - ondelr OutboundNetworkDependenciesEndpointListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *OutboundNetworkDependenciesEndpointListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OutboundNetworkDependenciesEndpointListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ondelr) - if err != nil { - return err - } - page.ondelr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *OutboundNetworkDependenciesEndpointListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page OutboundNetworkDependenciesEndpointListResultPage) NotDone() bool { - return !page.ondelr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page OutboundNetworkDependenciesEndpointListResultPage) Response() OutboundNetworkDependenciesEndpointListResult { - return page.ondelr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page OutboundNetworkDependenciesEndpointListResultPage) Values() []OutboundNetworkDependenciesEndpoint { - if page.ondelr.IsEmpty() { - return nil - } - return *page.ondelr.Value -} - -// Creates a new instance of the OutboundNetworkDependenciesEndpointListResultPage type. -func NewOutboundNetworkDependenciesEndpointListResultPage(cur OutboundNetworkDependenciesEndpointListResult, getNextPage func(context.Context, OutboundNetworkDependenciesEndpointListResult) (OutboundNetworkDependenciesEndpointListResult, error)) OutboundNetworkDependenciesEndpointListResultPage { - return OutboundNetworkDependenciesEndpointListResultPage{ - fn: getNextPage, - ondelr: cur, - } -} - -// OutboundNetworkDependenciesEndpointProperties endpoints accessed for a common purpose that the Kusto -// Service Environment requires outbound network access to. -type OutboundNetworkDependenciesEndpointProperties struct { - // Category - The type of service accessed by the Kusto Service Environment, e.g., Azure Storage, Azure SQL Database, and Azure Active Directory. - Category *string `json:"category,omitempty"` - // Endpoints - The endpoints that the Kusto Service Environment reaches the service at. - Endpoints *[]EndpointDependency `json:"endpoints,omitempty"` - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for OutboundNetworkDependenciesEndpointProperties. -func (ondep OutboundNetworkDependenciesEndpointProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ondep.Category != nil { - objectMap["category"] = ondep.Category - } - if ondep.Endpoints != nil { - objectMap["endpoints"] = ondep.Endpoints - } - return json.Marshal(objectMap) -} - -// PrivateEndpointConnection a private endpoint connection -type PrivateEndpointConnection struct { - autorest.Response `json:"-"` - // PrivateEndpointConnectionProperties - Resource properties. - *PrivateEndpointConnectionProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointConnection. -func (pec PrivateEndpointConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pec.PrivateEndpointConnectionProperties != nil { - objectMap["properties"] = pec.PrivateEndpointConnectionProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateEndpointConnection struct. -func (pec *PrivateEndpointConnection) 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 privateEndpointConnectionProperties PrivateEndpointConnectionProperties - err = json.Unmarshal(*v, &privateEndpointConnectionProperties) - if err != nil { - return err - } - pec.PrivateEndpointConnectionProperties = &privateEndpointConnectionProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - pec.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pec.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pec.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pec.Type = &typeVar - } - } - } - - return nil -} - -// PrivateEndpointConnectionListResult a list of private endpoint connections -type PrivateEndpointConnectionListResult struct { - autorest.Response `json:"-"` - // Value - Array of private endpoint connections - Value *[]PrivateEndpointConnection `json:"value,omitempty"` -} - -// PrivateEndpointConnectionProperties properties of a private endpoint connection. -type PrivateEndpointConnectionProperties struct { - // PrivateEndpoint - READ-ONLY; Private endpoint which the connection belongs to. - PrivateEndpoint *PrivateEndpointProperty `json:"privateEndpoint,omitempty"` - // PrivateLinkServiceConnectionState - Connection State of the Private Endpoint Connection. - PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionStateProperty `json:"privateLinkServiceConnectionState,omitempty"` - // GroupID - READ-ONLY; Group id of the private endpoint. - GroupID *string `json:"groupId,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the private endpoint. - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointConnectionProperties. -func (pecp PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pecp.PrivateLinkServiceConnectionState != nil { - objectMap["privateLinkServiceConnectionState"] = pecp.PrivateLinkServiceConnectionState - } - return json.Marshal(objectMap) -} - -// PrivateEndpointConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type PrivateEndpointConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateEndpointConnectionsClient) (PrivateEndpointConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateEndpointConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateEndpointConnectionsCreateOrUpdateFuture.Result. -func (future *PrivateEndpointConnectionsCreateOrUpdateFuture) result(client PrivateEndpointConnectionsClient) (pec PrivateEndpointConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pec.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.PrivateEndpointConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pec.Response.Response, err = future.GetResult(sender); err == nil && pec.Response.Response.StatusCode != http.StatusNoContent { - pec, err = client.CreateOrUpdateResponder(pec.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsCreateOrUpdateFuture", "Result", pec.Response.Response, "Failure responding to request") - } - } - return -} - -// PrivateEndpointConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PrivateEndpointConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateEndpointConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateEndpointConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateEndpointConnectionsDeleteFuture.Result. -func (future *PrivateEndpointConnectionsDeleteFuture) result(client PrivateEndpointConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.PrivateEndpointConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PrivateEndpointProperty private endpoint which the connection belongs to. -type PrivateEndpointProperty struct { - // ID - READ-ONLY; Resource id of the private endpoint. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointProperty. -func (pep PrivateEndpointProperty) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PrivateLinkResource a private link resource -type PrivateLinkResource struct { - autorest.Response `json:"-"` - // PrivateLinkResourceProperties - Resource properties. - *PrivateLinkResourceProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkResource. -func (plr PrivateLinkResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if plr.PrivateLinkResourceProperties != nil { - objectMap["properties"] = plr.PrivateLinkResourceProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateLinkResource struct. -func (plr *PrivateLinkResource) 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 privateLinkResourceProperties PrivateLinkResourceProperties - err = json.Unmarshal(*v, &privateLinkResourceProperties) - if err != nil { - return err - } - plr.PrivateLinkResourceProperties = &privateLinkResourceProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - plr.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - plr.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - plr.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - plr.Type = &typeVar - } - } - } - - return nil -} - -// PrivateLinkResourceListResult a list of private link resources -type PrivateLinkResourceListResult struct { - autorest.Response `json:"-"` - // Value - Array of private link resources - Value *[]PrivateLinkResource `json:"value,omitempty"` -} - -// PrivateLinkResourceProperties properties of a private link resource. -type PrivateLinkResourceProperties struct { - // GroupID - READ-ONLY; The private link resource group id. - GroupID *string `json:"groupId,omitempty"` - // RequiredMembers - READ-ONLY; The private link resource required member names. - RequiredMembers *[]string `json:"requiredMembers,omitempty"` - // RequiredZoneNames - READ-ONLY; The private link resource required zone names. - RequiredZoneNames *[]string `json:"requiredZoneNames,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkResourceProperties. -func (plrp PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PrivateLinkServiceConnectionStateProperty connection State of the Private Endpoint Connection. -type PrivateLinkServiceConnectionStateProperty struct { - // Status - The private link service connection status. - Status *string `json:"status,omitempty"` - // Description - The private link service connection description. - Description *string `json:"description,omitempty"` - // ActionsRequired - READ-ONLY; Any action that is required beyond basic workflow (approve/ reject/ disconnect) - ActionsRequired *string `json:"actionsRequired,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkServiceConnectionStateProperty. -func (plscsp PrivateLinkServiceConnectionStateProperty) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if plscsp.Status != nil { - objectMap["status"] = plscsp.Status - } - if plscsp.Description != nil { - objectMap["description"] = plscsp.Description - } - return json.Marshal(objectMap) -} - -// ProxyResource the resource model definition for a Azure Resource Manager proxy resource. It will not -// have tags and a location -type ProxyResource struct { - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ProxyResource. -func (pr ProxyResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ReadOnlyFollowingDatabase class representing a read only following database. -type ReadOnlyFollowingDatabase struct { - // ReadOnlyFollowingDatabaseProperties - The database properties. - *ReadOnlyFollowingDatabaseProperties `json:"properties,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Kind - Possible values include: 'KindDatabase', 'KindReadWrite', 'KindReadOnlyFollowing' - Kind Kind `json:"kind,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ReadOnlyFollowingDatabase. -func (rofd ReadOnlyFollowingDatabase) MarshalJSON() ([]byte, error) { - rofd.Kind = KindReadOnlyFollowing - objectMap := make(map[string]interface{}) - if rofd.ReadOnlyFollowingDatabaseProperties != nil { - objectMap["properties"] = rofd.ReadOnlyFollowingDatabaseProperties - } - if rofd.Location != nil { - objectMap["location"] = rofd.Location - } - if rofd.Kind != "" { - objectMap["kind"] = rofd.Kind - } - return json.Marshal(objectMap) -} - -// AsReadWriteDatabase is the BasicDatabase implementation for ReadOnlyFollowingDatabase. -func (rofd ReadOnlyFollowingDatabase) AsReadWriteDatabase() (*ReadWriteDatabase, bool) { - return nil, false -} - -// AsReadOnlyFollowingDatabase is the BasicDatabase implementation for ReadOnlyFollowingDatabase. -func (rofd ReadOnlyFollowingDatabase) AsReadOnlyFollowingDatabase() (*ReadOnlyFollowingDatabase, bool) { - return &rofd, true -} - -// AsDatabase is the BasicDatabase implementation for ReadOnlyFollowingDatabase. -func (rofd ReadOnlyFollowingDatabase) AsDatabase() (*Database, bool) { - return nil, false -} - -// AsBasicDatabase is the BasicDatabase implementation for ReadOnlyFollowingDatabase. -func (rofd ReadOnlyFollowingDatabase) AsBasicDatabase() (BasicDatabase, bool) { - return &rofd, true -} - -// UnmarshalJSON is the custom unmarshaler for ReadOnlyFollowingDatabase struct. -func (rofd *ReadOnlyFollowingDatabase) 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 readOnlyFollowingDatabaseProperties ReadOnlyFollowingDatabaseProperties - err = json.Unmarshal(*v, &readOnlyFollowingDatabaseProperties) - if err != nil { - return err - } - rofd.ReadOnlyFollowingDatabaseProperties = &readOnlyFollowingDatabaseProperties - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - rofd.Location = &location - } - case "kind": - if v != nil { - var kind Kind - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - rofd.Kind = kind - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rofd.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rofd.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rofd.Type = &typeVar - } - } - } - - return nil -} - -// ReadOnlyFollowingDatabaseProperties class representing the Kusto database properties. -type ReadOnlyFollowingDatabaseProperties struct { - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // SoftDeletePeriod - READ-ONLY; The time the data should be kept before it stops being accessible to queries in TimeSpan. - SoftDeletePeriod *string `json:"softDeletePeriod,omitempty"` - // HotCachePeriod - The time the data should be kept in cache for fast queries in TimeSpan. - HotCachePeriod *string `json:"hotCachePeriod,omitempty"` - // Statistics - The statistics of the database. - Statistics *DatabaseStatistics `json:"statistics,omitempty"` - // LeaderClusterResourceID - READ-ONLY; The name of the leader cluster - LeaderClusterResourceID *string `json:"leaderClusterResourceId,omitempty"` - // AttachedDatabaseConfigurationName - READ-ONLY; The name of the attached database configuration cluster - AttachedDatabaseConfigurationName *string `json:"attachedDatabaseConfigurationName,omitempty"` - // PrincipalsModificationKind - READ-ONLY; The principals modification kind of the database. Possible values include: 'PrincipalsModificationKindUnion', 'PrincipalsModificationKindReplace', 'PrincipalsModificationKindNone' - PrincipalsModificationKind PrincipalsModificationKind `json:"principalsModificationKind,omitempty"` -} - -// MarshalJSON is the custom marshaler for ReadOnlyFollowingDatabaseProperties. -func (rofdp ReadOnlyFollowingDatabaseProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rofdp.HotCachePeriod != nil { - objectMap["hotCachePeriod"] = rofdp.HotCachePeriod - } - if rofdp.Statistics != nil { - objectMap["statistics"] = rofdp.Statistics - } - return json.Marshal(objectMap) -} - -// ReadWriteDatabase class representing a read write database. -type ReadWriteDatabase struct { - // ReadWriteDatabaseProperties - The database properties. - *ReadWriteDatabaseProperties `json:"properties,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Kind - Possible values include: 'KindDatabase', 'KindReadWrite', 'KindReadOnlyFollowing' - Kind Kind `json:"kind,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ReadWriteDatabase. -func (rwd ReadWriteDatabase) MarshalJSON() ([]byte, error) { - rwd.Kind = KindReadWrite - objectMap := make(map[string]interface{}) - if rwd.ReadWriteDatabaseProperties != nil { - objectMap["properties"] = rwd.ReadWriteDatabaseProperties - } - if rwd.Location != nil { - objectMap["location"] = rwd.Location - } - if rwd.Kind != "" { - objectMap["kind"] = rwd.Kind - } - return json.Marshal(objectMap) -} - -// AsReadWriteDatabase is the BasicDatabase implementation for ReadWriteDatabase. -func (rwd ReadWriteDatabase) AsReadWriteDatabase() (*ReadWriteDatabase, bool) { - return &rwd, true -} - -// AsReadOnlyFollowingDatabase is the BasicDatabase implementation for ReadWriteDatabase. -func (rwd ReadWriteDatabase) AsReadOnlyFollowingDatabase() (*ReadOnlyFollowingDatabase, bool) { - return nil, false -} - -// AsDatabase is the BasicDatabase implementation for ReadWriteDatabase. -func (rwd ReadWriteDatabase) AsDatabase() (*Database, bool) { - return nil, false -} - -// AsBasicDatabase is the BasicDatabase implementation for ReadWriteDatabase. -func (rwd ReadWriteDatabase) AsBasicDatabase() (BasicDatabase, bool) { - return &rwd, true -} - -// UnmarshalJSON is the custom unmarshaler for ReadWriteDatabase struct. -func (rwd *ReadWriteDatabase) 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 readWriteDatabaseProperties ReadWriteDatabaseProperties - err = json.Unmarshal(*v, &readWriteDatabaseProperties) - if err != nil { - return err - } - rwd.ReadWriteDatabaseProperties = &readWriteDatabaseProperties - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - rwd.Location = &location - } - case "kind": - if v != nil { - var kind Kind - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - rwd.Kind = kind - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rwd.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rwd.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rwd.Type = &typeVar - } - } - } - - return nil -} - -// ReadWriteDatabaseProperties class representing the Kusto database properties. -type ReadWriteDatabaseProperties struct { - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // SoftDeletePeriod - The time the data should be kept before it stops being accessible to queries in TimeSpan. - SoftDeletePeriod *string `json:"softDeletePeriod,omitempty"` - // HotCachePeriod - The time the data should be kept in cache for fast queries in TimeSpan. - HotCachePeriod *string `json:"hotCachePeriod,omitempty"` - // Statistics - The statistics of the database. - Statistics *DatabaseStatistics `json:"statistics,omitempty"` - // IsFollowed - READ-ONLY; Indicates whether the database is followed. - IsFollowed *bool `json:"isFollowed,omitempty"` -} - -// MarshalJSON is the custom marshaler for ReadWriteDatabaseProperties. -func (rwdp ReadWriteDatabaseProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rwdp.SoftDeletePeriod != nil { - objectMap["softDeletePeriod"] = rwdp.SoftDeletePeriod - } - if rwdp.HotCachePeriod != nil { - objectMap["hotCachePeriod"] = rwdp.HotCachePeriod - } - if rwdp.Statistics != nil { - objectMap["statistics"] = rwdp.Statistics - } - return json.Marshal(objectMap) -} - -// Resource common fields that are returned in the response for all Azure Resource Manager resources -type Resource struct { - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Script class representing a database script. -type Script struct { - autorest.Response `json:"-"` - // ScriptProperties - The database script. - *ScriptProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Script. -func (s Script) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if s.ScriptProperties != nil { - objectMap["properties"] = s.ScriptProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Script struct. -func (s *Script) 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 scriptProperties ScriptProperties - err = json.Unmarshal(*v, &scriptProperties) - if err != nil { - return err - } - s.ScriptProperties = &scriptProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - s.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - s.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - s.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - s.Type = &typeVar - } - } - } - - return nil -} - -// ScriptCheckNameRequest a script name availability request. -type ScriptCheckNameRequest struct { - // Name - Script name. - Name *string `json:"name,omitempty"` - // Type - The type of resource, Microsoft.Kusto/clusters/databases/scripts. - Type *string `json:"type,omitempty"` -} - -// ScriptListResult the list Kusto database script operation response. -type ScriptListResult struct { - autorest.Response `json:"-"` - // Value - The list of Kusto scripts. - Value *[]Script `json:"value,omitempty"` -} - -// ScriptProperties a class representing database script property. -type ScriptProperties struct { - // ScriptURL - The url to the KQL script blob file. - ScriptURL *string `json:"scriptUrl,omitempty"` - // ScriptURLSasToken - The SaS token. - ScriptURLSasToken *string `json:"scriptUrlSasToken,omitempty"` - // ForceUpdateTag - A unique string. If changed the script will be applied again. - ForceUpdateTag *string `json:"forceUpdateTag,omitempty"` - // ContinueOnErrors - Flag that indicates whether to continue if one of the command fails. - ContinueOnErrors *bool `json:"continueOnErrors,omitempty"` - // ProvisioningState - READ-ONLY; The provisioned state of the resource. Possible values include: 'ProvisioningStateRunning', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ScriptProperties. -func (sp ScriptProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sp.ScriptURL != nil { - objectMap["scriptUrl"] = sp.ScriptURL - } - if sp.ScriptURLSasToken != nil { - objectMap["scriptUrlSasToken"] = sp.ScriptURLSasToken - } - if sp.ForceUpdateTag != nil { - objectMap["forceUpdateTag"] = sp.ForceUpdateTag - } - if sp.ContinueOnErrors != nil { - objectMap["continueOnErrors"] = sp.ContinueOnErrors - } - return json.Marshal(objectMap) -} - -// ScriptsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ScriptsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ScriptsClient) (Script, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ScriptsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ScriptsCreateOrUpdateFuture.Result. -func (future *ScriptsCreateOrUpdateFuture) result(client ScriptsClient) (s Script, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ScriptsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.CreateOrUpdateResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsCreateOrUpdateFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// ScriptsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ScriptsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ScriptsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ScriptsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ScriptsDeleteFuture.Result. -func (future *ScriptsDeleteFuture) result(client ScriptsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ScriptsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ScriptsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ScriptsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ScriptsClient) (Script, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ScriptsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ScriptsUpdateFuture.Result. -func (future *ScriptsUpdateFuture) result(client ScriptsClient) (s Script, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("kusto.ScriptsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.UpdateResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsUpdateFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// SkuDescription the Kusto SKU description of given resource type -type SkuDescription struct { - // ResourceType - READ-ONLY; The resource type - ResourceType *string `json:"resourceType,omitempty"` - // Name - READ-ONLY; The name of the SKU - Name *string `json:"name,omitempty"` - // Tier - READ-ONLY; The tier of the SKU - Tier *string `json:"tier,omitempty"` - // Locations - READ-ONLY; The set of locations that the SKU is available - Locations *[]string `json:"locations,omitempty"` - // LocationInfo - READ-ONLY; Locations and zones - LocationInfo *[]SkuLocationInfoItem `json:"locationInfo,omitempty"` - // Restrictions - READ-ONLY; The restrictions because of which SKU cannot be used - Restrictions *[]interface{} `json:"restrictions,omitempty"` -} - -// MarshalJSON is the custom marshaler for SkuDescription. -func (sd SkuDescription) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// SkuDescriptionList the list of the EngagementFabric SKU descriptions -type SkuDescriptionList struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; SKU descriptions - Value *[]SkuDescription `json:"value,omitempty"` -} - -// MarshalJSON is the custom marshaler for SkuDescriptionList. -func (sdl SkuDescriptionList) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// SkuLocationInfoItem the locations and zones info for SKU. -type SkuLocationInfoItem struct { - // Location - The available location of the SKU. - Location *string `json:"location,omitempty"` - // Zones - The available zone of the SKU. - Zones *[]string `json:"zones,omitempty"` -} - -// SystemData metadata pertaining to creation and last modification of the resource. -type SystemData struct { - // CreatedBy - The identity that created the resource. - CreatedBy *string `json:"createdBy,omitempty"` - // CreatedByType - The type of identity that created the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' - CreatedByType CreatedByType `json:"createdByType,omitempty"` - // CreatedAt - The timestamp of resource creation (UTC). - CreatedAt *date.Time `json:"createdAt,omitempty"` - // LastModifiedBy - The identity that last modified the resource. - LastModifiedBy *string `json:"lastModifiedBy,omitempty"` - // LastModifiedByType - The type of identity that last modified the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' - LastModifiedByType CreatedByType `json:"lastModifiedByType,omitempty"` - // LastModifiedAt - The timestamp of resource last modification (UTC) - LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` -} - -// TableLevelSharingProperties tables that will be included and excluded in the follower database -type TableLevelSharingProperties struct { - // TablesToInclude - List of tables to include in the follower database - TablesToInclude *[]string `json:"tablesToInclude,omitempty"` - // TablesToExclude - List of tables to exclude from the follower database - TablesToExclude *[]string `json:"tablesToExclude,omitempty"` - // ExternalTablesToInclude - List of external tables to include in the follower database - ExternalTablesToInclude *[]string `json:"externalTablesToInclude,omitempty"` - // ExternalTablesToExclude - List of external tables exclude from the follower database - ExternalTablesToExclude *[]string `json:"externalTablesToExclude,omitempty"` - // MaterializedViewsToInclude - List of materialized views to include in the follower database - MaterializedViewsToInclude *[]string `json:"materializedViewsToInclude,omitempty"` - // MaterializedViewsToExclude - List of materialized views exclude from the follower database - MaterializedViewsToExclude *[]string `json:"materializedViewsToExclude,omitempty"` -} - -// TrackedResource the resource model definition for an Azure Resource Manager tracked top level resource -// which has 'tags' and a 'location' -type TrackedResource struct { - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` - // Location - The geo-location where the resource lives - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - 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.Tags != nil { - objectMap["tags"] = tr.Tags - } - if tr.Location != nil { - objectMap["location"] = tr.Location - } - return json.Marshal(objectMap) -} - -// TrustedExternalTenant represents a tenant ID that is trusted by the cluster. -type TrustedExternalTenant struct { - // Value - GUID representing an external tenant. - Value *string `json:"value,omitempty"` -} - -// VirtualNetworkConfiguration a class that contains virtual network definition. -type VirtualNetworkConfiguration struct { - // SubnetID - The subnet resource id. - SubnetID *string `json:"subnetId,omitempty"` - // EnginePublicIPID - Engine service's public IP address resource id. - EnginePublicIPID *string `json:"enginePublicIpId,omitempty"` - // DataManagementPublicIPID - Data management's service public IP address resource id. - DataManagementPublicIPID *string `json:"dataManagementPublicIpId,omitempty"` -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/operations.go deleted file mode 100644 index e174a83bd3c3..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/operations.go +++ /dev/null @@ -1,142 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// OperationsClient is the the Azure Kusto management API provides a RESTful set of web services that interact with -// Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete -// clusters and databases. -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 using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List lists available operations for the Microsoft.Kusto provider. -func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.olr.Response.Response != nil { - sc = result.olr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.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, "kusto.OperationsClient", "List", resp, "Failure sending request") - return - } - - result.olr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.OperationsClient", "List", resp, "Failure responding to request") - return - } - if result.olr.hasNextLink() && result.olr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.Kusto/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 client.Send(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, - 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(ctx context.Context, lastResults OperationListResult) (result OperationListResult, err error) { - req, err := lastResults.operationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "kusto.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, "kusto.OperationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/operationsresults.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/operationsresults.go deleted file mode 100644 index 3e472a315aeb..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/operationsresults.go +++ /dev/null @@ -1,110 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// OperationsResultsClient is the the Azure Kusto management API provides a RESTful set of web services that interact -// with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete -// clusters and databases. -type OperationsResultsClient struct { - BaseClient -} - -// NewOperationsResultsClient creates an instance of the OperationsResultsClient client. -func NewOperationsResultsClient(subscriptionID string) OperationsResultsClient { - return NewOperationsResultsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewOperationsResultsClientWithBaseURI creates an instance of the OperationsResultsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewOperationsResultsClientWithBaseURI(baseURI string, subscriptionID string) OperationsResultsClient { - return OperationsResultsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get returns operation results. -// Parameters: -// location - azure location (region) name. -// operationID - the Guid of the operation ID -func (client OperationsResultsClient) Get(ctx context.Context, location string, operationID string) (result OperationResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsResultsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, location, operationID) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.OperationsResultsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.OperationsResultsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.OperationsResultsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client OperationsResultsClient) GetPreparer(ctx context.Context, location string, operationID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "operationId": autorest.Encode("path", operationID), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Kusto/locations/{location}/operationresults/{operationId}", 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 OperationsResultsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client OperationsResultsClient) GetResponder(resp *http.Response) (result OperationResult, err error) { - err = autorest.Respond( - resp, - 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/kusto/mgmt/2021-08-27/kusto/privateendpointconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/privateendpointconnections.go deleted file mode 100644 index ac2d90ac6271..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/privateendpointconnections.go +++ /dev/null @@ -1,360 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PrivateEndpointConnectionsClient is the the Azure Kusto management API provides a RESTful set of web services that -// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and -// delete clusters and databases. -type PrivateEndpointConnectionsClient struct { - BaseClient -} - -// NewPrivateEndpointConnectionsClient creates an instance of the PrivateEndpointConnectionsClient client. -func NewPrivateEndpointConnectionsClient(subscriptionID string) PrivateEndpointConnectionsClient { - return NewPrivateEndpointConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPrivateEndpointConnectionsClientWithBaseURI creates an instance of the PrivateEndpointConnectionsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewPrivateEndpointConnectionsClientWithBaseURI(baseURI string, subscriptionID string) PrivateEndpointConnectionsClient { - return PrivateEndpointConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate approve or reject a private endpoint connection with a given name. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// privateEndpointConnectionName - the name of the private endpoint connection. -func (client PrivateEndpointConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string, parameters PrivateEndpointConnection) (result PrivateEndpointConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.PrivateEndpointConnectionProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PrivateEndpointConnectionProperties.PrivateLinkServiceConnectionState", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewError("kusto.PrivateEndpointConnectionsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, privateEndpointConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PrivateEndpointConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string, parameters PrivateEndpointConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) CreateOrUpdateSender(req *http.Request) (future PrivateEndpointConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PrivateEndpointConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a private endpoint connection with a given name. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// privateEndpointConnectionName - the name of the private endpoint connection. -func (client PrivateEndpointConnectionsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string) (result PrivateEndpointConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, privateEndpointConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PrivateEndpointConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) DeleteSender(req *http.Request) (future PrivateEndpointConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PrivateEndpointConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a private endpoint connection. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// privateEndpointConnectionName - the name of the private endpoint connection. -func (client PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string) (result PrivateEndpointConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, privateEndpointConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PrivateEndpointConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PrivateEndpointConnectionsClient) GetResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List returns the list of private endpoint connections. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client PrivateEndpointConnectionsClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result PrivateEndpointConnectionListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateEndpointConnectionsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PrivateEndpointConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/privateEndpointConnections", 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 PrivateEndpointConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PrivateEndpointConnectionsClient) ListResponder(resp *http.Response) (result PrivateEndpointConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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/kusto/mgmt/2021-08-27/kusto/privatelinkresources.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/privatelinkresources.go deleted file mode 100644 index 887b2a4205ae..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/privatelinkresources.go +++ /dev/null @@ -1,188 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// PrivateLinkResourcesClient is the the Azure Kusto management API provides a RESTful set of web services that -// interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and -// delete clusters and databases. -type PrivateLinkResourcesClient struct { - BaseClient -} - -// NewPrivateLinkResourcesClient creates an instance of the PrivateLinkResourcesClient client. -func NewPrivateLinkResourcesClient(subscriptionID string) PrivateLinkResourcesClient { - return NewPrivateLinkResourcesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPrivateLinkResourcesClientWithBaseURI creates an instance of the PrivateLinkResourcesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewPrivateLinkResourcesClientWithBaseURI(baseURI string, subscriptionID string) PrivateLinkResourcesClient { - return PrivateLinkResourcesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets a private link resource. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// privateLinkResourceName - the name of the private link resource. -func (client PrivateLinkResourcesClient) Get(ctx context.Context, resourceGroupName string, clusterName string, privateLinkResourceName string) (result PrivateLinkResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, privateLinkResourceName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PrivateLinkResourcesClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, privateLinkResourceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "privateLinkResourceName": autorest.Encode("path", privateLinkResourceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/privateLinkResources/{privateLinkResourceName}", 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 PrivateLinkResourcesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PrivateLinkResourcesClient) GetResponder(resp *http.Response) (result PrivateLinkResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List returns the list of private link resources. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -func (client PrivateLinkResourcesClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result PrivateLinkResourceListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.PrivateLinkResourcesClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PrivateLinkResourcesClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/privateLinkResources", 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 PrivateLinkResourcesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PrivateLinkResourcesClient) ListResponder(resp *http.Response) (result PrivateLinkResourceListResult, err error) { - err = autorest.Respond( - resp, - 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/kusto/mgmt/2021-08-27/kusto/scripts.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/scripts.go deleted file mode 100644 index 81d3ef9e314c..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/scripts.go +++ /dev/null @@ -1,545 +0,0 @@ -package kusto - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ScriptsClient is the the Azure Kusto management API provides a RESTful set of web services that interact with Azure -// Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and -// databases. -type ScriptsClient struct { - BaseClient -} - -// NewScriptsClient creates an instance of the ScriptsClient client. -func NewScriptsClient(subscriptionID string) ScriptsClient { - return NewScriptsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewScriptsClientWithBaseURI creates an instance of the ScriptsClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewScriptsClientWithBaseURI(baseURI string, subscriptionID string) ScriptsClient { - return ScriptsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckNameAvailability checks that the script name is valid and is not already in use. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// scriptName - the name of the script. -func (client ScriptsClient) CheckNameAvailability(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName ScriptCheckNameRequest) (result CheckNameResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: scriptName, - Constraints: []validation.Constraint{{Target: "scriptName.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "scriptName.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("kusto.ScriptsClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client ScriptsClient) CheckNameAvailabilityPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName ScriptCheckNameRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - 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.Kusto/clusters/{clusterName}/databases/{databaseName}/scriptsCheckNameAvailability", pathParameters), - autorest.WithJSON(scriptName), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client ScriptsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client ScriptsClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates a Kusto database script. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// scriptName - the name of the Kusto database script. -// parameters - the Kusto Script parameters contains the KQL to run. -func (client ScriptsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string, parameters Script) (result ScriptsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ScriptProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ScriptProperties.ScriptURL", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ScriptProperties.ScriptURLSasToken", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("kusto.ScriptsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ScriptsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string, parameters Script) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "scriptName": autorest.Encode("path", scriptName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts/{scriptName}", 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 ScriptsClient) CreateOrUpdateSender(req *http.Request) (future ScriptsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ScriptsClient) CreateOrUpdateResponder(resp *http.Response) (result Script, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a Kusto principalAssignment. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// scriptName - the name of the Kusto database script. -func (client ScriptsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string) (result ScriptsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ScriptsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "scriptName": autorest.Encode("path", scriptName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts/{scriptName}", 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 ScriptsClient) DeleteSender(req *http.Request) (future ScriptsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ScriptsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a Kusto cluster database script. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// scriptName - the name of the Kusto database script. -func (client ScriptsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string) (result Script, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ScriptsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "scriptName": autorest.Encode("path", scriptName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts/{scriptName}", 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 ScriptsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ScriptsClient) GetResponder(resp *http.Response) (result Script, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByDatabase returns the list of database scripts for given database. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -func (client ScriptsClient) ListByDatabase(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (result ScriptListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.ListByDatabase") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, clusterName, databaseName) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "ListByDatabase", nil, "Failure preparing request") - return - } - - resp, err := client.ListByDatabaseSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "ListByDatabase", resp, "Failure sending request") - return - } - - result, err = client.ListByDatabaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "ListByDatabase", resp, "Failure responding to request") - return - } - - return -} - -// ListByDatabasePreparer prepares the ListByDatabase request. -func (client ScriptsClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByDatabaseSender sends the ListByDatabase request. The method will close the -// http.Response Body if it receives an error. -func (client ScriptsClient) ListByDatabaseSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByDatabaseResponder handles the response to the ListByDatabase request. The method always -// closes the http.Response Body. -func (client ScriptsClient) ListByDatabaseResponder(resp *http.Response) (result ScriptListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Update updates a database script. -// Parameters: -// resourceGroupName - the name of the resource group containing the Kusto cluster. -// clusterName - the name of the Kusto cluster. -// databaseName - the name of the database in the Kusto cluster. -// scriptName - the name of the Kusto database script. -// parameters - the Kusto Script parameters contains to the KQL to run. -func (client ScriptsClient) Update(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string, parameters Script) (result ScriptsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScriptsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, databaseName, scriptName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "kusto.ScriptsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ScriptsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, databaseName string, scriptName string, parameters Script) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "clusterName": autorest.Encode("path", clusterName), - "databaseName": autorest.Encode("path", databaseName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "scriptName": autorest.Encode("path", scriptName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-08-27" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/scripts/{scriptName}", 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 ScriptsClient) UpdateSender(req *http.Request) (future ScriptsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ScriptsClient) UpdateResponder(resp *http.Response) (result Script, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/kusto/mgmt/2021-08-27/kusto/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/version.go deleted file mode 100644 index cd02dad786e9..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/kusto/mgmt/2021-08-27/kusto/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package kusto - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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() + " kusto/2021-08-27" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/CHANGELOG.md deleted file mode 100644 index 52911e4cc5e4..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/_meta.json deleted file mode 100644 index 58571b36d636..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "3c764635e7d442b3e74caf593029fcd440b3ef82", - "readme": "/_/azure-rest-api-specs/specification/managedservices/resource-manager/readme.md", - "tag": "package-2019-06", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-2019-06 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION /_/azure-rest-api-specs/specification/managedservices/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/client.go deleted file mode 100644 index 377df1ada7a9..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/client.go +++ /dev/null @@ -1,39 +0,0 @@ -// Package managedservices implements the Azure ARM Managedservices service API version 2019-06-01. -// -// Specification for ManagedServices. -package managedservices - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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 Managedservices - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Managedservices. -type BaseClient struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the BaseClient client. -func New() BaseClient { - return NewWithBaseURI(DefaultBaseURI) -} - -// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewWithBaseURI(baseURI string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - } -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/enums.go deleted file mode 100644 index 4626725b551b..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/enums.go +++ /dev/null @@ -1,42 +0,0 @@ -package managedservices - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// ProvisioningState enumerates the values for provisioning state. -type ProvisioningState string - -const ( - // Accepted ... - Accepted ProvisioningState = "Accepted" - // Canceled ... - Canceled ProvisioningState = "Canceled" - // Created ... - Created ProvisioningState = "Created" - // Creating ... - Creating ProvisioningState = "Creating" - // Deleted ... - Deleted ProvisioningState = "Deleted" - // Deleting ... - Deleting ProvisioningState = "Deleting" - // Failed ... - Failed ProvisioningState = "Failed" - // NotSpecified ... - NotSpecified ProvisioningState = "NotSpecified" - // Ready ... - Ready ProvisioningState = "Ready" - // Running ... - Running ProvisioningState = "Running" - // Succeeded ... - Succeeded ProvisioningState = "Succeeded" - // Updating ... - Updating ProvisioningState = "Updating" -) - -// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. -func PossibleProvisioningStateValues() []ProvisioningState { - return []ProvisioningState{Accepted, Canceled, Created, Creating, Deleted, Deleting, Failed, NotSpecified, Ready, Running, Succeeded, Updating} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/models.go deleted file mode 100644 index b7aa52dcdd67..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/models.go +++ /dev/null @@ -1,707 +0,0 @@ -package managedservices - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/to" - "github.com/Azure/go-autorest/tracing" - "github.com/gofrs/uuid" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices" - -// Authorization authorization tuple containing principal Id (of user/service principal/security group) and -// role definition id. -type Authorization struct { - // PrincipalID - Principal Id of the security group/service principal/user that would be assigned permissions to the projected subscription - PrincipalID *string `json:"principalId,omitempty"` - // PrincipalIDDisplayName - Display name of the principal Id. - PrincipalIDDisplayName *string `json:"principalIdDisplayName,omitempty"` - // RoleDefinitionID - The role definition identifier. This role will define all the permissions that the security group/service principal/user must have on the projected subscription. This role cannot be an owner role. - RoleDefinitionID *string `json:"roleDefinitionId,omitempty"` - // DelegatedRoleDefinitionIds - The delegatedRoleDefinitionIds field is required when the roleDefinitionId refers to the User Access Administrator Role. It is the list of role definition ids which define all the permissions that the user in the authorization can assign to other security groups/service principals/users. - DelegatedRoleDefinitionIds *[]uuid.UUID `json:"delegatedRoleDefinitionIds,omitempty"` -} - -// ErrorDefinition error response indicates Azure Resource Manager is not able to process the incoming -// request. The reason is provided in the error message. -type ErrorDefinition struct { - // Code - Error code. - Code *string `json:"code,omitempty"` - // Message - Error message indicating why the operation failed. - Message *string `json:"message,omitempty"` - // Details - Internal error details. - Details *[]ErrorDefinition `json:"details,omitempty"` -} - -// ErrorResponse error response. -type ErrorResponse struct { - // Error - The error details. - Error *ErrorDefinition `json:"error,omitempty"` -} - -// Operation object that describes a single Microsoft.ManagedServices operation. -type Operation struct { - // Name - READ-ONLY; Operation name: {provider}/{resource}/{operation} - Name *string `json:"name,omitempty"` - // Display - READ-ONLY; The object that represents the operation. - Display *OperationDisplay `json:"display,omitempty"` -} - -// MarshalJSON is the custom marshaler for Operation. -func (o Operation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// OperationDisplay the object that represents the operation. -type OperationDisplay struct { - // Provider - Service provider: Microsoft.ManagedServices - Provider *string `json:"provider,omitempty"` - // Resource - Resource on which the operation is performed: Registration definition, registration assignment etc. - Resource *string `json:"resource,omitempty"` - // Operation - Operation type: Read, write, delete, etc. - Operation *string `json:"operation,omitempty"` - // Description - Description of the operation. - Description *string `json:"description,omitempty"` -} - -// OperationList list of the operations. -type OperationList struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; List of Microsoft.ManagedServices operations. - Value *[]Operation `json:"value,omitempty"` -} - -// MarshalJSON is the custom marshaler for OperationList. -func (ol OperationList) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Plan plan details for the managed services. -type Plan struct { - // Name - The plan name. - Name *string `json:"name,omitempty"` - // Publisher - The publisher ID. - Publisher *string `json:"publisher,omitempty"` - // Product - The product code. - Product *string `json:"product,omitempty"` - // Version - The plan's version. - Version *string `json:"version,omitempty"` -} - -// RegistrationAssignment registration assignment. -type RegistrationAssignment struct { - autorest.Response `json:"-"` - // Properties - Properties of a registration assignment. - Properties *RegistrationAssignmentProperties `json:"properties,omitempty"` - // ID - READ-ONLY; The fully qualified path of the registration assignment. - ID *string `json:"id,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // Name - READ-ONLY; Name of the registration assignment. - Name *string `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for RegistrationAssignment. -func (ra RegistrationAssignment) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ra.Properties != nil { - objectMap["properties"] = ra.Properties - } - return json.Marshal(objectMap) -} - -// RegistrationAssignmentList list of registration assignments. -type RegistrationAssignmentList struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; List of registration assignments. - Value *[]RegistrationAssignment `json:"value,omitempty"` - // NextLink - READ-ONLY; Link to next page of registration assignments. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for RegistrationAssignmentList. -func (ral RegistrationAssignmentList) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RegistrationAssignmentListIterator provides access to a complete listing of RegistrationAssignment -// values. -type RegistrationAssignmentListIterator struct { - i int - page RegistrationAssignmentListPage -} - -// NextWithContext 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 *RegistrationAssignmentListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationAssignmentListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RegistrationAssignmentListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RegistrationAssignmentListIterator) 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 RegistrationAssignmentListIterator) Response() RegistrationAssignmentList { - 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 RegistrationAssignmentListIterator) Value() RegistrationAssignment { - if !iter.page.NotDone() { - return RegistrationAssignment{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RegistrationAssignmentListIterator type. -func NewRegistrationAssignmentListIterator(page RegistrationAssignmentListPage) RegistrationAssignmentListIterator { - return RegistrationAssignmentListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ral RegistrationAssignmentList) IsEmpty() bool { - return ral.Value == nil || len(*ral.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ral RegistrationAssignmentList) hasNextLink() bool { - return ral.NextLink != nil && len(*ral.NextLink) != 0 -} - -// registrationAssignmentListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ral RegistrationAssignmentList) registrationAssignmentListPreparer(ctx context.Context) (*http.Request, error) { - if !ral.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ral.NextLink))) -} - -// RegistrationAssignmentListPage contains a page of RegistrationAssignment values. -type RegistrationAssignmentListPage struct { - fn func(context.Context, RegistrationAssignmentList) (RegistrationAssignmentList, error) - ral RegistrationAssignmentList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RegistrationAssignmentListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationAssignmentListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ral) - if err != nil { - return err - } - page.ral = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RegistrationAssignmentListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RegistrationAssignmentListPage) NotDone() bool { - return !page.ral.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RegistrationAssignmentListPage) Response() RegistrationAssignmentList { - return page.ral -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RegistrationAssignmentListPage) Values() []RegistrationAssignment { - if page.ral.IsEmpty() { - return nil - } - return *page.ral.Value -} - -// Creates a new instance of the RegistrationAssignmentListPage type. -func NewRegistrationAssignmentListPage(cur RegistrationAssignmentList, getNextPage func(context.Context, RegistrationAssignmentList) (RegistrationAssignmentList, error)) RegistrationAssignmentListPage { - return RegistrationAssignmentListPage{ - fn: getNextPage, - ral: cur, - } -} - -// RegistrationAssignmentProperties properties of a registration assignment. -type RegistrationAssignmentProperties struct { - // RegistrationDefinitionID - Fully qualified path of the registration definition. - RegistrationDefinitionID *string `json:"registrationDefinitionId,omitempty"` - // ProvisioningState - READ-ONLY; Current state of the registration assignment. Possible values include: 'NotSpecified', 'Accepted', 'Running', 'Ready', 'Creating', 'Created', 'Deleting', 'Deleted', 'Canceled', 'Failed', 'Succeeded', 'Updating' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // RegistrationDefinition - READ-ONLY; Registration definition inside registration assignment. - RegistrationDefinition *RegistrationAssignmentPropertiesRegistrationDefinition `json:"registrationDefinition,omitempty"` -} - -// MarshalJSON is the custom marshaler for RegistrationAssignmentProperties. -func (rap RegistrationAssignmentProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rap.RegistrationDefinitionID != nil { - objectMap["registrationDefinitionId"] = rap.RegistrationDefinitionID - } - return json.Marshal(objectMap) -} - -// RegistrationAssignmentPropertiesRegistrationDefinition registration definition inside registration -// assignment. -type RegistrationAssignmentPropertiesRegistrationDefinition struct { - // Properties - Properties of registration definition inside registration assignment. - Properties *RegistrationAssignmentPropertiesRegistrationDefinitionProperties `json:"properties,omitempty"` - // Plan - Plan details for the managed services. - Plan *Plan `json:"plan,omitempty"` - // ID - READ-ONLY; Fully qualified path of the registration definition. - ID *string `json:"id,omitempty"` - // Type - READ-ONLY; Type of the resource (Microsoft.ManagedServices/registrationDefinitions). - Type *string `json:"type,omitempty"` - // Name - READ-ONLY; Name of the registration definition. - Name *string `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for RegistrationAssignmentPropertiesRegistrationDefinition. -func (rapD RegistrationAssignmentPropertiesRegistrationDefinition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rapD.Properties != nil { - objectMap["properties"] = rapD.Properties - } - if rapD.Plan != nil { - objectMap["plan"] = rapD.Plan - } - return json.Marshal(objectMap) -} - -// RegistrationAssignmentPropertiesRegistrationDefinitionProperties properties of registration definition -// inside registration assignment. -type RegistrationAssignmentPropertiesRegistrationDefinitionProperties struct { - // Description - Description of the registration definition. - Description *string `json:"description,omitempty"` - // Authorizations - Authorization tuple containing principal id of the user/security group or service principal and id of the build-in role. - Authorizations *[]Authorization `json:"authorizations,omitempty"` - // RegistrationDefinitionName - Name of the registration definition. - RegistrationDefinitionName *string `json:"registrationDefinitionName,omitempty"` - // ProvisioningState - Current state of the registration definition. Possible values include: 'NotSpecified', 'Accepted', 'Running', 'Ready', 'Creating', 'Created', 'Deleting', 'Deleted', 'Canceled', 'Failed', 'Succeeded', 'Updating' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ManageeTenantID - Id of the home tenant. - ManageeTenantID *string `json:"manageeTenantId,omitempty"` - // ManageeTenantName - Name of the home tenant. - ManageeTenantName *string `json:"manageeTenantName,omitempty"` - // ManagedByTenantID - Id of the managedBy tenant. - ManagedByTenantID *string `json:"managedByTenantId,omitempty"` - // ManagedByTenantName - Name of the managedBy tenant. - ManagedByTenantName *string `json:"managedByTenantName,omitempty"` -} - -// RegistrationAssignmentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type RegistrationAssignmentsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RegistrationAssignmentsClient) (RegistrationAssignment, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RegistrationAssignmentsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RegistrationAssignmentsCreateOrUpdateFuture.Result. -func (future *RegistrationAssignmentsCreateOrUpdateFuture) result(client RegistrationAssignmentsClient) (ra RegistrationAssignment, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ra.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("managedservices.RegistrationAssignmentsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ra.Response.Response, err = future.GetResult(sender); err == nil && ra.Response.Response.StatusCode != http.StatusNoContent { - ra, err = client.CreateOrUpdateResponder(ra.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsCreateOrUpdateFuture", "Result", ra.Response.Response, "Failure responding to request") - } - } - return -} - -// RegistrationAssignmentsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type RegistrationAssignmentsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RegistrationAssignmentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RegistrationAssignmentsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RegistrationAssignmentsDeleteFuture.Result. -func (future *RegistrationAssignmentsDeleteFuture) result(client RegistrationAssignmentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("managedservices.RegistrationAssignmentsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RegistrationDefinition registration definition. -type RegistrationDefinition struct { - autorest.Response `json:"-"` - // Properties - Properties of a registration definition. - Properties *RegistrationDefinitionProperties `json:"properties,omitempty"` - // Plan - Plan details for the managed services. - Plan *Plan `json:"plan,omitempty"` - // ID - READ-ONLY; Fully qualified path of the registration definition. - ID *string `json:"id,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // Name - READ-ONLY; Name of the registration definition. - Name *string `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for RegistrationDefinition. -func (rd RegistrationDefinition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rd.Properties != nil { - objectMap["properties"] = rd.Properties - } - if rd.Plan != nil { - objectMap["plan"] = rd.Plan - } - return json.Marshal(objectMap) -} - -// RegistrationDefinitionList list of registration definitions. -type RegistrationDefinitionList struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; List of registration definitions. - Value *[]RegistrationDefinition `json:"value,omitempty"` - // NextLink - READ-ONLY; Link to next page of registration definitions. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for RegistrationDefinitionList. -func (rdl RegistrationDefinitionList) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RegistrationDefinitionListIterator provides access to a complete listing of RegistrationDefinition -// values. -type RegistrationDefinitionListIterator struct { - i int - page RegistrationDefinitionListPage -} - -// NextWithContext 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 *RegistrationDefinitionListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationDefinitionListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RegistrationDefinitionListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RegistrationDefinitionListIterator) 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 RegistrationDefinitionListIterator) Response() RegistrationDefinitionList { - 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 RegistrationDefinitionListIterator) Value() RegistrationDefinition { - if !iter.page.NotDone() { - return RegistrationDefinition{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RegistrationDefinitionListIterator type. -func NewRegistrationDefinitionListIterator(page RegistrationDefinitionListPage) RegistrationDefinitionListIterator { - return RegistrationDefinitionListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rdl RegistrationDefinitionList) IsEmpty() bool { - return rdl.Value == nil || len(*rdl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rdl RegistrationDefinitionList) hasNextLink() bool { - return rdl.NextLink != nil && len(*rdl.NextLink) != 0 -} - -// registrationDefinitionListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rdl RegistrationDefinitionList) registrationDefinitionListPreparer(ctx context.Context) (*http.Request, error) { - if !rdl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rdl.NextLink))) -} - -// RegistrationDefinitionListPage contains a page of RegistrationDefinition values. -type RegistrationDefinitionListPage struct { - fn func(context.Context, RegistrationDefinitionList) (RegistrationDefinitionList, error) - rdl RegistrationDefinitionList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RegistrationDefinitionListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationDefinitionListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rdl) - if err != nil { - return err - } - page.rdl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RegistrationDefinitionListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RegistrationDefinitionListPage) NotDone() bool { - return !page.rdl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RegistrationDefinitionListPage) Response() RegistrationDefinitionList { - return page.rdl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RegistrationDefinitionListPage) Values() []RegistrationDefinition { - if page.rdl.IsEmpty() { - return nil - } - return *page.rdl.Value -} - -// Creates a new instance of the RegistrationDefinitionListPage type. -func NewRegistrationDefinitionListPage(cur RegistrationDefinitionList, getNextPage func(context.Context, RegistrationDefinitionList) (RegistrationDefinitionList, error)) RegistrationDefinitionListPage { - return RegistrationDefinitionListPage{ - fn: getNextPage, - rdl: cur, - } -} - -// RegistrationDefinitionProperties properties of a registration definition. -type RegistrationDefinitionProperties struct { - // Description - Description of the registration definition. - Description *string `json:"description,omitempty"` - // Authorizations - Authorization tuple containing principal id of the user/security group or service principal and id of the build-in role. - Authorizations *[]Authorization `json:"authorizations,omitempty"` - // RegistrationDefinitionName - Name of the registration definition. - RegistrationDefinitionName *string `json:"registrationDefinitionName,omitempty"` - // ManagedByTenantID - Id of the managedBy tenant. - ManagedByTenantID *string `json:"managedByTenantId,omitempty"` - // ProvisioningState - READ-ONLY; Current state of the registration definition. Possible values include: 'NotSpecified', 'Accepted', 'Running', 'Ready', 'Creating', 'Created', 'Deleting', 'Deleted', 'Canceled', 'Failed', 'Succeeded', 'Updating' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ManagedByTenantName - READ-ONLY; Name of the managedBy tenant. - ManagedByTenantName *string `json:"managedByTenantName,omitempty"` -} - -// MarshalJSON is the custom marshaler for RegistrationDefinitionProperties. -func (rdp RegistrationDefinitionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rdp.Description != nil { - objectMap["description"] = rdp.Description - } - if rdp.Authorizations != nil { - objectMap["authorizations"] = rdp.Authorizations - } - if rdp.RegistrationDefinitionName != nil { - objectMap["registrationDefinitionName"] = rdp.RegistrationDefinitionName - } - if rdp.ManagedByTenantID != nil { - objectMap["managedByTenantId"] = rdp.ManagedByTenantID - } - return json.Marshal(objectMap) -} - -// RegistrationDefinitionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type RegistrationDefinitionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RegistrationDefinitionsClient) (RegistrationDefinition, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RegistrationDefinitionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RegistrationDefinitionsCreateOrUpdateFuture.Result. -func (future *RegistrationDefinitionsCreateOrUpdateFuture) result(client RegistrationDefinitionsClient) (rd RegistrationDefinition, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rd.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("managedservices.RegistrationDefinitionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rd.Response.Response, err = future.GetResult(sender); err == nil && rd.Response.Response.StatusCode != http.StatusNoContent { - rd, err = client.CreateOrUpdateResponder(rd.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsCreateOrUpdateFuture", "Result", rd.Response.Response, "Failure responding to request") - } - } - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/operations.go deleted file mode 100644 index 3a2a2593b96b..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/operations.go +++ /dev/null @@ -1,98 +0,0 @@ -package managedservices - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// OperationsClient is the specification for ManagedServices. -type OperationsClient struct { - BaseClient -} - -// NewOperationsClient creates an instance of the OperationsClient client. -func NewOperationsClient() OperationsClient { - return NewOperationsClientWithBaseURI(DefaultBaseURI) -} - -// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI)} -} - -// List gets a list of the operations. -func (client OperationsClient) List(ctx context.Context) (result OperationList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.OperationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "managedservices.OperationsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.OperationsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2019-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.ManagedServices/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 client.Send(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 OperationList, err error) { - err = autorest.Respond( - resp, - 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/managedservices/mgmt/2019-06-01/managedservices/registrationassignments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/registrationassignments.go deleted file mode 100644 index 008e6ef7bf68..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/registrationassignments.go +++ /dev/null @@ -1,410 +0,0 @@ -package managedservices - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RegistrationAssignmentsClient is the specification for ManagedServices. -type RegistrationAssignmentsClient struct { - BaseClient -} - -// NewRegistrationAssignmentsClient creates an instance of the RegistrationAssignmentsClient client. -func NewRegistrationAssignmentsClient() RegistrationAssignmentsClient { - return NewRegistrationAssignmentsClientWithBaseURI(DefaultBaseURI) -} - -// NewRegistrationAssignmentsClientWithBaseURI creates an instance of the RegistrationAssignmentsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewRegistrationAssignmentsClientWithBaseURI(baseURI string) RegistrationAssignmentsClient { - return RegistrationAssignmentsClient{NewWithBaseURI(baseURI)} -} - -// CreateOrUpdate creates or updates a registration assignment. -// Parameters: -// scope - scope of the resource. -// registrationAssignmentID - guid of the registration assignment. -// requestBody - the parameters required to create new registration assignment. -func (client RegistrationAssignmentsClient) CreateOrUpdate(ctx context.Context, scope string, registrationAssignmentID string, requestBody RegistrationAssignment) (result RegistrationAssignmentsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationAssignmentsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: requestBody, - Constraints: []validation.Constraint{{Target: "requestBody.Properties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "requestBody.Properties.RegistrationDefinitionID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "requestBody.Properties.RegistrationDefinition", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "requestBody.Properties.RegistrationDefinition.Plan", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "requestBody.Properties.RegistrationDefinition.Plan.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "requestBody.Properties.RegistrationDefinition.Plan.Publisher", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "requestBody.Properties.RegistrationDefinition.Plan.Product", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "requestBody.Properties.RegistrationDefinition.Plan.Version", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("managedservices.RegistrationAssignmentsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, scope, registrationAssignmentID, requestBody) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RegistrationAssignmentsClient) CreateOrUpdatePreparer(ctx context.Context, scope string, registrationAssignmentID string, requestBody RegistrationAssignment) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "registrationAssignmentId": autorest.Encode("path", registrationAssignmentID), - "scope": scope, - } - - const APIVersion = "2019-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - requestBody.ID = nil - requestBody.Type = nil - requestBody.Name = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.ManagedServices/registrationAssignments/{registrationAssignmentId}", pathParameters), - autorest.WithJSON(requestBody), - 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 RegistrationAssignmentsClient) CreateOrUpdateSender(req *http.Request) (future RegistrationAssignmentsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RegistrationAssignmentsClient) CreateOrUpdateResponder(resp *http.Response) (result RegistrationAssignment, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified registration assignment. -// Parameters: -// scope - scope of the resource. -// registrationAssignmentID - guid of the registration assignment. -func (client RegistrationAssignmentsClient) Delete(ctx context.Context, scope string, registrationAssignmentID string) (result RegistrationAssignmentsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationAssignmentsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, scope, registrationAssignmentID) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RegistrationAssignmentsClient) DeletePreparer(ctx context.Context, scope string, registrationAssignmentID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "registrationAssignmentId": autorest.Encode("path", registrationAssignmentID), - "scope": scope, - } - - const APIVersion = "2019-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.ManagedServices/registrationAssignments/{registrationAssignmentId}", 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 RegistrationAssignmentsClient) DeleteSender(req *http.Request) (future RegistrationAssignmentsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RegistrationAssignmentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the details of specified registration assignment. -// Parameters: -// scope - scope of the resource. -// registrationAssignmentID - guid of the registration assignment. -// expandRegistrationDefinition - tells whether to return registration definition details also along with -// registration assignment details. -func (client RegistrationAssignmentsClient) Get(ctx context.Context, scope string, registrationAssignmentID string, expandRegistrationDefinition *bool) (result RegistrationAssignment, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationAssignmentsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, scope, registrationAssignmentID, expandRegistrationDefinition) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RegistrationAssignmentsClient) GetPreparer(ctx context.Context, scope string, registrationAssignmentID string, expandRegistrationDefinition *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "registrationAssignmentId": autorest.Encode("path", registrationAssignmentID), - "scope": scope, - } - - const APIVersion = "2019-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if expandRegistrationDefinition != nil { - queryParameters["$expandRegistrationDefinition"] = autorest.Encode("query", *expandRegistrationDefinition) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.ManagedServices/registrationAssignments/{registrationAssignmentId}", 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 RegistrationAssignmentsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RegistrationAssignmentsClient) GetResponder(resp *http.Response) (result RegistrationAssignment, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets a list of the registration assignments. -// Parameters: -// scope - scope of the resource. -// expandRegistrationDefinition - tells whether to return registration definition details also along with -// registration assignment details. -func (client RegistrationAssignmentsClient) List(ctx context.Context, scope string, expandRegistrationDefinition *bool) (result RegistrationAssignmentListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationAssignmentsClient.List") - defer func() { - sc := -1 - if result.ral.Response.Response != nil { - sc = result.ral.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, scope, expandRegistrationDefinition) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ral.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "List", resp, "Failure sending request") - return - } - - result.ral, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "List", resp, "Failure responding to request") - return - } - if result.ral.hasNextLink() && result.ral.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RegistrationAssignmentsClient) ListPreparer(ctx context.Context, scope string, expandRegistrationDefinition *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "scope": scope, - } - - const APIVersion = "2019-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if expandRegistrationDefinition != nil { - queryParameters["$expandRegistrationDefinition"] = autorest.Encode("query", *expandRegistrationDefinition) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.ManagedServices/registrationAssignments", 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 RegistrationAssignmentsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(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 RegistrationAssignmentsClient) ListResponder(resp *http.Response) (result RegistrationAssignmentList, err error) { - err = autorest.Respond( - resp, - 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 RegistrationAssignmentsClient) listNextResults(ctx context.Context, lastResults RegistrationAssignmentList) (result RegistrationAssignmentList, err error) { - req, err := lastResults.registrationAssignmentListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "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, "managedservices.RegistrationAssignmentsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RegistrationAssignmentsClient) ListComplete(ctx context.Context, scope string, expandRegistrationDefinition *bool) (result RegistrationAssignmentListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationAssignmentsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, scope, expandRegistrationDefinition) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/registrationdefinitions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/registrationdefinitions.go deleted file mode 100644 index a7bec2abc15d..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/registrationdefinitions.go +++ /dev/null @@ -1,396 +0,0 @@ -package managedservices - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RegistrationDefinitionsClient is the specification for ManagedServices. -type RegistrationDefinitionsClient struct { - BaseClient -} - -// NewRegistrationDefinitionsClient creates an instance of the RegistrationDefinitionsClient client. -func NewRegistrationDefinitionsClient() RegistrationDefinitionsClient { - return NewRegistrationDefinitionsClientWithBaseURI(DefaultBaseURI) -} - -// NewRegistrationDefinitionsClientWithBaseURI creates an instance of the RegistrationDefinitionsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewRegistrationDefinitionsClientWithBaseURI(baseURI string) RegistrationDefinitionsClient { - return RegistrationDefinitionsClient{NewWithBaseURI(baseURI)} -} - -// CreateOrUpdate creates or updates a registration definition. -// Parameters: -// registrationDefinitionID - guid of the registration definition. -// scope - scope of the resource. -// requestBody - the parameters required to create new registration definition. -func (client RegistrationDefinitionsClient) CreateOrUpdate(ctx context.Context, registrationDefinitionID string, scope string, requestBody RegistrationDefinition) (result RegistrationDefinitionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationDefinitionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: requestBody, - Constraints: []validation.Constraint{{Target: "requestBody.Properties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "requestBody.Properties.Authorizations", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "requestBody.Properties.ManagedByTenantID", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "requestBody.Plan", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "requestBody.Plan.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "requestBody.Plan.Publisher", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "requestBody.Plan.Product", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "requestBody.Plan.Version", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("managedservices.RegistrationDefinitionsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, registrationDefinitionID, scope, requestBody) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RegistrationDefinitionsClient) CreateOrUpdatePreparer(ctx context.Context, registrationDefinitionID string, scope string, requestBody RegistrationDefinition) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "registrationDefinitionId": autorest.Encode("path", registrationDefinitionID), - "scope": scope, - } - - const APIVersion = "2019-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - requestBody.ID = nil - requestBody.Type = nil - requestBody.Name = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.ManagedServices/registrationDefinitions/{registrationDefinitionId}", pathParameters), - autorest.WithJSON(requestBody), - 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 RegistrationDefinitionsClient) CreateOrUpdateSender(req *http.Request) (future RegistrationDefinitionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RegistrationDefinitionsClient) CreateOrUpdateResponder(resp *http.Response) (result RegistrationDefinition, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the registration definition. -// Parameters: -// registrationDefinitionID - guid of the registration definition. -// scope - scope of the resource. -func (client RegistrationDefinitionsClient) Delete(ctx context.Context, registrationDefinitionID string, scope string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationDefinitionsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, registrationDefinitionID, scope) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RegistrationDefinitionsClient) DeletePreparer(ctx context.Context, registrationDefinitionID string, scope string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "registrationDefinitionId": autorest.Encode("path", registrationDefinitionID), - "scope": scope, - } - - const APIVersion = "2019-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.ManagedServices/registrationDefinitions/{registrationDefinitionId}", 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 RegistrationDefinitionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RegistrationDefinitionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the registration definition details. -// Parameters: -// scope - scope of the resource. -// registrationDefinitionID - guid of the registration definition. -func (client RegistrationDefinitionsClient) Get(ctx context.Context, scope string, registrationDefinitionID string) (result RegistrationDefinition, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationDefinitionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, scope, registrationDefinitionID) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RegistrationDefinitionsClient) GetPreparer(ctx context.Context, scope string, registrationDefinitionID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "registrationDefinitionId": autorest.Encode("path", registrationDefinitionID), - "scope": scope, - } - - const APIVersion = "2019-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.ManagedServices/registrationDefinitions/{registrationDefinitionId}", 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 RegistrationDefinitionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RegistrationDefinitionsClient) GetResponder(resp *http.Response) (result RegistrationDefinition, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets a list of the registration definitions. -// Parameters: -// scope - scope of the resource. -func (client RegistrationDefinitionsClient) List(ctx context.Context, scope string) (result RegistrationDefinitionListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationDefinitionsClient.List") - defer func() { - sc := -1 - if result.rdl.Response.Response != nil { - sc = result.rdl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, scope) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rdl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "List", resp, "Failure sending request") - return - } - - result.rdl, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "List", resp, "Failure responding to request") - return - } - if result.rdl.hasNextLink() && result.rdl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RegistrationDefinitionsClient) ListPreparer(ctx context.Context, scope string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "scope": scope, - } - - const APIVersion = "2019-06-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{scope}/providers/Microsoft.ManagedServices/registrationDefinitions", 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 RegistrationDefinitionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(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 RegistrationDefinitionsClient) ListResponder(resp *http.Response) (result RegistrationDefinitionList, err error) { - err = autorest.Respond( - resp, - 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 RegistrationDefinitionsClient) listNextResults(ctx context.Context, lastResults RegistrationDefinitionList) (result RegistrationDefinitionList, err error) { - req, err := lastResults.registrationDefinitionListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "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, "managedservices.RegistrationDefinitionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RegistrationDefinitionsClient) ListComplete(ctx context.Context, scope string) (result RegistrationDefinitionListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationDefinitionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, scope) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/version.go deleted file mode 100644 index 4004dbdd42b8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/managedservices/mgmt/2019-06-01/managedservices/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package managedservices - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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() + " managedservices/2019-06-01" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/CHANGELOG.md deleted file mode 100644 index 52911e4cc5e4..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/_meta.json deleted file mode 100644 index 85e4ce68e842..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "bb9f1204f9a337404ff7e7b73b4c7b4ddde7f8f1", - "readme": "/_/azure-rest-api-specs/specification/netapp/resource-manager/readme.md", - "tag": "package-netapp-2021-10-01", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-netapp-2021-10-01 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix /_/azure-rest-api-specs/specification/netapp/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/accountbackups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/accountbackups.go deleted file mode 100644 index 0c1f8bb6327c..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/accountbackups.go +++ /dev/null @@ -1,290 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AccountBackupsClient is the microsoft NetApp Files Azure Resource Provider specification -type AccountBackupsClient struct { - BaseClient -} - -// NewAccountBackupsClient creates an instance of the AccountBackupsClient client. -func NewAccountBackupsClient(subscriptionID string) AccountBackupsClient { - return NewAccountBackupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAccountBackupsClientWithBaseURI creates an instance of the AccountBackupsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewAccountBackupsClientWithBaseURI(baseURI string, subscriptionID string) AccountBackupsClient { - return AccountBackupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Delete delete the specified Backup for a Netapp Account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// backupName - the name of the backup -func (client AccountBackupsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, backupName string) (result AccountBackupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountBackupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.AccountBackupsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, backupName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountBackupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountBackupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client AccountBackupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, backupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupName": autorest.Encode("path", backupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/accountBackups/{backupName}", 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 AccountBackupsClient) DeleteSender(req *http.Request) (future AccountBackupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client AccountBackupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified backup for a Netapp Account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// backupName - the name of the backup -func (client AccountBackupsClient) Get(ctx context.Context, resourceGroupName string, accountName string, backupName string) (result Backup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountBackupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.AccountBackupsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName, backupName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountBackupsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.AccountBackupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountBackupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client AccountBackupsClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, backupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupName": autorest.Encode("path", backupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/accountBackups/{backupName}", 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 AccountBackupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client AccountBackupsClient) GetResponder(resp *http.Response) (result Backup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all Backups for a Netapp Account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client AccountBackupsClient) List(ctx context.Context, resourceGroupName string, accountName string) (result BackupsList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountBackupsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.AccountBackupsClient", "List", err.Error()) - } - - req, err := client.ListPreparer(ctx, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountBackupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.AccountBackupsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountBackupsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AccountBackupsClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/accountBackups", 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 AccountBackupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AccountBackupsClient) ListResponder(resp *http.Response) (result BackupsList, err error) { - err = autorest.Respond( - resp, - 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/netapp/mgmt/2021-10-01/netapp/accounts.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/accounts.go deleted file mode 100644 index 2e1934acc518..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/accounts.go +++ /dev/null @@ -1,629 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AccountsClient is the microsoft NetApp Files Azure Resource Provider specification -type AccountsClient struct { - BaseClient -} - -// NewAccountsClient creates an instance of the AccountsClient client. -func NewAccountsClient(subscriptionID string) AccountsClient { - return NewAccountsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAccountsClientWithBaseURI creates an instance of the AccountsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewAccountsClientWithBaseURI(baseURI string, subscriptionID string) AccountsClient { - return AccountsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update the specified NetApp account within the resource group -// Parameters: -// body - netApp Account object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client AccountsClient) CreateOrUpdate(ctx context.Context, body Account, resourceGroupName string, accountName string) (result AccountsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Location", Name: validation.Null, Rule: true, Chain: nil}}}, - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.AccountsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, body, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client AccountsClient) CreateOrUpdatePreparer(ctx context.Context, body Account, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Etag = nil - body.Type = nil - body.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}", pathParameters), - autorest.WithJSON(body), - 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 AccountsClient) CreateOrUpdateSender(req *http.Request) (future AccountsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client AccountsClient) CreateOrUpdateResponder(resp *http.Response) (result Account, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the specified NetApp account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client AccountsClient) Delete(ctx context.Context, resourceGroupName string, accountName string) (result AccountsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.AccountsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client AccountsClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}", 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 AccountsClient) DeleteSender(req *http.Request) (future AccountsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client AccountsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the NetApp account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client AccountsClient) Get(ctx context.Context, resourceGroupName string, accountName string) (result Account, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.AccountsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client AccountsClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}", 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 AccountsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client AccountsClient) GetResponder(resp *http.Response) (result Account, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list and describe all NetApp accounts in the resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client AccountsClient) List(ctx context.Context, resourceGroupName string) (result AccountListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.List") - defer func() { - sc := -1 - if result.al.Response.Response != nil { - sc = result.al.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.AccountsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.al.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "List", resp, "Failure sending request") - return - } - - result.al, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "List", resp, "Failure responding to request") - return - } - if result.al.hasNextLink() && result.al.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AccountsClient) ListPreparer(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 = "2021-10-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.NetApp/netAppAccounts", 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 AccountsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AccountsClient) ListResponder(resp *http.Response) (result AccountList, err error) { - err = autorest.Respond( - resp, - 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 AccountsClient) listNextResults(ctx context.Context, lastResults AccountList) (result AccountList, err error) { - req, err := lastResults.accountListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "netapp.AccountsClient", "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, "netapp.AccountsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AccountsClient) ListComplete(ctx context.Context, resourceGroupName string) (result AccountListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListBySubscription list and describe all NetApp accounts in the subscription. -func (client AccountsClient) ListBySubscription(ctx context.Context) (result AccountListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.ListBySubscription") - defer func() { - sc := -1 - if result.al.Response.Response != nil { - sc = result.al.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.al.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.al, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.al.hasNextLink() && result.al.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client AccountsClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.NetApp/netAppAccounts", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client AccountsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client AccountsClient) ListBySubscriptionResponder(resp *http.Response) (result AccountList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client AccountsClient) listBySubscriptionNextResults(ctx context.Context, lastResults AccountList) (result AccountList, err error) { - req, err := lastResults.accountListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "netapp.AccountsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "netapp.AccountsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client AccountsClient) ListBySubscriptionComplete(ctx context.Context) (result AccountListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx) - return -} - -// Update patch the specified NetApp account -// Parameters: -// body - netApp Account object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client AccountsClient) Update(ctx context.Context, body AccountPatch, resourceGroupName string, accountName string) (result AccountsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.AccountsClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, body, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client AccountsClient) UpdatePreparer(ctx context.Context, body AccountPatch, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}", pathParameters), - autorest.WithJSON(body), - 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 AccountsClient) UpdateSender(req *http.Request) (future AccountsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client AccountsClient) UpdateResponder(resp *http.Response) (result Account, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/netapp/mgmt/2021-10-01/netapp/backuppolicies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/backuppolicies.go deleted file mode 100644 index 2073c2dd3d49..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/backuppolicies.go +++ /dev/null @@ -1,485 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// BackupPoliciesClient is the microsoft NetApp Files Azure Resource Provider specification -type BackupPoliciesClient struct { - BaseClient -} - -// NewBackupPoliciesClient creates an instance of the BackupPoliciesClient client. -func NewBackupPoliciesClient(subscriptionID string) BackupPoliciesClient { - return NewBackupPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewBackupPoliciesClientWithBaseURI creates an instance of the BackupPoliciesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewBackupPoliciesClientWithBaseURI(baseURI string, subscriptionID string) BackupPoliciesClient { - return BackupPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create create a backup policy for Netapp Account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// backupPolicyName - backup policy Name which uniquely identify backup policy. -// body - backup policy object supplied in the body of the operation. -func (client BackupPoliciesClient) Create(ctx context.Context, resourceGroupName string, accountName string, backupPolicyName string, body BackupPolicy) (result BackupPoliciesCreateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupPoliciesClient.Create") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Location", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.BackupPolicyProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupPoliciesClient", "Create", err.Error()) - } - - req, err := client.CreatePreparer(ctx, resourceGroupName, accountName, backupPolicyName, body) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "Create", nil, "Failure preparing request") - return - } - - result, err = client.CreateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "Create", result.Response(), "Failure sending request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client BackupPoliciesClient) CreatePreparer(ctx context.Context, resourceGroupName string, accountName string, backupPolicyName string, body BackupPolicy) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupPolicyName": autorest.Encode("path", backupPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Etag = nil - body.Type = nil - body.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/backupPolicies/{backupPolicyName}", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client BackupPoliciesClient) CreateSender(req *http.Request) (future BackupPoliciesCreateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client BackupPoliciesClient) CreateResponder(resp *http.Response) (result BackupPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete backup policy -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// backupPolicyName - backup policy Name which uniquely identify backup policy. -func (client BackupPoliciesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, backupPolicyName string) (result BackupPoliciesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupPoliciesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupPoliciesClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, backupPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client BackupPoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, backupPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupPolicyName": autorest.Encode("path", backupPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/backupPolicies/{backupPolicyName}", 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 BackupPoliciesClient) DeleteSender(req *http.Request) (future BackupPoliciesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client BackupPoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get a particular backup Policy -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// backupPolicyName - backup policy Name which uniquely identify backup policy. -func (client BackupPoliciesClient) Get(ctx context.Context, resourceGroupName string, accountName string, backupPolicyName string) (result BackupPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupPoliciesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupPoliciesClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName, backupPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client BackupPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, backupPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupPolicyName": autorest.Encode("path", backupPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/backupPolicies/{backupPolicyName}", 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 BackupPoliciesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client BackupPoliciesClient) GetResponder(resp *http.Response) (result BackupPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list backup policies for Netapp Account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client BackupPoliciesClient) List(ctx context.Context, resourceGroupName string, accountName string) (result BackupPoliciesList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupPoliciesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupPoliciesClient", "List", err.Error()) - } - - req, err := client.ListPreparer(ctx, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client BackupPoliciesClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/backupPolicies", 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 BackupPoliciesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client BackupPoliciesClient) ListResponder(resp *http.Response) (result BackupPoliciesList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Update patch a backup policy for Netapp Account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// backupPolicyName - backup policy Name which uniquely identify backup policy. -// body - backup policy object supplied in the body of the operation. -func (client BackupPoliciesClient) Update(ctx context.Context, resourceGroupName string, accountName string, backupPolicyName string, body BackupPolicyPatch) (result BackupPoliciesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupPoliciesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupPoliciesClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, resourceGroupName, accountName, backupPolicyName, body) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client BackupPoliciesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, backupPolicyName string, body BackupPolicyPatch) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupPolicyName": autorest.Encode("path", backupPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/backupPolicies/{backupPolicyName}", pathParameters), - autorest.WithJSON(body), - 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 BackupPoliciesClient) UpdateSender(req *http.Request) (future BackupPoliciesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client BackupPoliciesClient) UpdateResponder(resp *http.Response) (result BackupPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/netapp/mgmt/2021-10-01/netapp/backups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/backups.go deleted file mode 100644 index e430721365de..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/backups.go +++ /dev/null @@ -1,741 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// BackupsClient is the microsoft NetApp Files Azure Resource Provider specification -type BackupsClient struct { - BaseClient -} - -// NewBackupsClient creates an instance of the BackupsClient client. -func NewBackupsClient(subscriptionID string) BackupsClient { - return NewBackupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewBackupsClientWithBaseURI creates an instance of the BackupsClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewBackupsClientWithBaseURI(baseURI string, subscriptionID string) BackupsClient { - return BackupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create create a backup for the volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// backupName - the name of the backup -// body - backup object supplied in the body of the operation. -func (client BackupsClient) Create(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, backupName string, body Backup) (result BackupsCreateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupsClient.Create") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Location", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.BackupProperties", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "body.BackupProperties.BackupID", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.BackupProperties.BackupID", Name: validation.MaxLength, Rule: 36, Chain: nil}, - {Target: "body.BackupProperties.BackupID", Name: validation.MinLength, Rule: 36, Chain: nil}, - {Target: "body.BackupProperties.BackupID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$`, Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("netapp.BackupsClient", "Create", err.Error()) - } - - req, err := client.CreatePreparer(ctx, resourceGroupName, accountName, poolName, volumeName, backupName, body) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "Create", nil, "Failure preparing request") - return - } - - result, err = client.CreateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "Create", result.Response(), "Failure sending request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client BackupsClient) CreatePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, backupName string, body Backup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupName": autorest.Encode("path", backupName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/backups/{backupName}", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client BackupsClient) CreateSender(req *http.Request) (future BackupsCreateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client BackupsClient) CreateResponder(resp *http.Response) (result Backup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete a backup of the volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// backupName - the name of the backup -func (client BackupsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, backupName string) (result BackupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, poolName, volumeName, backupName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client BackupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, backupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupName": autorest.Encode("path", backupName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/backups/{backupName}", 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 BackupsClient) DeleteSender(req *http.Request) (future BackupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client BackupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified backup of the volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// backupName - the name of the backup -func (client BackupsClient) Get(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, backupName string) (result Backup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, backupName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client BackupsClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, backupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupName": autorest.Encode("path", backupName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/backups/{backupName}", 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 BackupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client BackupsClient) GetResponder(resp *http.Response) (result Backup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetStatus get the status of the backup for a volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client BackupsClient) GetStatus(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result BackupStatus, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupsClient.GetStatus") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupsClient", "GetStatus", err.Error()) - } - - req, err := client.GetStatusPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "GetStatus", nil, "Failure preparing request") - return - } - - resp, err := client.GetStatusSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "GetStatus", resp, "Failure sending request") - return - } - - result, err = client.GetStatusResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "GetStatus", resp, "Failure responding to request") - return - } - - return -} - -// GetStatusPreparer prepares the GetStatus request. -func (client BackupsClient) GetStatusPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/backupStatus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetStatusSender sends the GetStatus request. The method will close the -// http.Response Body if it receives an error. -func (client BackupsClient) GetStatusSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetStatusResponder handles the response to the GetStatus request. The method always -// closes the http.Response Body. -func (client BackupsClient) GetStatusResponder(resp *http.Response) (result BackupStatus, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVolumeRestoreStatus get the status of the restore for a volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client BackupsClient) GetVolumeRestoreStatus(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result RestoreStatus, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupsClient.GetVolumeRestoreStatus") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupsClient", "GetVolumeRestoreStatus", err.Error()) - } - - req, err := client.GetVolumeRestoreStatusPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "GetVolumeRestoreStatus", nil, "Failure preparing request") - return - } - - resp, err := client.GetVolumeRestoreStatusSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "GetVolumeRestoreStatus", resp, "Failure sending request") - return - } - - result, err = client.GetVolumeRestoreStatusResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "GetVolumeRestoreStatus", resp, "Failure responding to request") - return - } - - return -} - -// GetVolumeRestoreStatusPreparer prepares the GetVolumeRestoreStatus request. -func (client BackupsClient) GetVolumeRestoreStatusPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/restoreStatus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVolumeRestoreStatusSender sends the GetVolumeRestoreStatus request. The method will close the -// http.Response Body if it receives an error. -func (client BackupsClient) GetVolumeRestoreStatusSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetVolumeRestoreStatusResponder handles the response to the GetVolumeRestoreStatus request. The method always -// closes the http.Response Body. -func (client BackupsClient) GetVolumeRestoreStatusResponder(resp *http.Response) (result RestoreStatus, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all backups for a volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client BackupsClient) List(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result BackupsList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupsClient", "List", err.Error()) - } - - req, err := client.ListPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client BackupsClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/backups", 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 BackupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client BackupsClient) ListResponder(resp *http.Response) (result BackupsList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Update patch a backup for the volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// backupName - the name of the backup -// body - backup object supplied in the body of the operation. -func (client BackupsClient) Update(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, backupName string, body *BackupPatch) (result BackupsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BackupsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.BackupsClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, resourceGroupName, accountName, poolName, volumeName, backupName, body) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client BackupsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, backupName string, body *BackupPatch) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "backupName": autorest.Encode("path", backupName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/backups/{backupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if body != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(body)) - } - 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 BackupsClient) UpdateSender(req *http.Request) (future BackupsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client BackupsClient) UpdateResponder(resp *http.Response) (result Backup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/netapp/mgmt/2021-10-01/netapp/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/client.go deleted file mode 100644 index 780c3590d75f..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/client.go +++ /dev/null @@ -1,41 +0,0 @@ -// Package netapp implements the Azure ARM Netapp service API version 2021-10-01. -// -// Microsoft NetApp Files Azure Resource Provider specification -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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 Netapp - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Netapp. -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 using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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/netapp/mgmt/2021-10-01/netapp/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/enums.go deleted file mode 100644 index 8fa945a3125e..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/enums.go +++ /dev/null @@ -1,346 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// ActiveDirectoryStatus enumerates the values for active directory status. -type ActiveDirectoryStatus string - -const ( - // ActiveDirectoryStatusCreated Active Directory created but not in use - ActiveDirectoryStatusCreated ActiveDirectoryStatus = "Created" - // ActiveDirectoryStatusDeleted Active Directory Deleted - ActiveDirectoryStatusDeleted ActiveDirectoryStatus = "Deleted" - // ActiveDirectoryStatusError Error with the Active Directory - ActiveDirectoryStatusError ActiveDirectoryStatus = "Error" - // ActiveDirectoryStatusInUse Active Directory in use by SMB Volume - ActiveDirectoryStatusInUse ActiveDirectoryStatus = "InUse" - // ActiveDirectoryStatusUpdating Active Directory Updating - ActiveDirectoryStatusUpdating ActiveDirectoryStatus = "Updating" -) - -// PossibleActiveDirectoryStatusValues returns an array of possible values for the ActiveDirectoryStatus const type. -func PossibleActiveDirectoryStatusValues() []ActiveDirectoryStatus { - return []ActiveDirectoryStatus{ActiveDirectoryStatusCreated, ActiveDirectoryStatusDeleted, ActiveDirectoryStatusError, ActiveDirectoryStatusInUse, ActiveDirectoryStatusUpdating} -} - -// ApplicationType enumerates the values for application type. -type ApplicationType string - -const ( - // ApplicationTypeSAPHANA ... - ApplicationTypeSAPHANA ApplicationType = "SAP-HANA" -) - -// PossibleApplicationTypeValues returns an array of possible values for the ApplicationType const type. -func PossibleApplicationTypeValues() []ApplicationType { - return []ApplicationType{ApplicationTypeSAPHANA} -} - -// AvsDataStore enumerates the values for avs data store. -type AvsDataStore string - -const ( - // AvsDataStoreDisabled avsDataStore is disabled - AvsDataStoreDisabled AvsDataStore = "Disabled" - // AvsDataStoreEnabled avsDataStore is enabled - AvsDataStoreEnabled AvsDataStore = "Enabled" -) - -// PossibleAvsDataStoreValues returns an array of possible values for the AvsDataStore const type. -func PossibleAvsDataStoreValues() []AvsDataStore { - return []AvsDataStore{AvsDataStoreDisabled, AvsDataStoreEnabled} -} - -// BackupType enumerates the values for backup type. -type BackupType string - -const ( - // BackupTypeManual Manual backup - BackupTypeManual BackupType = "Manual" - // BackupTypeScheduled Scheduled backup - BackupTypeScheduled BackupType = "Scheduled" -) - -// PossibleBackupTypeValues returns an array of possible values for the BackupType const type. -func PossibleBackupTypeValues() []BackupType { - return []BackupType{BackupTypeManual, BackupTypeScheduled} -} - -// CheckNameResourceTypes enumerates the values for check name resource types. -type CheckNameResourceTypes string - -const ( - // CheckNameResourceTypesMicrosoftNetAppnetAppAccounts ... - CheckNameResourceTypesMicrosoftNetAppnetAppAccounts CheckNameResourceTypes = "Microsoft.NetApp/netAppAccounts" - // CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPools ... - CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPools CheckNameResourceTypes = "Microsoft.NetApp/netAppAccounts/capacityPools" - // CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumes ... - CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumes CheckNameResourceTypes = "Microsoft.NetApp/netAppAccounts/capacityPools/volumes" - // CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumessnapshots ... - CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumessnapshots CheckNameResourceTypes = "Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots" -) - -// PossibleCheckNameResourceTypesValues returns an array of possible values for the CheckNameResourceTypes const type. -func PossibleCheckNameResourceTypesValues() []CheckNameResourceTypes { - return []CheckNameResourceTypes{CheckNameResourceTypesMicrosoftNetAppnetAppAccounts, CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPools, CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumes, CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumessnapshots} -} - -// CheckQuotaNameResourceTypes enumerates the values for check quota name resource types. -type CheckQuotaNameResourceTypes string - -const ( - // CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccounts ... - CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccounts CheckQuotaNameResourceTypes = "Microsoft.NetApp/netAppAccounts" - // CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPools ... - CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPools CheckQuotaNameResourceTypes = "Microsoft.NetApp/netAppAccounts/capacityPools" - // CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumes ... - CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumes CheckQuotaNameResourceTypes = "Microsoft.NetApp/netAppAccounts/capacityPools/volumes" - // CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumessnapshots ... - CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumessnapshots CheckQuotaNameResourceTypes = "Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots" -) - -// PossibleCheckQuotaNameResourceTypesValues returns an array of possible values for the CheckQuotaNameResourceTypes const type. -func PossibleCheckQuotaNameResourceTypesValues() []CheckQuotaNameResourceTypes { - return []CheckQuotaNameResourceTypes{CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccounts, CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPools, CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumes, CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumessnapshots} -} - -// ChownMode enumerates the values for chown mode. -type ChownMode string - -const ( - // ChownModeRestricted ... - ChownModeRestricted ChownMode = "Restricted" - // ChownModeUnrestricted ... - ChownModeUnrestricted ChownMode = "Unrestricted" -) - -// PossibleChownModeValues returns an array of possible values for the ChownMode const type. -func PossibleChownModeValues() []ChownMode { - return []ChownMode{ChownModeRestricted, ChownModeUnrestricted} -} - -// CreatedByType enumerates the values for created by type. -type CreatedByType string - -const ( - // CreatedByTypeApplication ... - CreatedByTypeApplication CreatedByType = "Application" - // CreatedByTypeKey ... - CreatedByTypeKey CreatedByType = "Key" - // CreatedByTypeManagedIdentity ... - CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" - // CreatedByTypeUser ... - CreatedByTypeUser CreatedByType = "User" -) - -// PossibleCreatedByTypeValues returns an array of possible values for the CreatedByType const type. -func PossibleCreatedByTypeValues() []CreatedByType { - return []CreatedByType{CreatedByTypeApplication, CreatedByTypeKey, CreatedByTypeManagedIdentity, CreatedByTypeUser} -} - -// EnableSubvolumes enumerates the values for enable subvolumes. -type EnableSubvolumes string - -const ( - // EnableSubvolumesDisabled subvolumes are not enabled - EnableSubvolumesDisabled EnableSubvolumes = "Disabled" - // EnableSubvolumesEnabled subvolumes are enabled - EnableSubvolumesEnabled EnableSubvolumes = "Enabled" -) - -// PossibleEnableSubvolumesValues returns an array of possible values for the EnableSubvolumes const type. -func PossibleEnableSubvolumesValues() []EnableSubvolumes { - return []EnableSubvolumes{EnableSubvolumesDisabled, EnableSubvolumesEnabled} -} - -// EncryptionType enumerates the values for encryption type. -type EncryptionType string - -const ( - // EncryptionTypeDouble EncryptionType Double, volumes will use double encryption at rest - EncryptionTypeDouble EncryptionType = "Double" - // EncryptionTypeSingle EncryptionType Single, volumes will use single encryption at rest - EncryptionTypeSingle EncryptionType = "Single" -) - -// PossibleEncryptionTypeValues returns an array of possible values for the EncryptionType const type. -func PossibleEncryptionTypeValues() []EncryptionType { - return []EncryptionType{EncryptionTypeDouble, EncryptionTypeSingle} -} - -// EndpointType enumerates the values for endpoint type. -type EndpointType string - -const ( - // EndpointTypeDst ... - EndpointTypeDst EndpointType = "dst" - // EndpointTypeSrc ... - EndpointTypeSrc EndpointType = "src" -) - -// PossibleEndpointTypeValues returns an array of possible values for the EndpointType const type. -func PossibleEndpointTypeValues() []EndpointType { - return []EndpointType{EndpointTypeDst, EndpointTypeSrc} -} - -// InAvailabilityReasonType enumerates the values for in availability reason type. -type InAvailabilityReasonType string - -const ( - // InAvailabilityReasonTypeAlreadyExists ... - InAvailabilityReasonTypeAlreadyExists InAvailabilityReasonType = "AlreadyExists" - // InAvailabilityReasonTypeInvalid ... - InAvailabilityReasonTypeInvalid InAvailabilityReasonType = "Invalid" -) - -// PossibleInAvailabilityReasonTypeValues returns an array of possible values for the InAvailabilityReasonType const type. -func PossibleInAvailabilityReasonTypeValues() []InAvailabilityReasonType { - return []InAvailabilityReasonType{InAvailabilityReasonTypeAlreadyExists, InAvailabilityReasonTypeInvalid} -} - -// MetricAggregationType enumerates the values for metric aggregation type. -type MetricAggregationType string - -const ( - // MetricAggregationTypeAverage ... - MetricAggregationTypeAverage MetricAggregationType = "Average" -) - -// PossibleMetricAggregationTypeValues returns an array of possible values for the MetricAggregationType const type. -func PossibleMetricAggregationTypeValues() []MetricAggregationType { - return []MetricAggregationType{MetricAggregationTypeAverage} -} - -// MirrorState enumerates the values for mirror state. -type MirrorState string - -const ( - // MirrorStateBroken ... - MirrorStateBroken MirrorState = "Broken" - // MirrorStateMirrored ... - MirrorStateMirrored MirrorState = "Mirrored" - // MirrorStateUninitialized ... - MirrorStateUninitialized MirrorState = "Uninitialized" -) - -// PossibleMirrorStateValues returns an array of possible values for the MirrorState const type. -func PossibleMirrorStateValues() []MirrorState { - return []MirrorState{MirrorStateBroken, MirrorStateMirrored, MirrorStateUninitialized} -} - -// NetworkFeatures enumerates the values for network features. -type NetworkFeatures string - -const ( - // NetworkFeaturesBasic Basic network feature. - NetworkFeaturesBasic NetworkFeatures = "Basic" - // NetworkFeaturesStandard Standard network feature. - NetworkFeaturesStandard NetworkFeatures = "Standard" -) - -// PossibleNetworkFeaturesValues returns an array of possible values for the NetworkFeatures const type. -func PossibleNetworkFeaturesValues() []NetworkFeatures { - return []NetworkFeatures{NetworkFeaturesBasic, NetworkFeaturesStandard} -} - -// QosType enumerates the values for qos type. -type QosType string - -const ( - // QosTypeAuto qos type Auto - QosTypeAuto QosType = "Auto" - // QosTypeManual qos type Manual - QosTypeManual QosType = "Manual" -) - -// PossibleQosTypeValues returns an array of possible values for the QosType const type. -func PossibleQosTypeValues() []QosType { - return []QosType{QosTypeAuto, QosTypeManual} -} - -// RelationshipStatus enumerates the values for relationship status. -type RelationshipStatus string - -const ( - // RelationshipStatusIdle ... - RelationshipStatusIdle RelationshipStatus = "Idle" - // RelationshipStatusTransferring ... - RelationshipStatusTransferring RelationshipStatus = "Transferring" -) - -// PossibleRelationshipStatusValues returns an array of possible values for the RelationshipStatus const type. -func PossibleRelationshipStatusValues() []RelationshipStatus { - return []RelationshipStatus{RelationshipStatusIdle, RelationshipStatusTransferring} -} - -// ReplicationSchedule enumerates the values for replication schedule. -type ReplicationSchedule string - -const ( - // ReplicationSchedule10minutely ... - ReplicationSchedule10minutely ReplicationSchedule = "_10minutely" - // ReplicationScheduleDaily ... - ReplicationScheduleDaily ReplicationSchedule = "daily" - // ReplicationScheduleHourly ... - ReplicationScheduleHourly ReplicationSchedule = "hourly" -) - -// PossibleReplicationScheduleValues returns an array of possible values for the ReplicationSchedule const type. -func PossibleReplicationScheduleValues() []ReplicationSchedule { - return []ReplicationSchedule{ReplicationSchedule10minutely, ReplicationScheduleDaily, ReplicationScheduleHourly} -} - -// SecurityStyle enumerates the values for security style. -type SecurityStyle string - -const ( - // SecurityStyleNtfs ... - SecurityStyleNtfs SecurityStyle = "ntfs" - // SecurityStyleUnix ... - SecurityStyleUnix SecurityStyle = "unix" -) - -// PossibleSecurityStyleValues returns an array of possible values for the SecurityStyle const type. -func PossibleSecurityStyleValues() []SecurityStyle { - return []SecurityStyle{SecurityStyleNtfs, SecurityStyleUnix} -} - -// ServiceLevel enumerates the values for service level. -type ServiceLevel string - -const ( - // ServiceLevelPremium Premium service level - ServiceLevelPremium ServiceLevel = "Premium" - // ServiceLevelStandard Standard service level - ServiceLevelStandard ServiceLevel = "Standard" - // ServiceLevelStandardZRS Zone redundant storage service level - ServiceLevelStandardZRS ServiceLevel = "StandardZRS" - // ServiceLevelUltra Ultra service level - ServiceLevelUltra ServiceLevel = "Ultra" -) - -// PossibleServiceLevelValues returns an array of possible values for the ServiceLevel const type. -func PossibleServiceLevelValues() []ServiceLevel { - return []ServiceLevel{ServiceLevelPremium, ServiceLevelStandard, ServiceLevelStandardZRS, ServiceLevelUltra} -} - -// VolumeStorageToNetworkProximity enumerates the values for volume storage to network proximity. -type VolumeStorageToNetworkProximity string - -const ( - // VolumeStorageToNetworkProximityDefault Basic storage to network connectivity. - VolumeStorageToNetworkProximityDefault VolumeStorageToNetworkProximity = "Default" - // VolumeStorageToNetworkProximityT1 Standard T1 storage to network connectivity. - VolumeStorageToNetworkProximityT1 VolumeStorageToNetworkProximity = "T1" - // VolumeStorageToNetworkProximityT2 Standard T2 storage to network connectivity. - VolumeStorageToNetworkProximityT2 VolumeStorageToNetworkProximity = "T2" -) - -// PossibleVolumeStorageToNetworkProximityValues returns an array of possible values for the VolumeStorageToNetworkProximity const type. -func PossibleVolumeStorageToNetworkProximityValues() []VolumeStorageToNetworkProximity { - return []VolumeStorageToNetworkProximity{VolumeStorageToNetworkProximityDefault, VolumeStorageToNetworkProximityT1, VolumeStorageToNetworkProximityT2} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/models.go deleted file mode 100644 index 81c786643da8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/models.go +++ /dev/null @@ -1,5721 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp" - -// Account netApp account resource -type Account struct { - autorest.Response `json:"-"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // AccountProperties - NetApp Account properties - *AccountProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for Account. -func (a Account) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if a.Location != nil { - objectMap["location"] = a.Location - } - if a.Tags != nil { - objectMap["tags"] = a.Tags - } - if a.AccountProperties != nil { - objectMap["properties"] = a.AccountProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Account struct. -func (a *Account) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - a.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - a.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - a.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - a.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - a.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - a.Tags = tags - } - case "properties": - if v != nil { - var accountProperties AccountProperties - err = json.Unmarshal(*v, &accountProperties) - if err != nil { - return err - } - a.AccountProperties = &accountProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - a.SystemData = &systemData - } - } - } - - return nil -} - -// AccountBackupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type AccountBackupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AccountBackupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AccountBackupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AccountBackupsDeleteFuture.Result. -func (future *AccountBackupsDeleteFuture) result(client AccountBackupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountBackupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.AccountBackupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// AccountEncryption encryption settings -type AccountEncryption struct { - // KeySource - Encryption Key Source. Possible values are: 'Microsoft.NetApp'. - KeySource *string `json:"keySource,omitempty"` -} - -// AccountList list of NetApp account resources -type AccountList struct { - autorest.Response `json:"-"` - // Value - Multiple NetApp accounts - Value *[]Account `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// AccountListIterator provides access to a complete listing of Account values. -type AccountListIterator struct { - i int - page AccountListPage -} - -// NextWithContext 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 *AccountListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AccountListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AccountListIterator) 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 AccountListIterator) Response() AccountList { - 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 AccountListIterator) Value() Account { - if !iter.page.NotDone() { - return Account{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AccountListIterator type. -func NewAccountListIterator(page AccountListPage) AccountListIterator { - return AccountListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (al AccountList) IsEmpty() bool { - return al.Value == nil || len(*al.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (al AccountList) hasNextLink() bool { - return al.NextLink != nil && len(*al.NextLink) != 0 -} - -// accountListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (al AccountList) accountListPreparer(ctx context.Context) (*http.Request, error) { - if !al.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(al.NextLink))) -} - -// AccountListPage contains a page of Account values. -type AccountListPage struct { - fn func(context.Context, AccountList) (AccountList, error) - al AccountList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AccountListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AccountListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.al) - if err != nil { - return err - } - page.al = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AccountListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AccountListPage) NotDone() bool { - return !page.al.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AccountListPage) Response() AccountList { - return page.al -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AccountListPage) Values() []Account { - if page.al.IsEmpty() { - return nil - } - return *page.al.Value -} - -// Creates a new instance of the AccountListPage type. -func NewAccountListPage(cur AccountList, getNextPage func(context.Context, AccountList) (AccountList, error)) AccountListPage { - return AccountListPage{ - fn: getNextPage, - al: cur, - } -} - -// AccountPatch netApp account patch resource -type AccountPatch struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // AccountProperties - NetApp Account properties - *AccountProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for AccountPatch. -func (ap AccountPatch) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ap.Location != nil { - objectMap["location"] = ap.Location - } - if ap.Tags != nil { - objectMap["tags"] = ap.Tags - } - if ap.AccountProperties != nil { - objectMap["properties"] = ap.AccountProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AccountPatch struct. -func (ap *AccountPatch) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ap.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ap.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ap.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ap.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ap.Tags = tags - } - case "properties": - if v != nil { - var accountProperties AccountProperties - err = json.Unmarshal(*v, &accountProperties) - if err != nil { - return err - } - ap.AccountProperties = &accountProperties - } - } - } - - return nil -} - -// AccountProperties netApp account properties -type AccountProperties struct { - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` - // ActiveDirectories - Active Directories - ActiveDirectories *[]ActiveDirectory `json:"activeDirectories,omitempty"` - // Encryption - Encryption settings - Encryption *AccountEncryption `json:"encryption,omitempty"` -} - -// MarshalJSON is the custom marshaler for AccountProperties. -func (ap AccountProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ap.ActiveDirectories != nil { - objectMap["activeDirectories"] = ap.ActiveDirectories - } - if ap.Encryption != nil { - objectMap["encryption"] = ap.Encryption - } - return json.Marshal(objectMap) -} - -// AccountsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type AccountsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AccountsClient) (Account, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AccountsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AccountsCreateOrUpdateFuture.Result. -func (future *AccountsCreateOrUpdateFuture) result(client AccountsClient) (a Account, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - a.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.AccountsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if a.Response.Response, err = future.GetResult(sender); err == nil && a.Response.Response.StatusCode != http.StatusNoContent { - a, err = client.CreateOrUpdateResponder(a.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsCreateOrUpdateFuture", "Result", a.Response.Response, "Failure responding to request") - } - } - return -} - -// AccountsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type AccountsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AccountsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AccountsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AccountsDeleteFuture.Result. -func (future *AccountsDeleteFuture) result(client AccountsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.AccountsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// AccountsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type AccountsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AccountsClient) (Account, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AccountsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AccountsUpdateFuture.Result. -func (future *AccountsUpdateFuture) result(client AccountsClient) (a Account, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - a.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.AccountsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if a.Response.Response, err = future.GetResult(sender); err == nil && a.Response.Response.StatusCode != http.StatusNoContent { - a, err = client.UpdateResponder(a.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.AccountsUpdateFuture", "Result", a.Response.Response, "Failure responding to request") - } - } - return -} - -// ActiveDirectory active Directory -type ActiveDirectory struct { - // ActiveDirectoryID - Id of the Active Directory - ActiveDirectoryID *string `json:"activeDirectoryId,omitempty"` - // Username - Username of Active Directory domain administrator - Username *string `json:"username,omitempty"` - // Password - Plain text password of Active Directory domain administrator, value is masked in the response - Password *string `json:"password,omitempty"` - // Domain - Name of the Active Directory domain - Domain *string `json:"domain,omitempty"` - // DNS - Comma separated list of DNS server IP addresses (IPv4 only) for the Active Directory domain - DNS *string `json:"dns,omitempty"` - // Status - READ-ONLY; Status of the Active Directory. Possible values include: 'ActiveDirectoryStatusCreated', 'ActiveDirectoryStatusInUse', 'ActiveDirectoryStatusDeleted', 'ActiveDirectoryStatusError', 'ActiveDirectoryStatusUpdating' - Status ActiveDirectoryStatus `json:"status,omitempty"` - // StatusDetails - READ-ONLY; Any details in regards to the Status of the Active Directory - StatusDetails *string `json:"statusDetails,omitempty"` - // SmbServerName - NetBIOS name of the SMB server. This name will be registered as a computer account in the AD and used to mount volumes - SmbServerName *string `json:"smbServerName,omitempty"` - // OrganizationalUnit - The Organizational Unit (OU) within the Windows Active Directory - OrganizationalUnit *string `json:"organizationalUnit,omitempty"` - // Site - The Active Directory site the service will limit Domain Controller discovery to - Site *string `json:"site,omitempty"` - // BackupOperators - Users to be added to the Built-in Backup Operator active directory group. A list of unique usernames without domain specifier - BackupOperators *[]string `json:"backupOperators,omitempty"` - // Administrators - Users to be added to the Built-in Administrators active directory group. A list of unique usernames without domain specifier - Administrators *[]string `json:"administrators,omitempty"` - // KdcIP - kdc server IP addresses for the active directory machine. This optional parameter is used only while creating kerberos volume. - KdcIP *string `json:"kdcIP,omitempty"` - // AdName - Name of the active directory machine. This optional parameter is used only while creating kerberos volume - AdName *string `json:"adName,omitempty"` - // ServerRootCACertificate - When LDAP over SSL/TLS is enabled, the LDAP client is required to have base64 encoded Active Directory Certificate Service's self-signed root CA certificate, this optional parameter is used only for dual protocol with LDAP user-mapping volumes. - ServerRootCACertificate *string `json:"serverRootCACertificate,omitempty"` - // AesEncryption - If enabled, AES encryption will be enabled for SMB communication. - AesEncryption *bool `json:"aesEncryption,omitempty"` - // LdapSigning - Specifies whether or not the LDAP traffic needs to be signed. - LdapSigning *bool `json:"ldapSigning,omitempty"` - // SecurityOperators - Domain Users in the Active directory to be given SeSecurityPrivilege privilege (Needed for SMB Continuously available shares for SQL). A list of unique usernames without domain specifier - SecurityOperators *[]string `json:"securityOperators,omitempty"` - // LdapOverTLS - Specifies whether or not the LDAP traffic needs to be secured via TLS. - LdapOverTLS *bool `json:"ldapOverTLS,omitempty"` - // AllowLocalNfsUsersWithLdap - If enabled, NFS client local users can also (in addition to LDAP users) access the NFS volumes. - AllowLocalNfsUsersWithLdap *bool `json:"allowLocalNfsUsersWithLdap,omitempty"` - // EncryptDCConnections - If enabled, Traffic between the SMB server to Domain Controller (DC) will be encrypted. - EncryptDCConnections *bool `json:"encryptDCConnections,omitempty"` - // LdapSearchScope - LDAP Search scope options - LdapSearchScope *LdapSearchScopeOpt `json:"ldapSearchScope,omitempty"` -} - -// MarshalJSON is the custom marshaler for ActiveDirectory. -func (ad ActiveDirectory) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ad.ActiveDirectoryID != nil { - objectMap["activeDirectoryId"] = ad.ActiveDirectoryID - } - if ad.Username != nil { - objectMap["username"] = ad.Username - } - if ad.Password != nil { - objectMap["password"] = ad.Password - } - if ad.Domain != nil { - objectMap["domain"] = ad.Domain - } - if ad.DNS != nil { - objectMap["dns"] = ad.DNS - } - if ad.SmbServerName != nil { - objectMap["smbServerName"] = ad.SmbServerName - } - if ad.OrganizationalUnit != nil { - objectMap["organizationalUnit"] = ad.OrganizationalUnit - } - if ad.Site != nil { - objectMap["site"] = ad.Site - } - if ad.BackupOperators != nil { - objectMap["backupOperators"] = ad.BackupOperators - } - if ad.Administrators != nil { - objectMap["administrators"] = ad.Administrators - } - if ad.KdcIP != nil { - objectMap["kdcIP"] = ad.KdcIP - } - if ad.AdName != nil { - objectMap["adName"] = ad.AdName - } - if ad.ServerRootCACertificate != nil { - objectMap["serverRootCACertificate"] = ad.ServerRootCACertificate - } - if ad.AesEncryption != nil { - objectMap["aesEncryption"] = ad.AesEncryption - } - if ad.LdapSigning != nil { - objectMap["ldapSigning"] = ad.LdapSigning - } - if ad.SecurityOperators != nil { - objectMap["securityOperators"] = ad.SecurityOperators - } - if ad.LdapOverTLS != nil { - objectMap["ldapOverTLS"] = ad.LdapOverTLS - } - if ad.AllowLocalNfsUsersWithLdap != nil { - objectMap["allowLocalNfsUsersWithLdap"] = ad.AllowLocalNfsUsersWithLdap - } - if ad.EncryptDCConnections != nil { - objectMap["encryptDCConnections"] = ad.EncryptDCConnections - } - if ad.LdapSearchScope != nil { - objectMap["ldapSearchScope"] = ad.LdapSearchScope - } - return json.Marshal(objectMap) -} - -// AuthorizeRequest authorize request -type AuthorizeRequest struct { - // RemoteVolumeResourceID - Resource id of the remote volume - RemoteVolumeResourceID *string `json:"remoteVolumeResourceId,omitempty"` -} - -// AzureEntityResource the resource model definition for an Azure Resource Manager resource with an etag. -type AzureEntityResource struct { - // Etag - READ-ONLY; Resource Etag. - Etag *string `json:"etag,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureEntityResource. -func (aer AzureEntityResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Backup backup of a Volume -type Backup struct { - autorest.Response `json:"-"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // BackupProperties - Backup Properties - *BackupProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for Backup. -func (b Backup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if b.Location != nil { - objectMap["location"] = b.Location - } - if b.BackupProperties != nil { - objectMap["properties"] = b.BackupProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Backup struct. -func (b *Backup) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - b.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - b.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - b.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - b.Type = &typeVar - } - case "properties": - if v != nil { - var backupProperties BackupProperties - err = json.Unmarshal(*v, &backupProperties) - if err != nil { - return err - } - b.BackupProperties = &backupProperties - } - } - } - - return nil -} - -// BackupPatch backup patch -type BackupPatch struct { - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // BackupProperties - Backup Properties - *BackupProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackupPatch. -func (bp BackupPatch) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bp.Tags != nil { - objectMap["tags"] = bp.Tags - } - if bp.BackupProperties != nil { - objectMap["properties"] = bp.BackupProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BackupPatch struct. -func (bp *BackupPatch) 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 "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - bp.Tags = tags - } - case "properties": - if v != nil { - var backupProperties BackupProperties - err = json.Unmarshal(*v, &backupProperties) - if err != nil { - return err - } - bp.BackupProperties = &backupProperties - } - } - } - - return nil -} - -// BackupPoliciesCreateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BackupPoliciesCreateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BackupPoliciesClient) (BackupPolicy, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BackupPoliciesCreateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BackupPoliciesCreateFuture.Result. -func (future *BackupPoliciesCreateFuture) result(client BackupPoliciesClient) (bp BackupPolicy, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesCreateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.BackupPoliciesCreateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bp.Response.Response, err = future.GetResult(sender); err == nil && bp.Response.Response.StatusCode != http.StatusNoContent { - bp, err = client.CreateResponder(bp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesCreateFuture", "Result", bp.Response.Response, "Failure responding to request") - } - } - return -} - -// BackupPoliciesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BackupPoliciesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BackupPoliciesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BackupPoliciesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BackupPoliciesDeleteFuture.Result. -func (future *BackupPoliciesDeleteFuture) result(client BackupPoliciesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.BackupPoliciesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// BackupPoliciesList list of Backup Policies -type BackupPoliciesList struct { - autorest.Response `json:"-"` - // Value - A list of backup policies - Value *[]BackupPolicy `json:"value,omitempty"` -} - -// BackupPoliciesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BackupPoliciesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BackupPoliciesClient) (BackupPolicy, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BackupPoliciesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BackupPoliciesUpdateFuture.Result. -func (future *BackupPoliciesUpdateFuture) result(client BackupPoliciesClient) (bp BackupPolicy, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.BackupPoliciesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bp.Response.Response, err = future.GetResult(sender); err == nil && bp.Response.Response.StatusCode != http.StatusNoContent { - bp, err = client.UpdateResponder(bp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupPoliciesUpdateFuture", "Result", bp.Response.Response, "Failure responding to request") - } - } - return -} - -// BackupPolicy backup policy information -type BackupPolicy struct { - autorest.Response `json:"-"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // BackupPolicyProperties - Backup policy Properties - *BackupPolicyProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackupPolicy. -func (bp BackupPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bp.Location != nil { - objectMap["location"] = bp.Location - } - if bp.Tags != nil { - objectMap["tags"] = bp.Tags - } - if bp.BackupPolicyProperties != nil { - objectMap["properties"] = bp.BackupPolicyProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BackupPolicy struct. -func (bp *BackupPolicy) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - bp.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - bp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - bp.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - bp.Tags = tags - } - case "properties": - if v != nil { - var backupPolicyProperties BackupPolicyProperties - err = json.Unmarshal(*v, &backupPolicyProperties) - if err != nil { - return err - } - bp.BackupPolicyProperties = &backupPolicyProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - bp.SystemData = &systemData - } - } - } - - return nil -} - -// BackupPolicyDetails backup policy properties -type BackupPolicyDetails struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // BackupPolicyProperties - Backup policy Properties - *BackupPolicyProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackupPolicyDetails. -func (bpd BackupPolicyDetails) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bpd.Location != nil { - objectMap["location"] = bpd.Location - } - if bpd.Tags != nil { - objectMap["tags"] = bpd.Tags - } - if bpd.BackupPolicyProperties != nil { - objectMap["properties"] = bpd.BackupPolicyProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BackupPolicyDetails struct. -func (bpd *BackupPolicyDetails) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - bpd.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bpd.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bpd.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - bpd.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - bpd.Tags = tags - } - case "properties": - if v != nil { - var backupPolicyProperties BackupPolicyProperties - err = json.Unmarshal(*v, &backupPolicyProperties) - if err != nil { - return err - } - bpd.BackupPolicyProperties = &backupPolicyProperties - } - } - } - - return nil -} - -// BackupPolicyPatch backup policy Details for create and update -type BackupPolicyPatch struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // BackupPolicyProperties - Backup policy Properties - *BackupPolicyProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackupPolicyPatch. -func (bpp BackupPolicyPatch) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bpp.Location != nil { - objectMap["location"] = bpp.Location - } - if bpp.Tags != nil { - objectMap["tags"] = bpp.Tags - } - if bpp.BackupPolicyProperties != nil { - objectMap["properties"] = bpp.BackupPolicyProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BackupPolicyPatch struct. -func (bpp *BackupPolicyPatch) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - bpp.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bpp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bpp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - bpp.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - bpp.Tags = tags - } - case "properties": - if v != nil { - var backupPolicyProperties BackupPolicyProperties - err = json.Unmarshal(*v, &backupPolicyProperties) - if err != nil { - return err - } - bpp.BackupPolicyProperties = &backupPolicyProperties - } - } - } - - return nil -} - -// BackupPolicyProperties backup policy properties -type BackupPolicyProperties struct { - // BackupPolicyID - READ-ONLY; Backup Policy Resource ID - BackupPolicyID *string `json:"backupPolicyId,omitempty"` - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` - // DailyBackupsToKeep - Daily backups count to keep - DailyBackupsToKeep *int32 `json:"dailyBackupsToKeep,omitempty"` - // WeeklyBackupsToKeep - Weekly backups count to keep - WeeklyBackupsToKeep *int32 `json:"weeklyBackupsToKeep,omitempty"` - // MonthlyBackupsToKeep - Monthly backups count to keep - MonthlyBackupsToKeep *int32 `json:"monthlyBackupsToKeep,omitempty"` - // VolumesAssigned - READ-ONLY; Volumes using current backup policy - VolumesAssigned *int32 `json:"volumesAssigned,omitempty"` - // Enabled - The property to decide policy is enabled or not - Enabled *bool `json:"enabled,omitempty"` - // VolumeBackups - READ-ONLY; A list of volumes assigned to this policy - VolumeBackups *[]VolumeBackups `json:"volumeBackups,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackupPolicyProperties. -func (bpp BackupPolicyProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bpp.DailyBackupsToKeep != nil { - objectMap["dailyBackupsToKeep"] = bpp.DailyBackupsToKeep - } - if bpp.WeeklyBackupsToKeep != nil { - objectMap["weeklyBackupsToKeep"] = bpp.WeeklyBackupsToKeep - } - if bpp.MonthlyBackupsToKeep != nil { - objectMap["monthlyBackupsToKeep"] = bpp.MonthlyBackupsToKeep - } - if bpp.Enabled != nil { - objectMap["enabled"] = bpp.Enabled - } - return json.Marshal(objectMap) -} - -// BackupProperties backup properties -type BackupProperties struct { - // BackupID - READ-ONLY; UUID v4 used to identify the Backup - BackupID *string `json:"backupId,omitempty"` - // CreationDate - READ-ONLY; The creation date of the backup - CreationDate *date.Time `json:"creationDate,omitempty"` - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` - // Size - READ-ONLY; Size of backup - Size *int64 `json:"size,omitempty"` - // Label - Label for backup - Label *string `json:"label,omitempty"` - // BackupType - READ-ONLY; Type of backup Manual or Scheduled. Possible values include: 'BackupTypeManual', 'BackupTypeScheduled' - BackupType BackupType `json:"backupType,omitempty"` - // FailureReason - READ-ONLY; Failure reason - FailureReason *string `json:"failureReason,omitempty"` - // VolumeName - READ-ONLY; Volume name - VolumeName *string `json:"volumeName,omitempty"` - // UseExistingSnapshot - Manual backup an already existing snapshot. This will always be false for scheduled backups and true/false for manual backups - UseExistingSnapshot *bool `json:"useExistingSnapshot,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackupProperties. -func (bp BackupProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bp.Label != nil { - objectMap["label"] = bp.Label - } - if bp.UseExistingSnapshot != nil { - objectMap["useExistingSnapshot"] = bp.UseExistingSnapshot - } - return json.Marshal(objectMap) -} - -// BackupsCreateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BackupsCreateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BackupsClient) (Backup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BackupsCreateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BackupsCreateFuture.Result. -func (future *BackupsCreateFuture) result(client BackupsClient) (b Backup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsCreateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - b.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.BackupsCreateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if b.Response.Response, err = future.GetResult(sender); err == nil && b.Response.Response.StatusCode != http.StatusNoContent { - b, err = client.CreateResponder(b.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsCreateFuture", "Result", b.Response.Response, "Failure responding to request") - } - } - return -} - -// BackupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BackupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BackupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BackupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BackupsDeleteFuture.Result. -func (future *BackupsDeleteFuture) result(client BackupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.BackupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// BackupsList list of Backups -type BackupsList struct { - autorest.Response `json:"-"` - // Value - A list of Backups - Value *[]Backup `json:"value,omitempty"` -} - -// BackupStatus backup status -type BackupStatus struct { - autorest.Response `json:"-"` - // Healthy - READ-ONLY; Backup health status - Healthy *bool `json:"healthy,omitempty"` - // RelationshipStatus - READ-ONLY; Status of the backup mirror relationship. Possible values include: 'RelationshipStatusIdle', 'RelationshipStatusTransferring' - RelationshipStatus RelationshipStatus `json:"relationshipStatus,omitempty"` - // MirrorState - READ-ONLY; The status of the backup. Possible values include: 'MirrorStateUninitialized', 'MirrorStateMirrored', 'MirrorStateBroken' - MirrorState MirrorState `json:"mirrorState,omitempty"` - // UnhealthyReason - READ-ONLY; Reason for the unhealthy backup relationship - UnhealthyReason *string `json:"unhealthyReason,omitempty"` - // ErrorMessage - READ-ONLY; Displays error message if the backup is in an error state - ErrorMessage *string `json:"errorMessage,omitempty"` - // LastTransferSize - READ-ONLY; Displays the last transfer size - LastTransferSize *int64 `json:"lastTransferSize,omitempty"` - // LastTransferType - READ-ONLY; Displays the last transfer type - LastTransferType *string `json:"lastTransferType,omitempty"` - // TotalTransferBytes - READ-ONLY; Displays the total bytes transferred - TotalTransferBytes *int64 `json:"totalTransferBytes,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackupStatus. -func (bs BackupStatus) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// BackupsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BackupsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BackupsClient) (Backup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BackupsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BackupsUpdateFuture.Result. -func (future *BackupsUpdateFuture) result(client BackupsClient) (b Backup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - b.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.BackupsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if b.Response.Response, err = future.GetResult(sender); err == nil && b.Response.Response.StatusCode != http.StatusNoContent { - b, err = client.UpdateResponder(b.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.BackupsUpdateFuture", "Result", b.Response.Response, "Failure responding to request") - } - } - return -} - -// BreakReplicationRequest break replication request -type BreakReplicationRequest struct { - // ForceBreakReplication - If replication is in status transferring and you want to force break the replication, set to true - ForceBreakReplication *bool `json:"forceBreakReplication,omitempty"` -} - -// CapacityPool capacity pool resource -type CapacityPool struct { - autorest.Response `json:"-"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // PoolProperties - Capacity pool properties - *PoolProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for CapacityPool. -func (cp CapacityPool) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cp.Location != nil { - objectMap["location"] = cp.Location - } - if cp.Tags != nil { - objectMap["tags"] = cp.Tags - } - if cp.PoolProperties != nil { - objectMap["properties"] = cp.PoolProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for CapacityPool struct. -func (cp *CapacityPool) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cp.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cp.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cp.Tags = tags - } - case "properties": - if v != nil { - var poolProperties PoolProperties - err = json.Unmarshal(*v, &poolProperties) - if err != nil { - return err - } - cp.PoolProperties = &poolProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - cp.SystemData = &systemData - } - } - } - - return nil -} - -// CapacityPoolList list of capacity pool resources -type CapacityPoolList struct { - autorest.Response `json:"-"` - // Value - List of Capacity pools - Value *[]CapacityPool `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// CapacityPoolListIterator provides access to a complete listing of CapacityPool values. -type CapacityPoolListIterator struct { - i int - page CapacityPoolListPage -} - -// NextWithContext 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 *CapacityPoolListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CapacityPoolListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *CapacityPoolListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter CapacityPoolListIterator) 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 CapacityPoolListIterator) Response() CapacityPoolList { - 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 CapacityPoolListIterator) Value() CapacityPool { - if !iter.page.NotDone() { - return CapacityPool{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the CapacityPoolListIterator type. -func NewCapacityPoolListIterator(page CapacityPoolListPage) CapacityPoolListIterator { - return CapacityPoolListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (cpl CapacityPoolList) IsEmpty() bool { - return cpl.Value == nil || len(*cpl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (cpl CapacityPoolList) hasNextLink() bool { - return cpl.NextLink != nil && len(*cpl.NextLink) != 0 -} - -// capacityPoolListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (cpl CapacityPoolList) capacityPoolListPreparer(ctx context.Context) (*http.Request, error) { - if !cpl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(cpl.NextLink))) -} - -// CapacityPoolListPage contains a page of CapacityPool values. -type CapacityPoolListPage struct { - fn func(context.Context, CapacityPoolList) (CapacityPoolList, error) - cpl CapacityPoolList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *CapacityPoolListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CapacityPoolListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.cpl) - if err != nil { - return err - } - page.cpl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *CapacityPoolListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page CapacityPoolListPage) NotDone() bool { - return !page.cpl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page CapacityPoolListPage) Response() CapacityPoolList { - return page.cpl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page CapacityPoolListPage) Values() []CapacityPool { - if page.cpl.IsEmpty() { - return nil - } - return *page.cpl.Value -} - -// Creates a new instance of the CapacityPoolListPage type. -func NewCapacityPoolListPage(cur CapacityPoolList, getNextPage func(context.Context, CapacityPoolList) (CapacityPoolList, error)) CapacityPoolListPage { - return CapacityPoolListPage{ - fn: getNextPage, - cpl: cur, - } -} - -// CapacityPoolPatch capacity pool patch resource -type CapacityPoolPatch struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // PoolPatchProperties - Capacity pool properties - *PoolPatchProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for CapacityPoolPatch. -func (cpp CapacityPoolPatch) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cpp.Location != nil { - objectMap["location"] = cpp.Location - } - if cpp.Tags != nil { - objectMap["tags"] = cpp.Tags - } - if cpp.PoolPatchProperties != nil { - objectMap["properties"] = cpp.PoolPatchProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for CapacityPoolPatch struct. -func (cpp *CapacityPoolPatch) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cpp.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cpp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cpp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cpp.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cpp.Tags = tags - } - case "properties": - if v != nil { - var poolPatchProperties PoolPatchProperties - err = json.Unmarshal(*v, &poolPatchProperties) - if err != nil { - return err - } - cpp.PoolPatchProperties = &poolPatchProperties - } - } - } - - return nil -} - -// CheckAvailabilityResponse information regarding availability of a resource. -type CheckAvailabilityResponse struct { - autorest.Response `json:"-"` - // IsAvailable - true indicates name is valid and available. false indicates the name is invalid, unavailable, or both. - IsAvailable *bool `json:"isAvailable,omitempty"` - // Reason - Invalid indicates the name provided does not match Azure App Service naming requirements. AlreadyExists indicates that the name is already in use and is therefore unavailable. Possible values include: 'InAvailabilityReasonTypeInvalid', 'InAvailabilityReasonTypeAlreadyExists' - Reason InAvailabilityReasonType `json:"reason,omitempty"` - // Message - If reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that resource name is already in use, and direct them to select a different name. - Message *string `json:"message,omitempty"` -} - -// CloudError an error response from the service. -type CloudError struct { - // Error - Cloud error body. - Error *CloudErrorBody `json:"error,omitempty"` -} - -// CloudErrorBody an error response from the service. -type CloudErrorBody struct { - // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. - Code *string `json:"code,omitempty"` - // Message - A message describing the error, intended to be suitable for display in a user interface. - Message *string `json:"message,omitempty"` -} - -// DailySchedule daily Schedule properties -type DailySchedule struct { - // SnapshotsToKeep - Daily snapshot count to keep - SnapshotsToKeep *int32 `json:"snapshotsToKeep,omitempty"` - // Hour - Indicates which hour in UTC timezone a snapshot should be taken - Hour *int32 `json:"hour,omitempty"` - // Minute - Indicates which minute snapshot should be taken - Minute *int32 `json:"minute,omitempty"` - // UsedBytes - Resource size in bytes, current storage usage for the volume in bytes - UsedBytes *int64 `json:"usedBytes,omitempty"` -} - -// Dimension dimension of blobs, possibly be blob type or access tier. -type Dimension struct { - // Name - Display name of dimension. - Name *string `json:"name,omitempty"` - // DisplayName - Display name of dimension. - DisplayName *string `json:"displayName,omitempty"` -} - -// ExportPolicyRule volume Export Policy Rule -type ExportPolicyRule struct { - // RuleIndex - Order index - RuleIndex *int32 `json:"ruleIndex,omitempty"` - // UnixReadOnly - Read only access - UnixReadOnly *bool `json:"unixReadOnly,omitempty"` - // UnixReadWrite - Read and write access - UnixReadWrite *bool `json:"unixReadWrite,omitempty"` - // Kerberos5ReadOnly - Kerberos5 Read only access. To be use with swagger version 2020-05-01 or later - Kerberos5ReadOnly *bool `json:"kerberos5ReadOnly,omitempty"` - // Kerberos5ReadWrite - Kerberos5 Read and write access. To be use with swagger version 2020-05-01 or later - Kerberos5ReadWrite *bool `json:"kerberos5ReadWrite,omitempty"` - // Kerberos5iReadOnly - Kerberos5i Read only access. To be use with swagger version 2020-05-01 or later - Kerberos5iReadOnly *bool `json:"kerberos5iReadOnly,omitempty"` - // Kerberos5iReadWrite - Kerberos5i Read and write access. To be use with swagger version 2020-05-01 or later - Kerberos5iReadWrite *bool `json:"kerberos5iReadWrite,omitempty"` - // Kerberos5pReadOnly - Kerberos5p Read only access. To be use with swagger version 2020-05-01 or later - Kerberos5pReadOnly *bool `json:"kerberos5pReadOnly,omitempty"` - // Kerberos5pReadWrite - Kerberos5p Read and write access. To be use with swagger version 2020-05-01 or later - Kerberos5pReadWrite *bool `json:"kerberos5pReadWrite,omitempty"` - // Cifs - Allows CIFS protocol - Cifs *bool `json:"cifs,omitempty"` - // Nfsv3 - Allows NFSv3 protocol. Enable only for NFSv3 type volumes - Nfsv3 *bool `json:"nfsv3,omitempty"` - // Nfsv41 - Allows NFSv4.1 protocol. Enable only for NFSv4.1 type volumes - Nfsv41 *bool `json:"nfsv41,omitempty"` - // AllowedClients - Client ingress specification as comma separated string with IPv4 CIDRs, IPv4 host addresses and host names - AllowedClients *string `json:"allowedClients,omitempty"` - // HasRootAccess - Has root access to volume - HasRootAccess *bool `json:"hasRootAccess,omitempty"` - // ChownMode - This parameter specifies who is authorized to change the ownership of a file. restricted - Only root user can change the ownership of the file. unrestricted - Non-root users can change ownership of files that they own. Possible values include: 'ChownModeRestricted', 'ChownModeUnrestricted' - ChownMode ChownMode `json:"chownMode,omitempty"` -} - -// FilePathAvailabilityRequest file path availability request content - availability is based on the name -// and the subnetId. -type FilePathAvailabilityRequest struct { - // Name - File path to verify. - Name *string `json:"name,omitempty"` - // SubnetID - The Azure Resource URI for a delegated subnet. Must have the delegation Microsoft.NetApp/volumes - SubnetID *string `json:"subnetId,omitempty"` -} - -// HourlySchedule hourly Schedule properties -type HourlySchedule struct { - // SnapshotsToKeep - Hourly snapshot count to keep - SnapshotsToKeep *int32 `json:"snapshotsToKeep,omitempty"` - // Minute - Indicates which minute snapshot should be taken - Minute *int32 `json:"minute,omitempty"` - // UsedBytes - Resource size in bytes, current storage usage for the volume in bytes - UsedBytes *int64 `json:"usedBytes,omitempty"` -} - -// LdapSearchScopeOpt LDAP search scope -type LdapSearchScopeOpt struct { - // UserDN - This specifies the user DN, which overrides the base DN for user lookups. - UserDN *string `json:"userDN,omitempty"` - // GroupDN - This specifies the group DN, which overrides the base DN for group lookups. - GroupDN *string `json:"groupDN,omitempty"` - // GroupMembershipFilter - This specifies the custom LDAP search filter to be used when looking up group membership from LDAP server. - GroupMembershipFilter *string `json:"groupMembershipFilter,omitempty"` -} - -// LogSpecification log Definition of a single resource metric. -type LogSpecification struct { - // Name - Name of log specification. - Name *string `json:"name,omitempty"` - // DisplayName - Display name of log specification. - DisplayName *string `json:"displayName,omitempty"` -} - -// MetricSpecification metric specification of operation. -type MetricSpecification struct { - // Name - Name of metric specification. - Name *string `json:"name,omitempty"` - // DisplayName - Display name of metric specification. - DisplayName *string `json:"displayName,omitempty"` - // DisplayDescription - Display description of metric specification. - DisplayDescription *string `json:"displayDescription,omitempty"` - // Unit - Unit could be Bytes or Count. - Unit *string `json:"unit,omitempty"` - // SupportedAggregationTypes - Support metric aggregation type. - SupportedAggregationTypes *[]MetricAggregationType `json:"supportedAggregationTypes,omitempty"` - // SupportedTimeGrainTypes - The supported time grain types for the metrics. - SupportedTimeGrainTypes *[]string `json:"supportedTimeGrainTypes,omitempty"` - // InternalMetricName - The internal metric name. - InternalMetricName *string `json:"internalMetricName,omitempty"` - // EnableRegionalMdmAccount - Whether or not the service is using regional MDM accounts. - EnableRegionalMdmAccount *bool `json:"enableRegionalMdmAccount,omitempty"` - // SourceMdmAccount - The source MDM account. - SourceMdmAccount *string `json:"sourceMdmAccount,omitempty"` - // SourceMdmNamespace - The source MDM namespace. - SourceMdmNamespace *string `json:"sourceMdmNamespace,omitempty"` - // Dimensions - Dimensions of blobs, including blob type and access tier. - Dimensions *[]Dimension `json:"dimensions,omitempty"` - // AggregationType - Aggregation type could be Average. - AggregationType *string `json:"aggregationType,omitempty"` - // FillGapWithZero - The property to decide fill gap with zero or not. - FillGapWithZero *bool `json:"fillGapWithZero,omitempty"` - // Category - The category this metric specification belong to, could be Capacity. - Category *string `json:"category,omitempty"` - // ResourceIDDimensionNameOverride - Account Resource Id. - ResourceIDDimensionNameOverride *string `json:"resourceIdDimensionNameOverride,omitempty"` - // IsInternal - Whether the metric is internal. - IsInternal *bool `json:"isInternal,omitempty"` -} - -// MonthlySchedule monthly Schedule properties -type MonthlySchedule struct { - // SnapshotsToKeep - Monthly snapshot count to keep - SnapshotsToKeep *int32 `json:"snapshotsToKeep,omitempty"` - // DaysOfMonth - Indicates which days of the month snapshot should be taken. A comma delimited string. - DaysOfMonth *string `json:"daysOfMonth,omitempty"` - // Hour - Indicates which hour in UTC timezone a snapshot should be taken - Hour *int32 `json:"hour,omitempty"` - // Minute - Indicates which minute snapshot should be taken - Minute *int32 `json:"minute,omitempty"` - // UsedBytes - Resource size in bytes, current storage usage for the volume in bytes - UsedBytes *int64 `json:"usedBytes,omitempty"` -} - -// MountTarget mount Target -type MountTarget struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // MountTargetProperties - Mount Target Properties - *MountTargetProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for MountTarget. -func (mt MountTarget) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mt.Location != nil { - objectMap["location"] = mt.Location - } - if mt.Tags != nil { - objectMap["tags"] = mt.Tags - } - if mt.MountTargetProperties != nil { - objectMap["properties"] = mt.MountTargetProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for MountTarget struct. -func (mt *MountTarget) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - mt.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - mt.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - mt.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - mt.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - mt.Tags = tags - } - case "properties": - if v != nil { - var mountTargetProperties MountTargetProperties - err = json.Unmarshal(*v, &mountTargetProperties) - if err != nil { - return err - } - mt.MountTargetProperties = &mountTargetProperties - } - } - } - - return nil -} - -// MountTargetProperties mount target properties -type MountTargetProperties struct { - // MountTargetID - READ-ONLY; UUID v4 used to identify the MountTarget - MountTargetID *string `json:"mountTargetId,omitempty"` - // FileSystemID - UUID v4 used to identify the MountTarget - FileSystemID *string `json:"fileSystemId,omitempty"` - // IPAddress - READ-ONLY; The mount target's IPv4 address - IPAddress *string `json:"ipAddress,omitempty"` - // SmbServerFqdn - The SMB server's Fully Qualified Domain Name, FQDN - SmbServerFqdn *string `json:"smbServerFqdn,omitempty"` -} - -// MarshalJSON is the custom marshaler for MountTargetProperties. -func (mtp MountTargetProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mtp.FileSystemID != nil { - objectMap["fileSystemId"] = mtp.FileSystemID - } - if mtp.SmbServerFqdn != nil { - objectMap["smbServerFqdn"] = mtp.SmbServerFqdn - } - return json.Marshal(objectMap) -} - -// Operation microsoft.NetApp REST API operation definition. -type Operation struct { - // Name - Operation name: {provider}/{resource}/{operation} - Name *string `json:"name,omitempty"` - // Display - Display metadata associated with the operation. - Display *OperationDisplay `json:"display,omitempty"` - // Origin - The origin of operations. - Origin *string `json:"origin,omitempty"` - // OperationProperties - Properties of operation, include metric specifications. - *OperationProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for Operation. -func (o Operation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if o.Name != nil { - objectMap["name"] = o.Name - } - if o.Display != nil { - objectMap["display"] = o.Display - } - if o.Origin != nil { - objectMap["origin"] = o.Origin - } - if o.OperationProperties != nil { - objectMap["properties"] = o.OperationProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Operation struct. -func (o *Operation) 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 - } - o.Name = &name - } - case "display": - if v != nil { - var display OperationDisplay - err = json.Unmarshal(*v, &display) - if err != nil { - return err - } - o.Display = &display - } - case "origin": - if v != nil { - var origin string - err = json.Unmarshal(*v, &origin) - if err != nil { - return err - } - o.Origin = &origin - } - case "properties": - if v != nil { - var operationProperties OperationProperties - err = json.Unmarshal(*v, &operationProperties) - if err != nil { - return err - } - o.OperationProperties = &operationProperties - } - } - } - - return nil -} - -// OperationDisplay display metadata associated with the operation. -type OperationDisplay struct { - // Provider - Service provider: Microsoft NetApp. - Provider *string `json:"provider,omitempty"` - // Resource - Resource on which the operation is performed etc. - Resource *string `json:"resource,omitempty"` - // Operation - Type of operation: get, read, delete, etc. - Operation *string `json:"operation,omitempty"` - // Description - Operation description. - Description *string `json:"description,omitempty"` -} - -// OperationListResult result of the request to list Cloud Volume 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 Storage operations supported by the Storage resource provider. - Value *[]Operation `json:"value,omitempty"` -} - -// OperationProperties properties of operation, include metric specifications. -type OperationProperties struct { - // ServiceSpecification - One property of operation, include metric specifications. - ServiceSpecification *ServiceSpecification `json:"serviceSpecification,omitempty"` -} - -// PlacementKeyValuePairs application specific parameters for the placement of volumes in the volume group -type PlacementKeyValuePairs struct { - // Key - Key for an application specific parameter for the placement of volumes in the volume group - Key *string `json:"key,omitempty"` - // Value - Value for an application specific parameter for the placement of volumes in the volume group - Value *string `json:"value,omitempty"` -} - -// PoolChangeRequest pool change request -type PoolChangeRequest struct { - // NewPoolResourceID - Resource id of the pool to move volume to - NewPoolResourceID *string `json:"newPoolResourceId,omitempty"` -} - -// PoolPatchProperties patchable pool properties -type PoolPatchProperties struct { - // Size - Provisioned size of the pool (in bytes). Allowed values are in 1TiB chunks (value must be multiply of 4398046511104). - Size *int64 `json:"size,omitempty"` - // QosType - The qos type of the pool. Possible values include: 'QosTypeAuto', 'QosTypeManual' - QosType QosType `json:"qosType,omitempty"` -} - -// PoolProperties pool properties -type PoolProperties struct { - // PoolID - READ-ONLY; UUID v4 used to identify the Pool - PoolID *string `json:"poolId,omitempty"` - // Size - Provisioned size of the pool (in bytes). Allowed values are in 1TiB chunks (value must be multiply of 4398046511104). - Size *int64 `json:"size,omitempty"` - // ServiceLevel - Possible values include: 'ServiceLevelStandard', 'ServiceLevelPremium', 'ServiceLevelUltra', 'ServiceLevelStandardZRS' - ServiceLevel ServiceLevel `json:"serviceLevel,omitempty"` - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` - // TotalThroughputMibps - READ-ONLY; Total throughput of pool in Mibps - TotalThroughputMibps *float64 `json:"totalThroughputMibps,omitempty"` - // UtilizedThroughputMibps - READ-ONLY; Utilized throughput of pool in Mibps - UtilizedThroughputMibps *float64 `json:"utilizedThroughputMibps,omitempty"` - // QosType - The qos type of the pool. Possible values include: 'QosTypeAuto', 'QosTypeManual' - QosType QosType `json:"qosType,omitempty"` - // CoolAccess - If enabled (true) the pool can contain cool Access enabled volumes. - CoolAccess *bool `json:"coolAccess,omitempty"` - // EncryptionType - Encryption type of the capacity pool, set encryption type for data at rest for this pool and all volumes in it. This value can only be set when creating new pool. Possible values include: 'EncryptionTypeSingle', 'EncryptionTypeDouble' - EncryptionType EncryptionType `json:"encryptionType,omitempty"` -} - -// MarshalJSON is the custom marshaler for PoolProperties. -func (pp PoolProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pp.Size != nil { - objectMap["size"] = pp.Size - } - if pp.ServiceLevel != "" { - objectMap["serviceLevel"] = pp.ServiceLevel - } - if pp.QosType != "" { - objectMap["qosType"] = pp.QosType - } - if pp.CoolAccess != nil { - objectMap["coolAccess"] = pp.CoolAccess - } - if pp.EncryptionType != "" { - objectMap["encryptionType"] = pp.EncryptionType - } - return json.Marshal(objectMap) -} - -// PoolsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PoolsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PoolsClient) (CapacityPool, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PoolsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PoolsCreateOrUpdateFuture.Result. -func (future *PoolsCreateOrUpdateFuture) result(client PoolsClient) (cp CapacityPool, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.PoolsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cp.Response.Response, err = future.GetResult(sender); err == nil && cp.Response.Response.StatusCode != http.StatusNoContent { - cp, err = client.CreateOrUpdateResponder(cp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsCreateOrUpdateFuture", "Result", cp.Response.Response, "Failure responding to request") - } - } - return -} - -// PoolsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type PoolsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PoolsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PoolsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PoolsDeleteFuture.Result. -func (future *PoolsDeleteFuture) result(client PoolsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.PoolsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PoolsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type PoolsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PoolsClient) (CapacityPool, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PoolsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PoolsUpdateFuture.Result. -func (future *PoolsUpdateFuture) result(client PoolsClient) (cp CapacityPool, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.PoolsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cp.Response.Response, err = future.GetResult(sender); err == nil && cp.Response.Response.StatusCode != http.StatusNoContent { - cp, err = client.UpdateResponder(cp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsUpdateFuture", "Result", cp.Response.Response, "Failure responding to request") - } - } - return -} - -// ProxyResource the resource model definition for a Azure Resource Manager proxy resource. It will not -// have tags and a location -type ProxyResource struct { - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ProxyResource. -func (pr ProxyResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// QuotaAvailabilityRequest quota availability request content. -type QuotaAvailabilityRequest struct { - // Name - Name of the resource to verify. - Name *string `json:"name,omitempty"` - // Type - Resource type used for verification. Possible values include: 'CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccounts', 'CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPools', 'CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumes', 'CheckQuotaNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumessnapshots' - Type CheckQuotaNameResourceTypes `json:"type,omitempty"` - // ResourceGroup - Resource group name. - ResourceGroup *string `json:"resourceGroup,omitempty"` -} - -// ReplicationObject replication properties -type ReplicationObject struct { - // ReplicationID - Id - ReplicationID *string `json:"replicationId,omitempty"` - // EndpointType - Indicates whether the local volume is the source or destination for the Volume Replication. Possible values include: 'EndpointTypeSrc', 'EndpointTypeDst' - EndpointType EndpointType `json:"endpointType,omitempty"` - // ReplicationSchedule - Schedule. Possible values include: 'ReplicationSchedule10minutely', 'ReplicationScheduleHourly', 'ReplicationScheduleDaily' - ReplicationSchedule ReplicationSchedule `json:"replicationSchedule,omitempty"` - // RemoteVolumeResourceID - The resource ID of the remote volume. - RemoteVolumeResourceID *string `json:"remoteVolumeResourceId,omitempty"` - // RemoteVolumeRegion - The remote region for the other end of the Volume Replication. - RemoteVolumeRegion *string `json:"remoteVolumeRegion,omitempty"` -} - -// ReplicationStatus replication status -type ReplicationStatus struct { - autorest.Response `json:"-"` - // Healthy - Replication health check - Healthy *bool `json:"healthy,omitempty"` - // RelationshipStatus - Status of the mirror relationship. Possible values include: 'RelationshipStatusIdle', 'RelationshipStatusTransferring' - RelationshipStatus RelationshipStatus `json:"relationshipStatus,omitempty"` - // MirrorState - The status of the replication. Possible values include: 'MirrorStateUninitialized', 'MirrorStateMirrored', 'MirrorStateBroken' - MirrorState MirrorState `json:"mirrorState,omitempty"` - // TotalProgress - The progress of the replication - TotalProgress *string `json:"totalProgress,omitempty"` - // ErrorMessage - Displays error message if the replication is in an error state - ErrorMessage *string `json:"errorMessage,omitempty"` -} - -// Resource common fields that are returned in the response for all Azure Resource Manager resources -type Resource struct { - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ResourceIdentity identity for the resource. -type ResourceIdentity struct { - // PrincipalID - READ-ONLY; Object id of the identity resource - PrincipalID *string `json:"principalId,omitempty"` - // TenantID - READ-ONLY; The tenant id of the resource - TenantID *string `json:"tenantId,omitempty"` - // Type - Type of Identity. Supported values are: 'None', 'SystemAssigned' - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceIdentity. -func (ri ResourceIdentity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ri.Type != nil { - objectMap["type"] = ri.Type - } - return json.Marshal(objectMap) -} - -// ResourceNameAvailabilityRequest resource name availability request content. -type ResourceNameAvailabilityRequest struct { - // Name - Resource name to verify. - Name *string `json:"name,omitempty"` - // Type - Resource type used for verification. Possible values include: 'CheckNameResourceTypesMicrosoftNetAppnetAppAccounts', 'CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPools', 'CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumes', 'CheckNameResourceTypesMicrosoftNetAppnetAppAccountscapacityPoolsvolumessnapshots' - Type CheckNameResourceTypes `json:"type,omitempty"` - // ResourceGroup - Resource group name. - ResourceGroup *string `json:"resourceGroup,omitempty"` -} - -// RestoreStatus restore status -type RestoreStatus struct { - autorest.Response `json:"-"` - // Healthy - READ-ONLY; Restore health status - Healthy *bool `json:"healthy,omitempty"` - // RelationshipStatus - READ-ONLY; Status of the restore SnapMirror relationship. Possible values include: 'RelationshipStatusIdle', 'RelationshipStatusTransferring' - RelationshipStatus RelationshipStatus `json:"relationshipStatus,omitempty"` - // MirrorState - READ-ONLY; The status of the restore. Possible values include: 'MirrorStateUninitialized', 'MirrorStateMirrored', 'MirrorStateBroken' - MirrorState MirrorState `json:"mirrorState,omitempty"` - // UnhealthyReason - READ-ONLY; Reason for the unhealthy restore relationship - UnhealthyReason *string `json:"unhealthyReason,omitempty"` - // ErrorMessage - READ-ONLY; Displays error message if the restore is in an error state - ErrorMessage *string `json:"errorMessage,omitempty"` - // TotalTransferBytes - READ-ONLY; Displays the total bytes transferred - TotalTransferBytes *int64 `json:"totalTransferBytes,omitempty"` -} - -// MarshalJSON is the custom marshaler for RestoreStatus. -func (rs RestoreStatus) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ServiceSpecification one property of operation, include metric specifications. -type ServiceSpecification struct { - // MetricSpecifications - Metric specifications of operation. - MetricSpecifications *[]MetricSpecification `json:"metricSpecifications,omitempty"` - // LogSpecifications - Log specification of operation. - LogSpecifications *[]LogSpecification `json:"logSpecifications,omitempty"` -} - -// Snapshot snapshot of a Volume -type Snapshot struct { - autorest.Response `json:"-"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // SnapshotProperties - Snapshot Properties - *SnapshotProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for Snapshot. -func (s Snapshot) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if s.Location != nil { - objectMap["location"] = s.Location - } - if s.SnapshotProperties != nil { - objectMap["properties"] = s.SnapshotProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Snapshot struct. -func (s *Snapshot) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - s.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - s.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - s.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - s.Type = &typeVar - } - case "properties": - if v != nil { - var snapshotProperties SnapshotProperties - err = json.Unmarshal(*v, &snapshotProperties) - if err != nil { - return err - } - s.SnapshotProperties = &snapshotProperties - } - } - } - - return nil -} - -// SnapshotPoliciesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotPoliciesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotPoliciesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotPoliciesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotPoliciesDeleteFuture.Result. -func (future *SnapshotPoliciesDeleteFuture) result(client SnapshotPoliciesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SnapshotPoliciesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SnapshotPoliciesList list of Snapshot Policies -type SnapshotPoliciesList struct { - autorest.Response `json:"-"` - // Value - A list of snapshot policies - Value *[]SnapshotPolicy `json:"value,omitempty"` -} - -// SnapshotPoliciesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotPoliciesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotPoliciesClient) (SnapshotPolicy, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotPoliciesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotPoliciesUpdateFuture.Result. -func (future *SnapshotPoliciesUpdateFuture) result(client SnapshotPoliciesClient) (sp SnapshotPolicy, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SnapshotPoliciesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sp.Response.Response, err = future.GetResult(sender); err == nil && sp.Response.Response.StatusCode != http.StatusNoContent { - sp, err = client.UpdateResponder(sp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesUpdateFuture", "Result", sp.Response.Response, "Failure responding to request") - } - } - return -} - -// SnapshotPolicy snapshot policy information -type SnapshotPolicy struct { - autorest.Response `json:"-"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // SnapshotPolicyProperties - Snapshot policy Properties - *SnapshotPolicyProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for SnapshotPolicy. -func (sp SnapshotPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sp.Location != nil { - objectMap["location"] = sp.Location - } - if sp.Tags != nil { - objectMap["tags"] = sp.Tags - } - if sp.SnapshotPolicyProperties != nil { - objectMap["properties"] = sp.SnapshotPolicyProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SnapshotPolicy struct. -func (sp *SnapshotPolicy) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - sp.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sp.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - sp.Tags = tags - } - case "properties": - if v != nil { - var snapshotPolicyProperties SnapshotPolicyProperties - err = json.Unmarshal(*v, &snapshotPolicyProperties) - if err != nil { - return err - } - sp.SnapshotPolicyProperties = &snapshotPolicyProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - sp.SystemData = &systemData - } - } - } - - return nil -} - -// SnapshotPolicyDetails snapshot policy properties -type SnapshotPolicyDetails struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // SnapshotPolicyProperties - Snapshot policy Properties - *SnapshotPolicyProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for SnapshotPolicyDetails. -func (spd SnapshotPolicyDetails) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if spd.Location != nil { - objectMap["location"] = spd.Location - } - if spd.Tags != nil { - objectMap["tags"] = spd.Tags - } - if spd.SnapshotPolicyProperties != nil { - objectMap["properties"] = spd.SnapshotPolicyProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SnapshotPolicyDetails struct. -func (spd *SnapshotPolicyDetails) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - spd.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - spd.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - spd.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - spd.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - spd.Tags = tags - } - case "properties": - if v != nil { - var snapshotPolicyProperties SnapshotPolicyProperties - err = json.Unmarshal(*v, &snapshotPolicyProperties) - if err != nil { - return err - } - spd.SnapshotPolicyProperties = &snapshotPolicyProperties - } - } - } - - return nil -} - -// SnapshotPolicyPatch snapshot policy Details for create and update -type SnapshotPolicyPatch struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // SnapshotPolicyProperties - Snapshot Policy properties - *SnapshotPolicyProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for SnapshotPolicyPatch. -func (spp SnapshotPolicyPatch) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if spp.Location != nil { - objectMap["location"] = spp.Location - } - if spp.Tags != nil { - objectMap["tags"] = spp.Tags - } - if spp.SnapshotPolicyProperties != nil { - objectMap["properties"] = spp.SnapshotPolicyProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SnapshotPolicyPatch struct. -func (spp *SnapshotPolicyPatch) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - spp.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - spp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - spp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - spp.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - spp.Tags = tags - } - case "properties": - if v != nil { - var snapshotPolicyProperties SnapshotPolicyProperties - err = json.Unmarshal(*v, &snapshotPolicyProperties) - if err != nil { - return err - } - spp.SnapshotPolicyProperties = &snapshotPolicyProperties - } - } - } - - return nil -} - -// SnapshotPolicyProperties snapshot policy properties -type SnapshotPolicyProperties struct { - // HourlySchedule - Schedule for hourly snapshots - HourlySchedule *HourlySchedule `json:"hourlySchedule,omitempty"` - // DailySchedule - Schedule for daily snapshots - DailySchedule *DailySchedule `json:"dailySchedule,omitempty"` - // WeeklySchedule - Schedule for weekly snapshots - WeeklySchedule *WeeklySchedule `json:"weeklySchedule,omitempty"` - // MonthlySchedule - Schedule for monthly snapshots - MonthlySchedule *MonthlySchedule `json:"monthlySchedule,omitempty"` - // Enabled - The property to decide policy is enabled or not - Enabled *bool `json:"enabled,omitempty"` - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for SnapshotPolicyProperties. -func (spp SnapshotPolicyProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if spp.HourlySchedule != nil { - objectMap["hourlySchedule"] = spp.HourlySchedule - } - if spp.DailySchedule != nil { - objectMap["dailySchedule"] = spp.DailySchedule - } - if spp.WeeklySchedule != nil { - objectMap["weeklySchedule"] = spp.WeeklySchedule - } - if spp.MonthlySchedule != nil { - objectMap["monthlySchedule"] = spp.MonthlySchedule - } - if spp.Enabled != nil { - objectMap["enabled"] = spp.Enabled - } - return json.Marshal(objectMap) -} - -// SnapshotPolicyVolumeList volumes associated with snapshot policy -type SnapshotPolicyVolumeList struct { - autorest.Response `json:"-"` - // Value - List of volumes - Value *[]Volume `json:"value,omitempty"` -} - -// SnapshotProperties snapshot properties -type SnapshotProperties struct { - // SnapshotID - READ-ONLY; UUID v4 used to identify the Snapshot - SnapshotID *string `json:"snapshotId,omitempty"` - // Created - READ-ONLY; The creation date of the snapshot - Created *date.Time `json:"created,omitempty"` - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for SnapshotProperties. -func (sp SnapshotProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// SnapshotRestoreFiles restore payload for Single File Snapshot Restore -type SnapshotRestoreFiles struct { - // FilePaths - List of files to be restored - FilePaths *[]string `json:"filePaths,omitempty"` - // DestinationPath - Destination folder where the files will be restored - DestinationPath *string `json:"destinationPath,omitempty"` -} - -// SnapshotsCreateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotsCreateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotsClient) (Snapshot, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotsCreateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotsCreateFuture.Result. -func (future *SnapshotsCreateFuture) result(client SnapshotsClient) (s Snapshot, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsCreateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SnapshotsCreateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.CreateResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsCreateFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// SnapshotsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotsDeleteFuture.Result. -func (future *SnapshotsDeleteFuture) result(client SnapshotsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SnapshotsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SnapshotsList list of Snapshots -type SnapshotsList struct { - autorest.Response `json:"-"` - // Value - A list of Snapshots - Value *[]Snapshot `json:"value,omitempty"` -} - -// SnapshotsRestoreFilesFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotsRestoreFilesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotsRestoreFilesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotsRestoreFilesFuture.Result. -func (future *SnapshotsRestoreFilesFuture) result(client SnapshotsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsRestoreFilesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SnapshotsRestoreFilesFuture") - return - } - ar.Response = future.Response() - return -} - -// SnapshotsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SnapshotsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SnapshotsClient) (Snapshot, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SnapshotsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SnapshotsUpdateFuture.Result. -func (future *SnapshotsUpdateFuture) result(client SnapshotsClient) (s Snapshot, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SnapshotsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.UpdateResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsUpdateFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// SubscriptionQuotaItem information regarding Subscription Quota Item. -type SubscriptionQuotaItem struct { - autorest.Response `json:"-"` - // SubscriptionQuotaItemProperties - SubscriptionQuotaItem properties - *SubscriptionQuotaItemProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubscriptionQuotaItem. -func (sqi SubscriptionQuotaItem) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sqi.SubscriptionQuotaItemProperties != nil { - objectMap["properties"] = sqi.SubscriptionQuotaItemProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SubscriptionQuotaItem struct. -func (sqi *SubscriptionQuotaItem) 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 subscriptionQuotaItemProperties SubscriptionQuotaItemProperties - err = json.Unmarshal(*v, &subscriptionQuotaItemProperties) - if err != nil { - return err - } - sqi.SubscriptionQuotaItemProperties = &subscriptionQuotaItemProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - sqi.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sqi.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sqi.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sqi.Type = &typeVar - } - } - } - - return nil -} - -// SubscriptionQuotaItemList list of Subscription Quota Items -type SubscriptionQuotaItemList struct { - autorest.Response `json:"-"` - // Value - A list of SubscriptionQuotaItems - Value *[]SubscriptionQuotaItem `json:"value,omitempty"` -} - -// SubscriptionQuotaItemProperties subscriptionQuotaItem Properties -type SubscriptionQuotaItemProperties struct { - // Current - READ-ONLY; The current quota value. - Current *int32 `json:"current,omitempty"` - // Default - READ-ONLY; The default quota value. - Default *int32 `json:"default,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubscriptionQuotaItemProperties. -func (sqip SubscriptionQuotaItemProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// SubvolumeInfo subvolume Information properties -type SubvolumeInfo struct { - autorest.Response `json:"-"` - // SubvolumeProperties - Subvolume Properties - *SubvolumeProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubvolumeInfo. -func (si SubvolumeInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if si.SubvolumeProperties != nil { - objectMap["properties"] = si.SubvolumeProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SubvolumeInfo struct. -func (si *SubvolumeInfo) 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 subvolumeProperties SubvolumeProperties - err = json.Unmarshal(*v, &subvolumeProperties) - if err != nil { - return err - } - si.SubvolumeProperties = &subvolumeProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - si.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - si.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - si.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - si.Type = &typeVar - } - } - } - - return nil -} - -// SubvolumeModel result of the post subvolume and action is to get metadata of the subvolume. -type SubvolumeModel struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // SubvolumeModelProperties - It represents the minimal properties of the subvolume. - *SubvolumeModelProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubvolumeModel. -func (sm SubvolumeModel) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sm.SubvolumeModelProperties != nil { - objectMap["properties"] = sm.SubvolumeModelProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SubvolumeModel struct. -func (sm *SubvolumeModel) 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 "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sm.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sm.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sm.Type = &typeVar - } - case "properties": - if v != nil { - var subvolumeModelProperties SubvolumeModelProperties - err = json.Unmarshal(*v, &subvolumeModelProperties) - if err != nil { - return err - } - sm.SubvolumeModelProperties = &subvolumeModelProperties - } - } - } - - return nil -} - -// SubvolumeModelProperties properties which represents actual subvolume model which is stored as a file in -// the system. -type SubvolumeModelProperties struct { - // Path - Path to the subvolume - Path *string `json:"path,omitempty"` - // ParentPath - Path to the parent subvolume - ParentPath *string `json:"parentPath,omitempty"` - // Size - Size of subvolume - Size *int64 `json:"size,omitempty"` - // BytesUsed - Bytes used - BytesUsed *int64 `json:"bytesUsed,omitempty"` - // Permissions - Permissions of the subvolume - Permissions *string `json:"permissions,omitempty"` - // CreationTimeStamp - Creation time and date - CreationTimeStamp *date.Time `json:"creationTimeStamp,omitempty"` - // AccessedTimeStamp - Most recent access time and date - AccessedTimeStamp *date.Time `json:"accessedTimeStamp,omitempty"` - // ModifiedTimeStamp - Most recent modification time and date - ModifiedTimeStamp *date.Time `json:"modifiedTimeStamp,omitempty"` - // ChangedTimeStamp - Most recent change time and date - ChangedTimeStamp *date.Time `json:"changedTimeStamp,omitempty"` - // ProvisioningState - Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// SubvolumePatchParams parameters with which a subvolume can be updated -type SubvolumePatchParams struct { - // Size - Truncate subvolume to the provided size in bytes - Size *int64 `json:"size,omitempty"` - // Path - path to the subvolume - Path *string `json:"path,omitempty"` -} - -// SubvolumePatchRequest subvolume Patch Request properties -type SubvolumePatchRequest struct { - // SubvolumePatchParams - Subvolume Properties - *SubvolumePatchParams `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubvolumePatchRequest. -func (spr SubvolumePatchRequest) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if spr.SubvolumePatchParams != nil { - objectMap["properties"] = spr.SubvolumePatchParams - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SubvolumePatchRequest struct. -func (spr *SubvolumePatchRequest) 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 subvolumePatchParams SubvolumePatchParams - err = json.Unmarshal(*v, &subvolumePatchParams) - if err != nil { - return err - } - spr.SubvolumePatchParams = &subvolumePatchParams - } - } - } - - return nil -} - -// SubvolumeProperties this represents path associated with the subvolume -type SubvolumeProperties struct { - // Path - Path to the subvolume - Path *string `json:"path,omitempty"` - // Size - Truncate subvolume to the provided size in bytes - Size *int64 `json:"size,omitempty"` - // ParentPath - parent path to the subvolume - ParentPath *string `json:"parentPath,omitempty"` - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubvolumeProperties. -func (sp SubvolumeProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sp.Path != nil { - objectMap["path"] = sp.Path - } - if sp.Size != nil { - objectMap["size"] = sp.Size - } - if sp.ParentPath != nil { - objectMap["parentPath"] = sp.ParentPath - } - return json.Marshal(objectMap) -} - -// SubvolumesCreateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SubvolumesCreateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubvolumesClient) (SubvolumeInfo, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubvolumesCreateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubvolumesCreateFuture.Result. -func (future *SubvolumesCreateFuture) result(client SubvolumesClient) (si SubvolumeInfo, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesCreateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - si.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SubvolumesCreateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if si.Response.Response, err = future.GetResult(sender); err == nil && si.Response.Response.StatusCode != http.StatusNoContent { - si, err = client.CreateResponder(si.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesCreateFuture", "Result", si.Response.Response, "Failure responding to request") - } - } - return -} - -// SubvolumesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SubvolumesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubvolumesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubvolumesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubvolumesDeleteFuture.Result. -func (future *SubvolumesDeleteFuture) result(client SubvolumesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SubvolumesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SubvolumesGetMetadataFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SubvolumesGetMetadataFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubvolumesClient) (SubvolumeModel, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubvolumesGetMetadataFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubvolumesGetMetadataFuture.Result. -func (future *SubvolumesGetMetadataFuture) result(client SubvolumesClient) (sm SubvolumeModel, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesGetMetadataFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sm.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SubvolumesGetMetadataFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sm.Response.Response, err = future.GetResult(sender); err == nil && sm.Response.Response.StatusCode != http.StatusNoContent { - sm, err = client.GetMetadataResponder(sm.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesGetMetadataFuture", "Result", sm.Response.Response, "Failure responding to request") - } - } - return -} - -// SubvolumesList list of Subvolumes -type SubvolumesList struct { - autorest.Response `json:"-"` - // Value - A list of Subvolumes - Value *[]SubvolumeInfo `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// SubvolumesListIterator provides access to a complete listing of SubvolumeInfo values. -type SubvolumesListIterator struct { - i int - page SubvolumesListPage -} - -// NextWithContext 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 *SubvolumesListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubvolumesListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SubvolumesListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SubvolumesListIterator) 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 SubvolumesListIterator) Response() SubvolumesList { - 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 SubvolumesListIterator) Value() SubvolumeInfo { - if !iter.page.NotDone() { - return SubvolumeInfo{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SubvolumesListIterator type. -func NewSubvolumesListIterator(page SubvolumesListPage) SubvolumesListIterator { - return SubvolumesListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sl SubvolumesList) IsEmpty() bool { - return sl.Value == nil || len(*sl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sl SubvolumesList) hasNextLink() bool { - return sl.NextLink != nil && len(*sl.NextLink) != 0 -} - -// subvolumesListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sl SubvolumesList) subvolumesListPreparer(ctx context.Context) (*http.Request, error) { - if !sl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sl.NextLink))) -} - -// SubvolumesListPage contains a page of SubvolumeInfo values. -type SubvolumesListPage struct { - fn func(context.Context, SubvolumesList) (SubvolumesList, error) - sl SubvolumesList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SubvolumesListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubvolumesListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sl) - if err != nil { - return err - } - page.sl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SubvolumesListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SubvolumesListPage) NotDone() bool { - return !page.sl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SubvolumesListPage) Response() SubvolumesList { - return page.sl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SubvolumesListPage) Values() []SubvolumeInfo { - if page.sl.IsEmpty() { - return nil - } - return *page.sl.Value -} - -// Creates a new instance of the SubvolumesListPage type. -func NewSubvolumesListPage(cur SubvolumesList, getNextPage func(context.Context, SubvolumesList) (SubvolumesList, error)) SubvolumesListPage { - return SubvolumesListPage{ - fn: getNextPage, - sl: cur, - } -} - -// SubvolumesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SubvolumesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubvolumesClient) (SubvolumeInfo, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubvolumesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubvolumesUpdateFuture.Result. -func (future *SubvolumesUpdateFuture) result(client SubvolumesClient) (si SubvolumeInfo, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - si.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.SubvolumesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if si.Response.Response, err = future.GetResult(sender); err == nil && si.Response.Response.StatusCode != http.StatusNoContent { - si, err = client.UpdateResponder(si.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesUpdateFuture", "Result", si.Response.Response, "Failure responding to request") - } - } - return -} - -// SystemData metadata pertaining to creation and last modification of the resource. -type SystemData struct { - // CreatedBy - The identity that created the resource. - CreatedBy *string `json:"createdBy,omitempty"` - // CreatedByType - The type of identity that created the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' - CreatedByType CreatedByType `json:"createdByType,omitempty"` - // CreatedAt - The timestamp of resource creation (UTC). - CreatedAt *date.Time `json:"createdAt,omitempty"` - // LastModifiedBy - The identity that last modified the resource. - LastModifiedBy *string `json:"lastModifiedBy,omitempty"` - // LastModifiedByType - The type of identity that last modified the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' - LastModifiedByType CreatedByType `json:"lastModifiedByType,omitempty"` - // LastModifiedAt - The timestamp of resource last modification (UTC) - LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` -} - -// TrackedResource the resource model definition for an Azure Resource Manager tracked top level resource -// which has 'tags' and a 'location' -type TrackedResource struct { - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` - // Location - The geo-location where the resource lives - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - 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.Tags != nil { - objectMap["tags"] = tr.Tags - } - if tr.Location != nil { - objectMap["location"] = tr.Location - } - return json.Marshal(objectMap) -} - -// Vault vault information -type Vault struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // VaultProperties - Vault Properties - *VaultProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for Vault. -func (vVar Vault) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vVar.Location != nil { - objectMap["location"] = vVar.Location - } - if vVar.VaultProperties != nil { - objectMap["properties"] = vVar.VaultProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Vault struct. -func (vVar *Vault) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vVar.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vVar.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vVar.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vVar.Type = &typeVar - } - case "properties": - if v != nil { - var vaultProperties VaultProperties - err = json.Unmarshal(*v, &vaultProperties) - if err != nil { - return err - } - vVar.VaultProperties = &vaultProperties - } - } - } - - return nil -} - -// VaultList list of Vaults -type VaultList struct { - autorest.Response `json:"-"` - // Value - A list of vaults - Value *[]Vault `json:"value,omitempty"` -} - -// VaultProperties vault properties -type VaultProperties struct { - // VaultName - Vault Name - VaultName *string `json:"vaultName,omitempty"` -} - -// Volume volume resource -type Volume struct { - autorest.Response `json:"-"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // VolumeProperties - Volume properties - *VolumeProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for Volume. -func (vVar Volume) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vVar.Location != nil { - objectMap["location"] = vVar.Location - } - if vVar.Tags != nil { - objectMap["tags"] = vVar.Tags - } - if vVar.VolumeProperties != nil { - objectMap["properties"] = vVar.VolumeProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Volume struct. -func (vVar *Volume) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vVar.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vVar.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vVar.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vVar.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vVar.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vVar.Tags = tags - } - case "properties": - if v != nil { - var volumeProperties VolumeProperties - err = json.Unmarshal(*v, &volumeProperties) - if err != nil { - return err - } - vVar.VolumeProperties = &volumeProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - vVar.SystemData = &systemData - } - } - } - - return nil -} - -// VolumeBackupProperties volume Backup Properties -type VolumeBackupProperties struct { - // BackupPolicyID - Backup Policy Resource ID - BackupPolicyID *string `json:"backupPolicyId,omitempty"` - // PolicyEnforced - Policy Enforced - PolicyEnforced *bool `json:"policyEnforced,omitempty"` - // VaultID - Vault Resource ID - VaultID *string `json:"vaultId,omitempty"` - // BackupEnabled - Backup Enabled - BackupEnabled *bool `json:"backupEnabled,omitempty"` -} - -// VolumeBackups volume details using the backup policy -type VolumeBackups struct { - // VolumeName - Volume name - VolumeName *string `json:"volumeName,omitempty"` - // BackupsCount - Total count of backups for volume - BackupsCount *int32 `json:"backupsCount,omitempty"` - // PolicyEnabled - Policy enabled - PolicyEnabled *bool `json:"policyEnabled,omitempty"` -} - -// VolumeGroup volume group resource -type VolumeGroup struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // VolumeGroupListProperties - Volume group properties - *VolumeGroupListProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for VolumeGroup. -func (vg VolumeGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vg.Location != nil { - objectMap["location"] = vg.Location - } - if vg.Tags != nil { - objectMap["tags"] = vg.Tags - } - if vg.VolumeGroupListProperties != nil { - objectMap["properties"] = vg.VolumeGroupListProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VolumeGroup struct. -func (vg *VolumeGroup) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vg.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vg.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vg.Tags = tags - } - case "properties": - if v != nil { - var volumeGroupListProperties VolumeGroupListProperties - err = json.Unmarshal(*v, &volumeGroupListProperties) - if err != nil { - return err - } - vg.VolumeGroupListProperties = &volumeGroupListProperties - } - } - } - - return nil -} - -// VolumeGroupDetails volume group resource for create -type VolumeGroupDetails struct { - autorest.Response `json:"-"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // VolumeGroupProperties - Volume group properties - *VolumeGroupProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for VolumeGroupDetails. -func (vgd VolumeGroupDetails) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vgd.Location != nil { - objectMap["location"] = vgd.Location - } - if vgd.Tags != nil { - objectMap["tags"] = vgd.Tags - } - if vgd.VolumeGroupProperties != nil { - objectMap["properties"] = vgd.VolumeGroupProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VolumeGroupDetails struct. -func (vgd *VolumeGroupDetails) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vgd.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vgd.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vgd.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vgd.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vgd.Tags = tags - } - case "properties": - if v != nil { - var volumeGroupProperties VolumeGroupProperties - err = json.Unmarshal(*v, &volumeGroupProperties) - if err != nil { - return err - } - vgd.VolumeGroupProperties = &volumeGroupProperties - } - } - } - - return nil -} - -// VolumeGroupList list of volume group resources -type VolumeGroupList struct { - autorest.Response `json:"-"` - // Value - List of volume Groups - Value *[]VolumeGroup `json:"value,omitempty"` -} - -// VolumeGroupListProperties volume group properties -type VolumeGroupListProperties struct { - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` - // GroupMetaData - Volume group details - GroupMetaData *VolumeGroupMetaData `json:"groupMetaData,omitempty"` -} - -// MarshalJSON is the custom marshaler for VolumeGroupListProperties. -func (vglp VolumeGroupListProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vglp.GroupMetaData != nil { - objectMap["groupMetaData"] = vglp.GroupMetaData - } - return json.Marshal(objectMap) -} - -// VolumeGroupMetaData volume group properties -type VolumeGroupMetaData struct { - // GroupDescription - Group Description - GroupDescription *string `json:"groupDescription,omitempty"` - // ApplicationType - Application Type. Possible values include: 'ApplicationTypeSAPHANA' - ApplicationType ApplicationType `json:"applicationType,omitempty"` - // ApplicationIdentifier - Application specific identifier - ApplicationIdentifier *string `json:"applicationIdentifier,omitempty"` - // GlobalPlacementRules - Application specific placement rules for the volume group - GlobalPlacementRules *[]PlacementKeyValuePairs `json:"globalPlacementRules,omitempty"` - // DeploymentSpecID - Application specific identifier of deployment rules for the volume group - DeploymentSpecID *string `json:"deploymentSpecId,omitempty"` - // VolumesCount - READ-ONLY; Number of volumes in volume group - VolumesCount *int64 `json:"volumesCount,omitempty"` -} - -// MarshalJSON is the custom marshaler for VolumeGroupMetaData. -func (vgmd VolumeGroupMetaData) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vgmd.GroupDescription != nil { - objectMap["groupDescription"] = vgmd.GroupDescription - } - if vgmd.ApplicationType != "" { - objectMap["applicationType"] = vgmd.ApplicationType - } - if vgmd.ApplicationIdentifier != nil { - objectMap["applicationIdentifier"] = vgmd.ApplicationIdentifier - } - if vgmd.GlobalPlacementRules != nil { - objectMap["globalPlacementRules"] = vgmd.GlobalPlacementRules - } - if vgmd.DeploymentSpecID != nil { - objectMap["deploymentSpecId"] = vgmd.DeploymentSpecID - } - return json.Marshal(objectMap) -} - -// VolumeGroupProperties volume group properties -type VolumeGroupProperties struct { - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` - // GroupMetaData - Volume group details - GroupMetaData *VolumeGroupMetaData `json:"groupMetaData,omitempty"` - // Volumes - List of volumes from group - Volumes *[]VolumeGroupVolumeProperties `json:"volumes,omitempty"` -} - -// MarshalJSON is the custom marshaler for VolumeGroupProperties. -func (vgp VolumeGroupProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vgp.GroupMetaData != nil { - objectMap["groupMetaData"] = vgp.GroupMetaData - } - if vgp.Volumes != nil { - objectMap["volumes"] = vgp.Volumes - } - return json.Marshal(objectMap) -} - -// VolumeGroupsCreateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VolumeGroupsCreateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumeGroupsClient) (VolumeGroupDetails, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumeGroupsCreateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumeGroupsCreateFuture.Result. -func (future *VolumeGroupsCreateFuture) result(client VolumeGroupsClient) (vgd VolumeGroupDetails, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsCreateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vgd.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumeGroupsCreateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vgd.Response.Response, err = future.GetResult(sender); err == nil && vgd.Response.Response.StatusCode != http.StatusNoContent { - vgd, err = client.CreateResponder(vgd.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsCreateFuture", "Result", vgd.Response.Response, "Failure responding to request") - } - } - return -} - -// VolumeGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VolumeGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumeGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumeGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumeGroupsDeleteFuture.Result. -func (future *VolumeGroupsDeleteFuture) result(client VolumeGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumeGroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VolumeGroupVolumeProperties volume resource -type VolumeGroupVolumeProperties struct { - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // VolumeProperties - Volume properties - *VolumeProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for VolumeGroupVolumeProperties. -func (vgvp VolumeGroupVolumeProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vgvp.Name != nil { - objectMap["name"] = vgvp.Name - } - if vgvp.Tags != nil { - objectMap["tags"] = vgvp.Tags - } - if vgvp.VolumeProperties != nil { - objectMap["properties"] = vgvp.VolumeProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VolumeGroupVolumeProperties struct. -func (vgvp *VolumeGroupVolumeProperties) 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 "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vgvp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vgvp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vgvp.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vgvp.Tags = tags - } - case "properties": - if v != nil { - var volumeProperties VolumeProperties - err = json.Unmarshal(*v, &volumeProperties) - if err != nil { - return err - } - vgvp.VolumeProperties = &volumeProperties - } - } - } - - return nil -} - -// VolumeList list of volume resources -type VolumeList struct { - autorest.Response `json:"-"` - // Value - List of volumes - Value *[]Volume `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VolumeListIterator provides access to a complete listing of Volume values. -type VolumeListIterator struct { - i int - page VolumeListPage -} - -// NextWithContext 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 *VolumeListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumeListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VolumeListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VolumeListIterator) 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 VolumeListIterator) Response() VolumeList { - 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 VolumeListIterator) Value() Volume { - if !iter.page.NotDone() { - return Volume{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VolumeListIterator type. -func NewVolumeListIterator(page VolumeListPage) VolumeListIterator { - return VolumeListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vl VolumeList) IsEmpty() bool { - return vl.Value == nil || len(*vl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vl VolumeList) hasNextLink() bool { - return vl.NextLink != nil && len(*vl.NextLink) != 0 -} - -// volumeListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vl VolumeList) volumeListPreparer(ctx context.Context) (*http.Request, error) { - if !vl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vl.NextLink))) -} - -// VolumeListPage contains a page of Volume values. -type VolumeListPage struct { - fn func(context.Context, VolumeList) (VolumeList, error) - vl VolumeList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VolumeListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumeListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vl) - if err != nil { - return err - } - page.vl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VolumeListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VolumeListPage) NotDone() bool { - return !page.vl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VolumeListPage) Response() VolumeList { - return page.vl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VolumeListPage) Values() []Volume { - if page.vl.IsEmpty() { - return nil - } - return *page.vl.Value -} - -// Creates a new instance of the VolumeListPage type. -func NewVolumeListPage(cur VolumeList, getNextPage func(context.Context, VolumeList) (VolumeList, error)) VolumeListPage { - return VolumeListPage{ - fn: getNextPage, - vl: cur, - } -} - -// VolumePatch volume patch resource -type VolumePatch struct { - // Location - Resource location - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // VolumePatchProperties - Patchable volume properties - *VolumePatchProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for VolumePatch. -func (vp VolumePatch) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vp.Location != nil { - objectMap["location"] = vp.Location - } - if vp.Tags != nil { - objectMap["tags"] = vp.Tags - } - if vp.VolumePatchProperties != nil { - objectMap["properties"] = vp.VolumePatchProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VolumePatch struct. -func (vp *VolumePatch) 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 "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vp.Location = &location - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vp.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vp.Tags = tags - } - case "properties": - if v != nil { - var volumePatchProperties VolumePatchProperties - err = json.Unmarshal(*v, &volumePatchProperties) - if err != nil { - return err - } - vp.VolumePatchProperties = &volumePatchProperties - } - } - } - - return nil -} - -// VolumePatchProperties patchable volume properties -type VolumePatchProperties struct { - // ServiceLevel - Possible values include: 'ServiceLevelStandard', 'ServiceLevelPremium', 'ServiceLevelUltra', 'ServiceLevelStandardZRS' - ServiceLevel ServiceLevel `json:"serviceLevel,omitempty"` - // UsageThreshold - Maximum storage quota allowed for a file system in bytes. This is a soft quota used for alerting only. Minimum size is 100 GiB. Upper limit is 100TiB. Specified in bytes. - UsageThreshold *int64 `json:"usageThreshold,omitempty"` - // ExportPolicy - Set of export policy rules - ExportPolicy *VolumePatchPropertiesExportPolicy `json:"exportPolicy,omitempty"` - ThroughputMibps *float64 `json:"throughputMibps,omitempty"` - // DataProtection - DataProtection type volumes include an object containing details of the replication - DataProtection *VolumePatchPropertiesDataProtection `json:"dataProtection,omitempty"` - // IsDefaultQuotaEnabled - Specifies if default quota is enabled for the volume. - IsDefaultQuotaEnabled *bool `json:"isDefaultQuotaEnabled,omitempty"` - // DefaultUserQuotaInKiBs - Default user quota for volume in KiBs. If isDefaultQuotaEnabled is set, the minimum value of 4 KiBs applies . - DefaultUserQuotaInKiBs *int64 `json:"defaultUserQuotaInKiBs,omitempty"` - // DefaultGroupQuotaInKiBs - Default group quota for volume in KiBs. If isDefaultQuotaEnabled is set, the minimum value of 4 KiBs applies. - DefaultGroupQuotaInKiBs *int64 `json:"defaultGroupQuotaInKiBs,omitempty"` - // UnixPermissions - UNIX permissions for NFS volume accepted in octal 4 digit format. First digit selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission for the owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users in the same group. the fourth for other users not in the group. 0755 - gives read/write/execute permissions to owner and read/execute to group and other users. - UnixPermissions *string `json:"unixPermissions,omitempty"` -} - -// VolumePatchPropertiesDataProtection dataProtection type volumes include an object containing details of -// the replication -type VolumePatchPropertiesDataProtection struct { - // Backup - Backup Properties - Backup *VolumeBackupProperties `json:"backup,omitempty"` - // Snapshot - Snapshot properties. - Snapshot *VolumeSnapshotProperties `json:"snapshot,omitempty"` -} - -// VolumePatchPropertiesExportPolicy set of export policy rules -type VolumePatchPropertiesExportPolicy struct { - // Rules - Export policy rule - Rules *[]ExportPolicyRule `json:"rules,omitempty"` -} - -// VolumeProperties volume properties -type VolumeProperties struct { - // FileSystemID - READ-ONLY; Unique FileSystem Identifier. - FileSystemID *string `json:"fileSystemId,omitempty"` - // CreationToken - A unique file path for the volume. Used when creating mount targets - CreationToken *string `json:"creationToken,omitempty"` - // ServiceLevel - Possible values include: 'ServiceLevelStandard', 'ServiceLevelPremium', 'ServiceLevelUltra', 'ServiceLevelStandardZRS' - ServiceLevel ServiceLevel `json:"serviceLevel,omitempty"` - // UsageThreshold - Maximum storage quota allowed for a file system in bytes. This is a soft quota used for alerting only. Minimum size is 100 GiB. Upper limit is 100TiB. Specified in bytes. - UsageThreshold *int64 `json:"usageThreshold,omitempty"` - // ExportPolicy - Set of export policy rules - ExportPolicy *VolumePropertiesExportPolicy `json:"exportPolicy,omitempty"` - // ProtocolTypes - Set of protocol types, default NFSv3, CIFS for SMB protocol - ProtocolTypes *[]string `json:"protocolTypes,omitempty"` - // ProvisioningState - READ-ONLY; Azure lifecycle management - ProvisioningState *string `json:"provisioningState,omitempty"` - // SnapshotID - UUID v4 or resource identifier used to identify the Snapshot. - SnapshotID *string `json:"snapshotId,omitempty"` - // BackupID - UUID v4 or resource identifier used to identify the Backup. - BackupID *string `json:"backupId,omitempty"` - // BaremetalTenantID - READ-ONLY; Unique Baremetal Tenant Identifier. - BaremetalTenantID *string `json:"baremetalTenantId,omitempty"` - // SubnetID - The Azure Resource URI for a delegated subnet. Must have the delegation Microsoft.NetApp/volumes - SubnetID *string `json:"subnetId,omitempty"` - // NetworkFeatures - Basic network, or Standard features available to the volume. Possible values include: 'NetworkFeaturesBasic', 'NetworkFeaturesStandard' - NetworkFeatures NetworkFeatures `json:"networkFeatures,omitempty"` - // NetworkSiblingSetID - READ-ONLY; Network Sibling Set ID for the the group of volumes sharing networking resources. - NetworkSiblingSetID *string `json:"networkSiblingSetId,omitempty"` - // StorageToNetworkProximity - READ-ONLY; Provides storage to network proximity information for the volume. Possible values include: 'VolumeStorageToNetworkProximityDefault', 'VolumeStorageToNetworkProximityT1', 'VolumeStorageToNetworkProximityT2' - StorageToNetworkProximity VolumeStorageToNetworkProximity `json:"storageToNetworkProximity,omitempty"` - // MountTargets - READ-ONLY; List of mount targets - MountTargets *[]MountTargetProperties `json:"mountTargets,omitempty"` - // VolumeType - What type of volume is this. For destination volumes in Cross Region Replication, set type to DataProtection - VolumeType *string `json:"volumeType,omitempty"` - // DataProtection - DataProtection type volumes include an object containing details of the replication - DataProtection *VolumePropertiesDataProtection `json:"dataProtection,omitempty"` - // IsRestoring - Restoring - IsRestoring *bool `json:"isRestoring,omitempty"` - // SnapshotDirectoryVisible - If enabled (true) the volume will contain a read-only snapshot directory which provides access to each of the volume's snapshots (default to true). - SnapshotDirectoryVisible *bool `json:"snapshotDirectoryVisible,omitempty"` - // KerberosEnabled - Describe if a volume is KerberosEnabled. To be use with swagger version 2020-05-01 or later - KerberosEnabled *bool `json:"kerberosEnabled,omitempty"` - // SecurityStyle - The security style of volume, default unix, defaults to ntfs for dual protocol or CIFS protocol. Possible values include: 'SecurityStyleNtfs', 'SecurityStyleUnix' - SecurityStyle SecurityStyle `json:"securityStyle,omitempty"` - // SmbEncryption - Enables encryption for in-flight smb3 data. Only applicable for SMB/DualProtocol volume. To be used with swagger version 2020-08-01 or later - SmbEncryption *bool `json:"smbEncryption,omitempty"` - // SmbContinuouslyAvailable - Enables continuously available share property for smb volume. Only applicable for SMB volume - SmbContinuouslyAvailable *bool `json:"smbContinuouslyAvailable,omitempty"` - ThroughputMibps *float64 `json:"throughputMibps,omitempty"` - // EncryptionKeySource - Encryption Key Source. Possible values are: 'Microsoft.NetApp' - EncryptionKeySource *string `json:"encryptionKeySource,omitempty"` - // LdapEnabled - Specifies whether LDAP is enabled or not for a given NFS volume. - LdapEnabled *bool `json:"ldapEnabled,omitempty"` - // CoolAccess - Specifies whether Cool Access(tiering) is enabled for the volume. - CoolAccess *bool `json:"coolAccess,omitempty"` - // CoolnessPeriod - Specifies the number of days after which data that is not accessed by clients will be tiered. - CoolnessPeriod *int32 `json:"coolnessPeriod,omitempty"` - // UnixPermissions - UNIX permissions for NFS volume accepted in octal 4 digit format. First digit selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission for the owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users in the same group. the fourth for other users not in the group. 0755 - gives read/write/execute permissions to owner and read/execute to group and other users. - UnixPermissions *string `json:"unixPermissions,omitempty"` - // CloneProgress - READ-ONLY; When a volume is being restored from another volume's snapshot, will show the percentage completion of this cloning process. When this value is empty/null there is no cloning process currently happening on this volume. This value will update every 5 minutes during cloning. - CloneProgress *int32 `json:"cloneProgress,omitempty"` - // AvsDataStore - Specifies whether the volume is enabled for Azure VMware Solution (AVS) datastore purpose. Possible values include: 'AvsDataStoreEnabled', 'AvsDataStoreDisabled' - AvsDataStore AvsDataStore `json:"avsDataStore,omitempty"` - // IsDefaultQuotaEnabled - Specifies if default quota is enabled for the volume. - IsDefaultQuotaEnabled *bool `json:"isDefaultQuotaEnabled,omitempty"` - // DefaultUserQuotaInKiBs - Default user quota for volume in KiBs. If isDefaultQuotaEnabled is set, the minimum value of 4 KiBs applies . - DefaultUserQuotaInKiBs *int64 `json:"defaultUserQuotaInKiBs,omitempty"` - // DefaultGroupQuotaInKiBs - Default group quota for volume in KiBs. If isDefaultQuotaEnabled is set, the minimum value of 4 KiBs applies. - DefaultGroupQuotaInKiBs *int64 `json:"defaultGroupQuotaInKiBs,omitempty"` - // MaximumNumberOfFiles - READ-ONLY; Maximum number of files allowed. Needs a service request in order to be changed. Only allowed to be changed if volume quota is more than 4TiB. - MaximumNumberOfFiles *int64 `json:"maximumNumberOfFiles,omitempty"` - // VolumeGroupName - READ-ONLY; Volume Group Name - VolumeGroupName *string `json:"volumeGroupName,omitempty"` - // CapacityPoolResourceID - Pool Resource Id used in case of creating a volume through volume group - CapacityPoolResourceID *string `json:"capacityPoolResourceId,omitempty"` - // ProximityPlacementGroup - Proximity placement group associated with the volume - ProximityPlacementGroup *string `json:"proximityPlacementGroup,omitempty"` - // T2Network - READ-ONLY; T2 network information - T2Network *string `json:"t2Network,omitempty"` - // VolumeSpecName - Volume spec name is the application specific designation or identifier for the particular volume in a volume group for e.g. data, log - VolumeSpecName *string `json:"volumeSpecName,omitempty"` - // PlacementRules - Application specific placement rules for the particular volume - PlacementRules *[]PlacementKeyValuePairs `json:"placementRules,omitempty"` - // EnableSubvolumes - Flag indicating whether subvolume operations are enabled on the volume. Possible values include: 'EnableSubvolumesEnabled', 'EnableSubvolumesDisabled' - EnableSubvolumes EnableSubvolumes `json:"enableSubvolumes,omitempty"` -} - -// MarshalJSON is the custom marshaler for VolumeProperties. -func (vp VolumeProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vp.CreationToken != nil { - objectMap["creationToken"] = vp.CreationToken - } - if vp.ServiceLevel != "" { - objectMap["serviceLevel"] = vp.ServiceLevel - } - if vp.UsageThreshold != nil { - objectMap["usageThreshold"] = vp.UsageThreshold - } - if vp.ExportPolicy != nil { - objectMap["exportPolicy"] = vp.ExportPolicy - } - if vp.ProtocolTypes != nil { - objectMap["protocolTypes"] = vp.ProtocolTypes - } - if vp.SnapshotID != nil { - objectMap["snapshotId"] = vp.SnapshotID - } - if vp.BackupID != nil { - objectMap["backupId"] = vp.BackupID - } - if vp.SubnetID != nil { - objectMap["subnetId"] = vp.SubnetID - } - if vp.NetworkFeatures != "" { - objectMap["networkFeatures"] = vp.NetworkFeatures - } - if vp.VolumeType != nil { - objectMap["volumeType"] = vp.VolumeType - } - if vp.DataProtection != nil { - objectMap["dataProtection"] = vp.DataProtection - } - if vp.IsRestoring != nil { - objectMap["isRestoring"] = vp.IsRestoring - } - if vp.SnapshotDirectoryVisible != nil { - objectMap["snapshotDirectoryVisible"] = vp.SnapshotDirectoryVisible - } - if vp.KerberosEnabled != nil { - objectMap["kerberosEnabled"] = vp.KerberosEnabled - } - if vp.SecurityStyle != "" { - objectMap["securityStyle"] = vp.SecurityStyle - } - if vp.SmbEncryption != nil { - objectMap["smbEncryption"] = vp.SmbEncryption - } - if vp.SmbContinuouslyAvailable != nil { - objectMap["smbContinuouslyAvailable"] = vp.SmbContinuouslyAvailable - } - if vp.ThroughputMibps != nil { - objectMap["throughputMibps"] = vp.ThroughputMibps - } - if vp.EncryptionKeySource != nil { - objectMap["encryptionKeySource"] = vp.EncryptionKeySource - } - if vp.LdapEnabled != nil { - objectMap["ldapEnabled"] = vp.LdapEnabled - } - if vp.CoolAccess != nil { - objectMap["coolAccess"] = vp.CoolAccess - } - if vp.CoolnessPeriod != nil { - objectMap["coolnessPeriod"] = vp.CoolnessPeriod - } - if vp.UnixPermissions != nil { - objectMap["unixPermissions"] = vp.UnixPermissions - } - if vp.AvsDataStore != "" { - objectMap["avsDataStore"] = vp.AvsDataStore - } - if vp.IsDefaultQuotaEnabled != nil { - objectMap["isDefaultQuotaEnabled"] = vp.IsDefaultQuotaEnabled - } - if vp.DefaultUserQuotaInKiBs != nil { - objectMap["defaultUserQuotaInKiBs"] = vp.DefaultUserQuotaInKiBs - } - if vp.DefaultGroupQuotaInKiBs != nil { - objectMap["defaultGroupQuotaInKiBs"] = vp.DefaultGroupQuotaInKiBs - } - if vp.CapacityPoolResourceID != nil { - objectMap["capacityPoolResourceId"] = vp.CapacityPoolResourceID - } - if vp.ProximityPlacementGroup != nil { - objectMap["proximityPlacementGroup"] = vp.ProximityPlacementGroup - } - if vp.VolumeSpecName != nil { - objectMap["volumeSpecName"] = vp.VolumeSpecName - } - if vp.PlacementRules != nil { - objectMap["placementRules"] = vp.PlacementRules - } - if vp.EnableSubvolumes != "" { - objectMap["enableSubvolumes"] = vp.EnableSubvolumes - } - return json.Marshal(objectMap) -} - -// VolumePropertiesDataProtection dataProtection type volumes include an object containing details of the -// replication -type VolumePropertiesDataProtection struct { - // Backup - Backup Properties - Backup *VolumeBackupProperties `json:"backup,omitempty"` - // Replication - Replication properties - Replication *ReplicationObject `json:"replication,omitempty"` - // Snapshot - Snapshot properties. - Snapshot *VolumeSnapshotProperties `json:"snapshot,omitempty"` -} - -// VolumePropertiesExportPolicy set of export policy rules -type VolumePropertiesExportPolicy struct { - // Rules - Export policy rule - Rules *[]ExportPolicyRule `json:"rules,omitempty"` -} - -// VolumeRevert revert a volume to the snapshot -type VolumeRevert struct { - // SnapshotID - Resource id of the snapshot - SnapshotID *string `json:"snapshotId,omitempty"` -} - -// VolumesAuthorizeReplicationFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VolumesAuthorizeReplicationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesAuthorizeReplicationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesAuthorizeReplicationFuture.Result. -func (future *VolumesAuthorizeReplicationFuture) result(client VolumesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesAuthorizeReplicationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesAuthorizeReplicationFuture") - return - } - ar.Response = future.Response() - return -} - -// VolumesBreakReplicationFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VolumesBreakReplicationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesBreakReplicationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesBreakReplicationFuture.Result. -func (future *VolumesBreakReplicationFuture) result(client VolumesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesBreakReplicationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesBreakReplicationFuture") - return - } - ar.Response = future.Response() - return -} - -// VolumesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VolumesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (Volume, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesCreateOrUpdateFuture.Result. -func (future *VolumesCreateOrUpdateFuture) result(client VolumesClient) (vVar Volume, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vVar.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vVar.Response.Response, err = future.GetResult(sender); err == nil && vVar.Response.Response.StatusCode != http.StatusNoContent { - vVar, err = client.CreateOrUpdateResponder(vVar.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesCreateOrUpdateFuture", "Result", vVar.Response.Response, "Failure responding to request") - } - } - return -} - -// VolumesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VolumesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesDeleteFuture.Result. -func (future *VolumesDeleteFuture) result(client VolumesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VolumesDeleteReplicationFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VolumesDeleteReplicationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesDeleteReplicationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesDeleteReplicationFuture.Result. -func (future *VolumesDeleteReplicationFuture) result(client VolumesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesDeleteReplicationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesDeleteReplicationFuture") - return - } - ar.Response = future.Response() - return -} - -// VolumeSnapshotProperties volume Snapshot Properties -type VolumeSnapshotProperties struct { - // SnapshotPolicyID - Snapshot Policy ResourceId - SnapshotPolicyID *string `json:"snapshotPolicyId,omitempty"` -} - -// VolumesPoolChangeFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VolumesPoolChangeFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesPoolChangeFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesPoolChangeFuture.Result. -func (future *VolumesPoolChangeFuture) result(client VolumesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesPoolChangeFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesPoolChangeFuture") - return - } - ar.Response = future.Response() - return -} - -// VolumesReInitializeReplicationFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VolumesReInitializeReplicationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesReInitializeReplicationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesReInitializeReplicationFuture.Result. -func (future *VolumesReInitializeReplicationFuture) result(client VolumesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesReInitializeReplicationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesReInitializeReplicationFuture") - return - } - ar.Response = future.Response() - return -} - -// VolumesResyncReplicationFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VolumesResyncReplicationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesResyncReplicationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesResyncReplicationFuture.Result. -func (future *VolumesResyncReplicationFuture) result(client VolumesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesResyncReplicationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesResyncReplicationFuture") - return - } - ar.Response = future.Response() - return -} - -// VolumesRevertFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VolumesRevertFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesRevertFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesRevertFuture.Result. -func (future *VolumesRevertFuture) result(client VolumesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesRevertFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesRevertFuture") - return - } - ar.Response = future.Response() - return -} - -// VolumesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VolumesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VolumesClient) (Volume, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VolumesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VolumesUpdateFuture.Result. -func (future *VolumesUpdateFuture) result(client VolumesClient) (vVar Volume, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vVar.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("netapp.VolumesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vVar.Response.Response, err = future.GetResult(sender); err == nil && vVar.Response.Response.StatusCode != http.StatusNoContent { - vVar, err = client.UpdateResponder(vVar.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesUpdateFuture", "Result", vVar.Response.Response, "Failure responding to request") - } - } - return -} - -// WeeklySchedule weekly Schedule properties, make a snapshot every week at a specific day or days -type WeeklySchedule struct { - // SnapshotsToKeep - Weekly snapshot count to keep - SnapshotsToKeep *int32 `json:"snapshotsToKeep,omitempty"` - // Day - Indicates which weekdays snapshot should be taken, accepts a comma separated list of week day names in english - Day *string `json:"day,omitempty"` - // Hour - Indicates which hour in UTC timezone a snapshot should be taken - Hour *int32 `json:"hour,omitempty"` - // Minute - Indicates which minute snapshot should be taken - Minute *int32 `json:"minute,omitempty"` - // UsedBytes - Resource size in bytes, current storage usage for the volume in bytes - UsedBytes *int64 `json:"usedBytes,omitempty"` -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/operations.go deleted file mode 100644 index d903fa2473a3..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/operations.go +++ /dev/null @@ -1,98 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// OperationsClient is the microsoft NetApp Files Azure Resource Provider specification -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 using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List lists all of the available Microsoft.NetApp Rest API operations -func (client OperationsClient) List(ctx context.Context) (result OperationListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.OperationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.OperationsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.OperationsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.NetApp/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 client.Send(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, - 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/netapp/mgmt/2021-10-01/netapp/pools.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/pools.go deleted file mode 100644 index 67284b542dfa..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/pools.go +++ /dev/null @@ -1,550 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PoolsClient is the microsoft NetApp Files Azure Resource Provider specification -type PoolsClient struct { - BaseClient -} - -// NewPoolsClient creates an instance of the PoolsClient client. -func NewPoolsClient(subscriptionID string) PoolsClient { - return NewPoolsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPoolsClientWithBaseURI creates an instance of the PoolsClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewPoolsClientWithBaseURI(baseURI string, subscriptionID string) PoolsClient { - return PoolsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or Update a capacity pool -// Parameters: -// body - capacity pool object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -func (client PoolsClient) CreateOrUpdate(ctx context.Context, body CapacityPool, resourceGroupName string, accountName string, poolName string) (result PoolsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PoolsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Location", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.PoolProperties", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "body.PoolProperties.PoolID", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.PoolProperties.PoolID", Name: validation.MaxLength, Rule: 36, Chain: nil}, - {Target: "body.PoolProperties.PoolID", Name: validation.MinLength, Rule: 36, Chain: nil}, - {Target: "body.PoolProperties.PoolID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$`, Chain: nil}, - }}, - {Target: "body.PoolProperties.Size", Name: validation.Null, Rule: true, Chain: nil}, - }}}}, - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.PoolsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, body, resourceGroupName, accountName, poolName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PoolsClient) CreateOrUpdatePreparer(ctx context.Context, body CapacityPool, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Etag = nil - body.Type = nil - body.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}", pathParameters), - autorest.WithJSON(body), - 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 PoolsClient) CreateOrUpdateSender(req *http.Request) (future PoolsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PoolsClient) CreateOrUpdateResponder(resp *http.Response) (result CapacityPool, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the specified capacity pool -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -func (client PoolsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, poolName string) (result PoolsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PoolsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.PoolsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, poolName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PoolsClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}", 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 PoolsClient) DeleteSender(req *http.Request) (future PoolsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PoolsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get details of the specified capacity pool -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -func (client PoolsClient) Get(ctx context.Context, resourceGroupName string, accountName string, poolName string) (result CapacityPool, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PoolsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.PoolsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName, poolName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PoolsClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}", 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 PoolsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PoolsClient) GetResponder(resp *http.Response) (result CapacityPool, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all capacity pools in the NetApp Account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client PoolsClient) List(ctx context.Context, resourceGroupName string, accountName string) (result CapacityPoolListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PoolsClient.List") - defer func() { - sc := -1 - if result.cpl.Response.Response != nil { - sc = result.cpl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.PoolsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.cpl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "List", resp, "Failure sending request") - return - } - - result.cpl, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "List", resp, "Failure responding to request") - return - } - if result.cpl.hasNextLink() && result.cpl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PoolsClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools", 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 PoolsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PoolsClient) ListResponder(resp *http.Response) (result CapacityPoolList, err error) { - err = autorest.Respond( - resp, - 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 PoolsClient) listNextResults(ctx context.Context, lastResults CapacityPoolList) (result CapacityPoolList, err error) { - req, err := lastResults.capacityPoolListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "netapp.PoolsClient", "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, "netapp.PoolsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PoolsClient) ListComplete(ctx context.Context, resourceGroupName string, accountName string) (result CapacityPoolListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PoolsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, accountName) - return -} - -// Update patch the specified capacity pool -// Parameters: -// body - capacity pool object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -func (client PoolsClient) Update(ctx context.Context, body CapacityPoolPatch, resourceGroupName string, accountName string, poolName string) (result PoolsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PoolsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.PoolsClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, body, resourceGroupName, accountName, poolName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.PoolsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client PoolsClient) UpdatePreparer(ctx context.Context, body CapacityPoolPatch, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}", pathParameters), - autorest.WithJSON(body), - 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 PoolsClient) UpdateSender(req *http.Request) (future PoolsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client PoolsClient) UpdateResponder(resp *http.Response) (result CapacityPool, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/netapp/mgmt/2021-10-01/netapp/resource.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/resource.go deleted file mode 100644 index c2e42cc2ad2b..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/resource.go +++ /dev/null @@ -1,284 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ResourceClient is the microsoft NetApp Files Azure Resource Provider specification -type ResourceClient struct { - BaseClient -} - -// NewResourceClient creates an instance of the ResourceClient client. -func NewResourceClient(subscriptionID string) ResourceClient { - return NewResourceClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewResourceClientWithBaseURI creates an instance of the ResourceClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewResourceClientWithBaseURI(baseURI string, subscriptionID string) ResourceClient { - return ResourceClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckFilePathAvailability check if a file path is available. -// Parameters: -// body - file path availability request. -// location - the location -func (client ResourceClient) CheckFilePathAvailability(ctx context.Context, body FilePathAvailabilityRequest, location string) (result CheckAvailabilityResponse, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceClient.CheckFilePathAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.SubnetID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.ResourceClient", "CheckFilePathAvailability", err.Error()) - } - - req, err := client.CheckFilePathAvailabilityPreparer(ctx, body, location) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceClient", "CheckFilePathAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckFilePathAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.ResourceClient", "CheckFilePathAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckFilePathAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceClient", "CheckFilePathAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckFilePathAvailabilityPreparer prepares the CheckFilePathAvailability request. -func (client ResourceClient) CheckFilePathAvailabilityPreparer(ctx context.Context, body FilePathAvailabilityRequest, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/locations/{location}/checkFilePathAvailability", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckFilePathAvailabilitySender sends the CheckFilePathAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client ResourceClient) CheckFilePathAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckFilePathAvailabilityResponder handles the response to the CheckFilePathAvailability request. The method always -// closes the http.Response Body. -func (client ResourceClient) CheckFilePathAvailabilityResponder(resp *http.Response) (result CheckAvailabilityResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CheckNameAvailability check if a resource name is available. -// Parameters: -// body - name availability request. -// location - the location -func (client ResourceClient) CheckNameAvailability(ctx context.Context, body ResourceNameAvailabilityRequest, location string) (result CheckAvailabilityResponse, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.ResourceGroup", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.ResourceClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, body, location) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.ResourceClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client ResourceClient) CheckNameAvailabilityPreparer(ctx context.Context, body ResourceNameAvailabilityRequest, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/locations/{location}/checkNameAvailability", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client ResourceClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client ResourceClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckAvailabilityResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CheckQuotaAvailability check if a quota is available. -// Parameters: -// body - quota availability request. -// location - the location -func (client ResourceClient) CheckQuotaAvailability(ctx context.Context, body QuotaAvailabilityRequest, location string) (result CheckAvailabilityResponse, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceClient.CheckQuotaAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.ResourceGroup", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.ResourceClient", "CheckQuotaAvailability", err.Error()) - } - - req, err := client.CheckQuotaAvailabilityPreparer(ctx, body, location) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceClient", "CheckQuotaAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckQuotaAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.ResourceClient", "CheckQuotaAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckQuotaAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceClient", "CheckQuotaAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckQuotaAvailabilityPreparer prepares the CheckQuotaAvailability request. -func (client ResourceClient) CheckQuotaAvailabilityPreparer(ctx context.Context, body QuotaAvailabilityRequest, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/locations/{location}/checkQuotaAvailability", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckQuotaAvailabilitySender sends the CheckQuotaAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client ResourceClient) CheckQuotaAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckQuotaAvailabilityResponder handles the response to the CheckQuotaAvailability request. The method always -// closes the http.Response Body. -func (client ResourceClient) CheckQuotaAvailabilityResponder(resp *http.Response) (result CheckAvailabilityResponse, err error) { - err = autorest.Respond( - resp, - 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/netapp/mgmt/2021-10-01/netapp/resourcequotalimits.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/resourcequotalimits.go deleted file mode 100644 index 0cd8f587e0b8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/resourcequotalimits.go +++ /dev/null @@ -1,182 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// ResourceQuotaLimitsClient is the microsoft NetApp Files Azure Resource Provider specification -type ResourceQuotaLimitsClient struct { - BaseClient -} - -// NewResourceQuotaLimitsClient creates an instance of the ResourceQuotaLimitsClient client. -func NewResourceQuotaLimitsClient(subscriptionID string) ResourceQuotaLimitsClient { - return NewResourceQuotaLimitsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewResourceQuotaLimitsClientWithBaseURI creates an instance of the ResourceQuotaLimitsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewResourceQuotaLimitsClientWithBaseURI(baseURI string, subscriptionID string) ResourceQuotaLimitsClient { - return ResourceQuotaLimitsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get get the default and current subscription quota limit -// Parameters: -// location - the location -// quotaLimitName - the name of the Quota Limit -func (client ResourceQuotaLimitsClient) Get(ctx context.Context, location string, quotaLimitName string) (result SubscriptionQuotaItem, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceQuotaLimitsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, location, quotaLimitName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceQuotaLimitsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.ResourceQuotaLimitsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceQuotaLimitsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ResourceQuotaLimitsClient) GetPreparer(ctx context.Context, location string, quotaLimitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "quotaLimitName": autorest.Encode("path", quotaLimitName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.NetApp/locations/{location}/quotaLimits/{quotaLimitName}", 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 ResourceQuotaLimitsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ResourceQuotaLimitsClient) GetResponder(resp *http.Response) (result SubscriptionQuotaItem, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List get the default and current limits for quotas -// Parameters: -// location - the location -func (client ResourceQuotaLimitsClient) List(ctx context.Context, location string) (result SubscriptionQuotaItemList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceQuotaLimitsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceQuotaLimitsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.ResourceQuotaLimitsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.ResourceQuotaLimitsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ResourceQuotaLimitsClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.NetApp/locations/{location}/quotaLimits", 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 ResourceQuotaLimitsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ResourceQuotaLimitsClient) ListResponder(resp *http.Response) (result SubscriptionQuotaItemList, err error) { - err = autorest.Respond( - resp, - 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/netapp/mgmt/2021-10-01/netapp/snapshotpolicies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/snapshotpolicies.go deleted file mode 100644 index 365057c6955f..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/snapshotpolicies.go +++ /dev/null @@ -1,569 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SnapshotPoliciesClient is the microsoft NetApp Files Azure Resource Provider specification -type SnapshotPoliciesClient struct { - BaseClient -} - -// NewSnapshotPoliciesClient creates an instance of the SnapshotPoliciesClient client. -func NewSnapshotPoliciesClient(subscriptionID string) SnapshotPoliciesClient { - return NewSnapshotPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSnapshotPoliciesClientWithBaseURI creates an instance of the SnapshotPoliciesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewSnapshotPoliciesClientWithBaseURI(baseURI string, subscriptionID string) SnapshotPoliciesClient { - return SnapshotPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create create a snapshot policy -// Parameters: -// body - snapshot policy object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// snapshotPolicyName - the name of the snapshot policy -func (client SnapshotPoliciesClient) Create(ctx context.Context, body SnapshotPolicy, resourceGroupName string, accountName string, snapshotPolicyName string) (result SnapshotPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotPoliciesClient.Create") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Location", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.SnapshotPolicyProperties", Name: validation.Null, Rule: true, Chain: nil}}}, - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotPoliciesClient", "Create", err.Error()) - } - - req, err := client.CreatePreparer(ctx, body, resourceGroupName, accountName, snapshotPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Create", resp, "Failure responding to request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client SnapshotPoliciesClient) CreatePreparer(ctx context.Context, body SnapshotPolicy, resourceGroupName string, accountName string, snapshotPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotPolicyName": autorest.Encode("path", snapshotPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Etag = nil - body.Type = nil - body.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/snapshotPolicies/{snapshotPolicyName}", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotPoliciesClient) CreateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client SnapshotPoliciesClient) CreateResponder(resp *http.Response) (result SnapshotPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete snapshot policy -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// snapshotPolicyName - the name of the snapshot policy -func (client SnapshotPoliciesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, snapshotPolicyName string) (result SnapshotPoliciesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotPoliciesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotPoliciesClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, snapshotPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SnapshotPoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, snapshotPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotPolicyName": autorest.Encode("path", snapshotPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/snapshotPolicies/{snapshotPolicyName}", 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 SnapshotPoliciesClient) DeleteSender(req *http.Request) (future SnapshotPoliciesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SnapshotPoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get a snapshot Policy -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// snapshotPolicyName - the name of the snapshot policy -func (client SnapshotPoliciesClient) Get(ctx context.Context, resourceGroupName string, accountName string, snapshotPolicyName string) (result SnapshotPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotPoliciesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotPoliciesClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName, snapshotPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SnapshotPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, snapshotPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotPolicyName": autorest.Encode("path", snapshotPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/snapshotPolicies/{snapshotPolicyName}", 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 SnapshotPoliciesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SnapshotPoliciesClient) GetResponder(resp *http.Response) (result SnapshotPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list snapshot policy -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client SnapshotPoliciesClient) List(ctx context.Context, resourceGroupName string, accountName string) (result SnapshotPoliciesList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotPoliciesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotPoliciesClient", "List", err.Error()) - } - - req, err := client.ListPreparer(ctx, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SnapshotPoliciesClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/snapshotPolicies", 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 SnapshotPoliciesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SnapshotPoliciesClient) ListResponder(resp *http.Response) (result SnapshotPoliciesList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListVolumes get volumes associated with snapshot policy -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// snapshotPolicyName - the name of the snapshot policy -func (client SnapshotPoliciesClient) ListVolumes(ctx context.Context, resourceGroupName string, accountName string, snapshotPolicyName string) (result SnapshotPolicyVolumeList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotPoliciesClient.ListVolumes") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotPoliciesClient", "ListVolumes", err.Error()) - } - - req, err := client.ListVolumesPreparer(ctx, resourceGroupName, accountName, snapshotPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "ListVolumes", nil, "Failure preparing request") - return - } - - resp, err := client.ListVolumesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "ListVolumes", resp, "Failure sending request") - return - } - - result, err = client.ListVolumesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "ListVolumes", resp, "Failure responding to request") - return - } - - return -} - -// ListVolumesPreparer prepares the ListVolumes request. -func (client SnapshotPoliciesClient) ListVolumesPreparer(ctx context.Context, resourceGroupName string, accountName string, snapshotPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotPolicyName": autorest.Encode("path", snapshotPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/snapshotPolicies/{snapshotPolicyName}/volumes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVolumesSender sends the ListVolumes request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotPoliciesClient) ListVolumesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVolumesResponder handles the response to the ListVolumes request. The method always -// closes the http.Response Body. -func (client SnapshotPoliciesClient) ListVolumesResponder(resp *http.Response) (result SnapshotPolicyVolumeList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Update patch a snapshot policy -// Parameters: -// body - snapshot policy object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// snapshotPolicyName - the name of the snapshot policy -func (client SnapshotPoliciesClient) Update(ctx context.Context, body SnapshotPolicyPatch, resourceGroupName string, accountName string, snapshotPolicyName string) (result SnapshotPoliciesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotPoliciesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotPoliciesClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, body, resourceGroupName, accountName, snapshotPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotPoliciesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client SnapshotPoliciesClient) UpdatePreparer(ctx context.Context, body SnapshotPolicyPatch, resourceGroupName string, accountName string, snapshotPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotPolicyName": autorest.Encode("path", snapshotPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/snapshotPolicies/{snapshotPolicyName}", pathParameters), - autorest.WithJSON(body), - 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 SnapshotPoliciesClient) UpdateSender(req *http.Request) (future SnapshotPoliciesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client SnapshotPoliciesClient) UpdateResponder(resp *http.Response) (result SnapshotPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/netapp/mgmt/2021-10-01/netapp/snapshots.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/snapshots.go deleted file mode 100644 index d225f05633bc..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/snapshots.go +++ /dev/null @@ -1,654 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SnapshotsClient is the microsoft NetApp Files Azure Resource Provider specification -type SnapshotsClient struct { - BaseClient -} - -// NewSnapshotsClient creates an instance of the SnapshotsClient client. -func NewSnapshotsClient(subscriptionID string) SnapshotsClient { - return NewSnapshotsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSnapshotsClientWithBaseURI creates an instance of the SnapshotsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSnapshotsClientWithBaseURI(baseURI string, subscriptionID string) SnapshotsClient { - return SnapshotsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create create the specified snapshot within the given volume -// Parameters: -// body - snapshot object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// snapshotName - the name of the snapshot -func (client SnapshotsClient) Create(ctx context.Context, body Snapshot, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (result SnapshotsCreateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.Create") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Location", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.SnapshotProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.SnapshotProperties.SnapshotID", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.SnapshotProperties.SnapshotID", Name: validation.MaxLength, Rule: 36, Chain: nil}, - {Target: "body.SnapshotProperties.SnapshotID", Name: validation.MinLength, Rule: 36, Chain: nil}, - {Target: "body.SnapshotProperties.SnapshotID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$`, Chain: nil}, - }}, - }}}}, - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotsClient", "Create", err.Error()) - } - - req, err := client.CreatePreparer(ctx, body, resourceGroupName, accountName, poolName, volumeName, snapshotName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "Create", nil, "Failure preparing request") - return - } - - result, err = client.CreateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "Create", result.Response(), "Failure sending request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client SnapshotsClient) CreatePreparer(ctx context.Context, body Snapshot, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) CreateSender(req *http.Request) (future SnapshotsCreateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) CreateResponder(resp *http.Response) (result Snapshot, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete snapshot -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// snapshotName - the name of the snapshot -func (client SnapshotsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (result SnapshotsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, poolName, volumeName, snapshotName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SnapshotsClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}", 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 SnapshotsClient) DeleteSender(req *http.Request) (future SnapshotsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get details of the specified snapshot -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// snapshotName - the name of the snapshot -func (client SnapshotsClient) Get(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (result Snapshot, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, snapshotName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SnapshotsClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}", 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 SnapshotsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) GetResponder(resp *http.Response) (result Snapshot, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all snapshots associated with the volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client SnapshotsClient) List(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result SnapshotsList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotsClient", "List", err.Error()) - } - - req, err := client.ListPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SnapshotsClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots", 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 SnapshotsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) ListResponder(resp *http.Response) (result SnapshotsList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// RestoreFiles restore the specified files from the specified snapshot to the active filesystem -// Parameters: -// body - restore payload supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// snapshotName - the name of the snapshot -func (client SnapshotsClient) RestoreFiles(ctx context.Context, body SnapshotRestoreFiles, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (result SnapshotsRestoreFilesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.RestoreFiles") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.FilePaths", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "body.FilePaths", Name: validation.MaxItems, Rule: 10, Chain: nil}, - {Target: "body.FilePaths", Name: validation.MinItems, Rule: 1, Chain: nil}, - }}}}, - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotsClient", "RestoreFiles", err.Error()) - } - - req, err := client.RestoreFilesPreparer(ctx, body, resourceGroupName, accountName, poolName, volumeName, snapshotName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "RestoreFiles", nil, "Failure preparing request") - return - } - - result, err = client.RestoreFilesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "RestoreFiles", result.Response(), "Failure sending request") - return - } - - return -} - -// RestoreFilesPreparer prepares the RestoreFiles request. -func (client SnapshotsClient) RestoreFilesPreparer(ctx context.Context, body SnapshotRestoreFiles, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}/restoreFiles", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RestoreFilesSender sends the RestoreFiles request. The method will close the -// http.Response Body if it receives an error. -func (client SnapshotsClient) RestoreFilesSender(req *http.Request) (future SnapshotsRestoreFilesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RestoreFilesResponder handles the response to the RestoreFiles request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) RestoreFilesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update patch a snapshot -// Parameters: -// body - snapshot object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// snapshotName - the name of the snapshot -func (client SnapshotsClient) Update(ctx context.Context, body interface{}, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (result SnapshotsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SnapshotsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SnapshotsClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, body, resourceGroupName, accountName, poolName, volumeName, snapshotName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SnapshotsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client SnapshotsClient) UpdatePreparer(ctx context.Context, body interface{}, resourceGroupName string, accountName string, poolName string, volumeName string, snapshotName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "snapshotName": autorest.Encode("path", snapshotName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}", pathParameters), - autorest.WithJSON(body), - 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 SnapshotsClient) UpdateSender(req *http.Request) (future SnapshotsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client SnapshotsClient) UpdateResponder(resp *http.Response) (result Snapshot, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/netapp/mgmt/2021-10-01/netapp/subvolumes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/subvolumes.go deleted file mode 100644 index 54cec7e712e5..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/subvolumes.go +++ /dev/null @@ -1,698 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SubvolumesClient is the microsoft NetApp Files Azure Resource Provider specification -type SubvolumesClient struct { - BaseClient -} - -// NewSubvolumesClient creates an instance of the SubvolumesClient client. -func NewSubvolumesClient(subscriptionID string) SubvolumesClient { - return NewSubvolumesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSubvolumesClientWithBaseURI creates an instance of the SubvolumesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSubvolumesClientWithBaseURI(baseURI string, subscriptionID string) SubvolumesClient { - return SubvolumesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create creates a subvolume in the path or clones the subvolume mentioned in the parentPath -// Parameters: -// body - subvolume object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// subvolumeName - the name of the subvolume. -func (client SubvolumesClient) Create(ctx context.Context, body SubvolumeInfo, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (result SubvolumesCreateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubvolumesClient.Create") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: subvolumeName, - Constraints: []validation.Constraint{{Target: "subvolumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "subvolumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "subvolumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SubvolumesClient", "Create", err.Error()) - } - - req, err := client.CreatePreparer(ctx, body, resourceGroupName, accountName, poolName, volumeName, subvolumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "Create", nil, "Failure preparing request") - return - } - - result, err = client.CreateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "Create", result.Response(), "Failure sending request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client SubvolumesClient) CreatePreparer(ctx context.Context, body SubvolumeInfo, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "subvolumeName": autorest.Encode("path", subvolumeName), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/subvolumes/{subvolumeName}", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client SubvolumesClient) CreateSender(req *http.Request) (future SubvolumesCreateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client SubvolumesClient) CreateResponder(resp *http.Response) (result SubvolumeInfo, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete subvolume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// subvolumeName - the name of the subvolume. -func (client SubvolumesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (result SubvolumesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubvolumesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: subvolumeName, - Constraints: []validation.Constraint{{Target: "subvolumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "subvolumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "subvolumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SubvolumesClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, poolName, volumeName, subvolumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SubvolumesClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "subvolumeName": autorest.Encode("path", subvolumeName), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/subvolumes/{subvolumeName}", 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 SubvolumesClient) DeleteSender(req *http.Request) (future SubvolumesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SubvolumesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get returns the path associated with the subvolumeName provided -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// subvolumeName - the name of the subvolume. -func (client SubvolumesClient) Get(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (result SubvolumeInfo, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubvolumesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: subvolumeName, - Constraints: []validation.Constraint{{Target: "subvolumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "subvolumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "subvolumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SubvolumesClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, subvolumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SubvolumesClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "subvolumeName": autorest.Encode("path", subvolumeName), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/subvolumes/{subvolumeName}", 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 SubvolumesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SubvolumesClient) GetResponder(resp *http.Response) (result SubvolumeInfo, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetMetadata get details of the specified subvolume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// subvolumeName - the name of the subvolume. -func (client SubvolumesClient) GetMetadata(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (result SubvolumesGetMetadataFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubvolumesClient.GetMetadata") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: subvolumeName, - Constraints: []validation.Constraint{{Target: "subvolumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "subvolumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "subvolumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SubvolumesClient", "GetMetadata", err.Error()) - } - - req, err := client.GetMetadataPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, subvolumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "GetMetadata", nil, "Failure preparing request") - return - } - - result, err = client.GetMetadataSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "GetMetadata", result.Response(), "Failure sending request") - return - } - - return -} - -// GetMetadataPreparer prepares the GetMetadata request. -func (client SubvolumesClient) GetMetadataPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "subvolumeName": autorest.Encode("path", subvolumeName), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/subvolumes/{subvolumeName}/getMetadata", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetMetadataSender sends the GetMetadata request. The method will close the -// http.Response Body if it receives an error. -func (client SubvolumesClient) GetMetadataSender(req *http.Request) (future SubvolumesGetMetadataFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetMetadataResponder handles the response to the GetMetadata request. The method always -// closes the http.Response Body. -func (client SubvolumesClient) GetMetadataResponder(resp *http.Response) (result SubvolumeModel, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByVolume returns a list of the subvolumes in the volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client SubvolumesClient) ListByVolume(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result SubvolumesListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubvolumesClient.ListByVolume") - defer func() { - sc := -1 - if result.sl.Response.Response != nil { - sc = result.sl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SubvolumesClient", "ListByVolume", err.Error()) - } - - result.fn = client.listByVolumeNextResults - req, err := client.ListByVolumePreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "ListByVolume", nil, "Failure preparing request") - return - } - - resp, err := client.ListByVolumeSender(req) - if err != nil { - result.sl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "ListByVolume", resp, "Failure sending request") - return - } - - result.sl, err = client.ListByVolumeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "ListByVolume", resp, "Failure responding to request") - return - } - if result.sl.hasNextLink() && result.sl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByVolumePreparer prepares the ListByVolume request. -func (client SubvolumesClient) ListByVolumePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/subvolumes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByVolumeSender sends the ListByVolume request. The method will close the -// http.Response Body if it receives an error. -func (client SubvolumesClient) ListByVolumeSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByVolumeResponder handles the response to the ListByVolume request. The method always -// closes the http.Response Body. -func (client SubvolumesClient) ListByVolumeResponder(resp *http.Response) (result SubvolumesList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByVolumeNextResults retrieves the next set of results, if any. -func (client SubvolumesClient) listByVolumeNextResults(ctx context.Context, lastResults SubvolumesList) (result SubvolumesList, err error) { - req, err := lastResults.subvolumesListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "listByVolumeNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByVolumeSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "listByVolumeNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByVolumeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "listByVolumeNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByVolumeComplete enumerates all values, automatically crossing page boundaries as required. -func (client SubvolumesClient) ListByVolumeComplete(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result SubvolumesListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubvolumesClient.ListByVolume") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByVolume(ctx, resourceGroupName, accountName, poolName, volumeName) - return -} - -// Update patch a subvolume -// Parameters: -// body - subvolume object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// subvolumeName - the name of the subvolume. -func (client SubvolumesClient) Update(ctx context.Context, body SubvolumePatchRequest, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (result SubvolumesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubvolumesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: subvolumeName, - Constraints: []validation.Constraint{{Target: "subvolumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "subvolumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "subvolumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.SubvolumesClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, body, resourceGroupName, accountName, poolName, volumeName, subvolumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.SubvolumesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client SubvolumesClient) UpdatePreparer(ctx context.Context, body SubvolumePatchRequest, resourceGroupName string, accountName string, poolName string, volumeName string, subvolumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "subvolumeName": autorest.Encode("path", subvolumeName), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/subvolumes/{subvolumeName}", pathParameters), - autorest.WithJSON(body), - 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 SubvolumesClient) UpdateSender(req *http.Request) (future SubvolumesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client SubvolumesClient) UpdateResponder(resp *http.Response) (result SubvolumeInfo, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/netapp/mgmt/2021-10-01/netapp/vaults.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/vaults.go deleted file mode 100644 index ee3222d17445..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/vaults.go +++ /dev/null @@ -1,116 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VaultsClient is the microsoft NetApp Files Azure Resource Provider specification -type VaultsClient struct { - BaseClient -} - -// NewVaultsClient creates an instance of the VaultsClient client. -func NewVaultsClient(subscriptionID string) VaultsClient { - return NewVaultsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVaultsClientWithBaseURI creates an instance of the VaultsClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVaultsClientWithBaseURI(baseURI string, subscriptionID string) VaultsClient { - return VaultsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List list vaults for a Netapp Account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client VaultsClient) List(ctx context.Context, resourceGroupName string, accountName string) (result VaultList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VaultsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VaultsClient", "List", err.Error()) - } - - req, err := client.ListPreparer(ctx, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VaultsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.VaultsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VaultsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VaultsClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/vaults", 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 VaultsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VaultsClient) ListResponder(resp *http.Response) (result VaultList, err error) { - err = autorest.Respond( - resp, - 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/netapp/mgmt/2021-10-01/netapp/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/version.go deleted file mode 100644 index d254f8bece8a..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package netapp - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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() + " netapp/2021-10-01" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/volumegroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/volumegroups.go deleted file mode 100644 index 65bc0539bda9..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/volumegroups.go +++ /dev/null @@ -1,397 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VolumeGroupsClient is the microsoft NetApp Files Azure Resource Provider specification -type VolumeGroupsClient struct { - BaseClient -} - -// NewVolumeGroupsClient creates an instance of the VolumeGroupsClient client. -func NewVolumeGroupsClient(subscriptionID string) VolumeGroupsClient { - return NewVolumeGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVolumeGroupsClientWithBaseURI creates an instance of the VolumeGroupsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVolumeGroupsClientWithBaseURI(baseURI string, subscriptionID string) VolumeGroupsClient { - return VolumeGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create create a volume group along with specified volumes -// Parameters: -// body - volume Group object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// volumeGroupName - the name of the volumeGroup -func (client VolumeGroupsClient) Create(ctx context.Context, body VolumeGroupDetails, resourceGroupName string, accountName string, volumeGroupName string) (result VolumeGroupsCreateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumeGroupsClient.Create") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: volumeGroupName, - Constraints: []validation.Constraint{{Target: "volumeGroupName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumeGroupsClient", "Create", err.Error()) - } - - req, err := client.CreatePreparer(ctx, body, resourceGroupName, accountName, volumeGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "Create", nil, "Failure preparing request") - return - } - - result, err = client.CreateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "Create", result.Response(), "Failure sending request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client VolumeGroupsClient) CreatePreparer(ctx context.Context, body VolumeGroupDetails, resourceGroupName string, accountName string, volumeGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeGroupName": autorest.Encode("path", volumeGroupName), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/volumeGroups/{volumeGroupName}", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client VolumeGroupsClient) CreateSender(req *http.Request) (future VolumeGroupsCreateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client VolumeGroupsClient) CreateResponder(resp *http.Response) (result VolumeGroupDetails, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the specified volume group only if there are no volumes under volume group. -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// volumeGroupName - the name of the volumeGroup -func (client VolumeGroupsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, volumeGroupName string) (result VolumeGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumeGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: volumeGroupName, - Constraints: []validation.Constraint{{Target: "volumeGroupName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumeGroupsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, volumeGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VolumeGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, volumeGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeGroupName": autorest.Encode("path", volumeGroupName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/volumeGroups/{volumeGroupName}", 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 VolumeGroupsClient) DeleteSender(req *http.Request) (future VolumeGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VolumeGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get details of the specified volume group -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// volumeGroupName - the name of the volumeGroup -func (client VolumeGroupsClient) Get(ctx context.Context, resourceGroupName string, accountName string, volumeGroupName string) (result VolumeGroupDetails, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumeGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: volumeGroupName, - Constraints: []validation.Constraint{{Target: "volumeGroupName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumeGroupsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName, volumeGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VolumeGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, volumeGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeGroupName": autorest.Encode("path", volumeGroupName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/volumeGroups/{volumeGroupName}", 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 VolumeGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VolumeGroupsClient) GetResponder(resp *http.Response) (result VolumeGroupDetails, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByNetAppAccount list all volume groups for given account -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -func (client VolumeGroupsClient) ListByNetAppAccount(ctx context.Context, resourceGroupName string, accountName string) (result VolumeGroupList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumeGroupsClient.ListByNetAppAccount") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumeGroupsClient", "ListByNetAppAccount", err.Error()) - } - - req, err := client.ListByNetAppAccountPreparer(ctx, resourceGroupName, accountName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "ListByNetAppAccount", nil, "Failure preparing request") - return - } - - resp, err := client.ListByNetAppAccountSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "ListByNetAppAccount", resp, "Failure sending request") - return - } - - result, err = client.ListByNetAppAccountResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumeGroupsClient", "ListByNetAppAccount", resp, "Failure responding to request") - return - } - - return -} - -// ListByNetAppAccountPreparer prepares the ListByNetAppAccount request. -func (client VolumeGroupsClient) ListByNetAppAccountPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/volumeGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByNetAppAccountSender sends the ListByNetAppAccount request. The method will close the -// http.Response Body if it receives an error. -func (client VolumeGroupsClient) ListByNetAppAccountSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByNetAppAccountResponder handles the response to the ListByNetAppAccount request. The method always -// closes the http.Response Body. -func (client VolumeGroupsClient) ListByNetAppAccountResponder(resp *http.Response) (result VolumeGroupList, err error) { - err = autorest.Respond( - resp, - 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/netapp/mgmt/2021-10-01/netapp/volumes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/volumes.go deleted file mode 100644 index 11016cd3a95a..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/netapp/mgmt/2021-10-01/netapp/volumes.go +++ /dev/null @@ -1,1422 +0,0 @@ -package netapp - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VolumesClient is the microsoft NetApp Files Azure Resource Provider specification -type VolumesClient struct { - BaseClient -} - -// NewVolumesClient creates an instance of the VolumesClient client. -func NewVolumesClient(subscriptionID string) VolumesClient { - return NewVolumesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVolumesClientWithBaseURI creates an instance of the VolumesClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVolumesClientWithBaseURI(baseURI string, subscriptionID string) VolumesClient { - return VolumesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// AuthorizeReplication authorize the replication connection on the source volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// body - authorize request object supplied in the body of the operation. -func (client VolumesClient) AuthorizeReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body AuthorizeRequest) (result VolumesAuthorizeReplicationFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.AuthorizeReplication") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "AuthorizeReplication", err.Error()) - } - - req, err := client.AuthorizeReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, body) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "AuthorizeReplication", nil, "Failure preparing request") - return - } - - result, err = client.AuthorizeReplicationSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "AuthorizeReplication", result.Response(), "Failure sending request") - return - } - - return -} - -// AuthorizeReplicationPreparer prepares the AuthorizeReplication request. -func (client VolumesClient) AuthorizeReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body AuthorizeRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/authorizeReplication", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// AuthorizeReplicationSender sends the AuthorizeReplication request. The method will close the -// http.Response Body if it receives an error. -func (client VolumesClient) AuthorizeReplicationSender(req *http.Request) (future VolumesAuthorizeReplicationFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// AuthorizeReplicationResponder handles the response to the AuthorizeReplication request. The method always -// closes the http.Response Body. -func (client VolumesClient) AuthorizeReplicationResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// BreakReplication break the replication connection on the destination volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// body - optional body to force break the replication. -func (client VolumesClient) BreakReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body *BreakReplicationRequest) (result VolumesBreakReplicationFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.BreakReplication") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "BreakReplication", err.Error()) - } - - req, err := client.BreakReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, body) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "BreakReplication", nil, "Failure preparing request") - return - } - - result, err = client.BreakReplicationSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "BreakReplication", result.Response(), "Failure sending request") - return - } - - return -} - -// BreakReplicationPreparer prepares the BreakReplication request. -func (client VolumesClient) BreakReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body *BreakReplicationRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/breakReplication", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if body != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(body)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// BreakReplicationSender sends the BreakReplication request. The method will close the -// http.Response Body if it receives an error. -func (client VolumesClient) BreakReplicationSender(req *http.Request) (future VolumesBreakReplicationFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// BreakReplicationResponder handles the response to the BreakReplication request. The method always -// closes the http.Response Body. -func (client VolumesClient) BreakReplicationResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// CreateOrUpdate create or update the specified volume within the capacity pool -// Parameters: -// body - volume object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client VolumesClient) CreateOrUpdate(ctx context.Context, body Volume, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.Location", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.VolumeProperties", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.FileSystemID", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.FileSystemID", Name: validation.MaxLength, Rule: 36, Chain: nil}, - {Target: "body.VolumeProperties.FileSystemID", Name: validation.MinLength, Rule: 36, Chain: nil}, - {Target: "body.VolumeProperties.FileSystemID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$`, Chain: nil}, - }}, - {Target: "body.VolumeProperties.CreationToken", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.CreationToken", Name: validation.MaxLength, Rule: 80, Chain: nil}, - {Target: "body.VolumeProperties.CreationToken", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "body.VolumeProperties.CreationToken", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-]{0,79}$`, Chain: nil}, - }}, - {Target: "body.VolumeProperties.UsageThreshold", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.UsageThreshold", Name: validation.InclusiveMaximum, Rule: int64(109951162777600), Chain: nil}, - {Target: "body.VolumeProperties.UsageThreshold", Name: validation.InclusiveMinimum, Rule: int64(107374182400), Chain: nil}, - }}, - {Target: "body.VolumeProperties.SnapshotID", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.SnapshotID", Name: validation.MaxLength, Rule: 36, Chain: nil}, - {Target: "body.VolumeProperties.SnapshotID", Name: validation.MinLength, Rule: 36, Chain: nil}, - {Target: "body.VolumeProperties.SnapshotID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}|(\\?([^\/]*[\/])*)([^\/]+)$`, Chain: nil}, - }}, - {Target: "body.VolumeProperties.BackupID", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.BackupID", Name: validation.MaxLength, Rule: 36, Chain: nil}, - {Target: "body.VolumeProperties.BackupID", Name: validation.MinLength, Rule: 36, Chain: nil}, - {Target: "body.VolumeProperties.BackupID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}|(\\?([^\/]*[\/])*)([^\/]+)$`, Chain: nil}, - }}, - {Target: "body.VolumeProperties.SubnetID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "body.VolumeProperties.NetworkSiblingSetID", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.NetworkSiblingSetID", Name: validation.MaxLength, Rule: 36, Chain: nil}, - {Target: "body.VolumeProperties.NetworkSiblingSetID", Name: validation.MinLength, Rule: 36, Chain: nil}, - {Target: "body.VolumeProperties.NetworkSiblingSetID", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$`, Chain: nil}, - }}, - {Target: "body.VolumeProperties.DataProtection", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.DataProtection.Replication", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.DataProtection.Replication.RemoteVolumeResourceID", Name: validation.Null, Rule: true, Chain: nil}}}, - }}, - {Target: "body.VolumeProperties.CoolnessPeriod", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.CoolnessPeriod", Name: validation.InclusiveMaximum, Rule: int64(63), Chain: nil}, - {Target: "body.VolumeProperties.CoolnessPeriod", Name: validation.InclusiveMinimum, Rule: int64(7), Chain: nil}, - }}, - {Target: "body.VolumeProperties.UnixPermissions", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "body.VolumeProperties.UnixPermissions", Name: validation.MaxLength, Rule: 4, Chain: nil}, - {Target: "body.VolumeProperties.UnixPermissions", Name: validation.MinLength, Rule: 4, Chain: nil}, - }}, - }}}}, - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, body, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VolumesClient) CreateOrUpdatePreparer(ctx context.Context, body Volume, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Etag = nil - body.Type = nil - body.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", pathParameters), - autorest.WithJSON(body), - 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 VolumesClient) CreateOrUpdateSender(req *http.Request) (future VolumesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VolumesClient) CreateOrUpdateResponder(resp *http.Response) (result Volume, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the specified volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// forceDelete - an option to force delete the volume. Will cleanup resources connected to the particular -// volume -func (client VolumesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, forceDelete *bool) (result VolumesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, poolName, volumeName, forceDelete) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VolumesClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, forceDelete *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if forceDelete != nil { - queryParameters["forceDelete"] = autorest.Encode("query", *forceDelete) - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", 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 VolumesClient) DeleteSender(req *http.Request) (future VolumesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VolumesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// DeleteReplication delete the replication connection on the destination volume, and send release to the source -// replication -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client VolumesClient) DeleteReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesDeleteReplicationFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.DeleteReplication") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "DeleteReplication", err.Error()) - } - - req, err := client.DeleteReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "DeleteReplication", nil, "Failure preparing request") - return - } - - result, err = client.DeleteReplicationSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "DeleteReplication", result.Response(), "Failure sending request") - return - } - - return -} - -// DeleteReplicationPreparer prepares the DeleteReplication request. -func (client VolumesClient) DeleteReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/deleteReplication", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteReplicationSender sends the DeleteReplication request. The method will close the -// http.Response Body if it receives an error. -func (client VolumesClient) DeleteReplicationSender(req *http.Request) (future VolumesDeleteReplicationFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteReplicationResponder handles the response to the DeleteReplication request. The method always -// closes the http.Response Body. -func (client VolumesClient) DeleteReplicationResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the details of the specified volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client VolumesClient) Get(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result Volume, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VolumesClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", 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 VolumesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VolumesClient) GetResponder(resp *http.Response) (result Volume, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all volumes within the capacity pool -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -func (client VolumesClient) List(ctx context.Context, resourceGroupName string, accountName string, poolName string) (result VolumeListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.List") - defer func() { - sc := -1 - if result.vl.Response.Response != nil { - sc = result.vl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, accountName, poolName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "List", resp, "Failure sending request") - return - } - - result.vl, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "List", resp, "Failure responding to request") - return - } - if result.vl.hasNextLink() && result.vl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VolumesClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes", 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 VolumesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VolumesClient) ListResponder(resp *http.Response) (result VolumeList, err error) { - err = autorest.Respond( - resp, - 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 VolumesClient) listNextResults(ctx context.Context, lastResults VolumeList) (result VolumeList, err error) { - req, err := lastResults.volumeListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "netapp.VolumesClient", "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, "netapp.VolumesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VolumesClient) ListComplete(ctx context.Context, resourceGroupName string, accountName string, poolName string) (result VolumeListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, accountName, poolName) - return -} - -// PoolChange moves volume to another pool -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// body - move volume to the pool supplied in the body of the operation. -func (client VolumesClient) PoolChange(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body PoolChangeRequest) (result VolumesPoolChangeFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.PoolChange") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: body, - Constraints: []validation.Constraint{{Target: "body.NewPoolResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "PoolChange", err.Error()) - } - - req, err := client.PoolChangePreparer(ctx, resourceGroupName, accountName, poolName, volumeName, body) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "PoolChange", nil, "Failure preparing request") - return - } - - result, err = client.PoolChangeSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "PoolChange", result.Response(), "Failure sending request") - return - } - - return -} - -// PoolChangePreparer prepares the PoolChange request. -func (client VolumesClient) PoolChangePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body PoolChangeRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/poolChange", pathParameters), - autorest.WithJSON(body), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PoolChangeSender sends the PoolChange request. The method will close the -// http.Response Body if it receives an error. -func (client VolumesClient) PoolChangeSender(req *http.Request) (future VolumesPoolChangeFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PoolChangeResponder handles the response to the PoolChange request. The method always -// closes the http.Response Body. -func (client VolumesClient) PoolChangeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// ReInitializeReplication re-Initializes the replication connection on the destination volume -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client VolumesClient) ReInitializeReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesReInitializeReplicationFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.ReInitializeReplication") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "ReInitializeReplication", err.Error()) - } - - req, err := client.ReInitializeReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReInitializeReplication", nil, "Failure preparing request") - return - } - - result, err = client.ReInitializeReplicationSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReInitializeReplication", result.Response(), "Failure sending request") - return - } - - return -} - -// ReInitializeReplicationPreparer prepares the ReInitializeReplication request. -func (client VolumesClient) ReInitializeReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/reinitializeReplication", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ReInitializeReplicationSender sends the ReInitializeReplication request. The method will close the -// http.Response Body if it receives an error. -func (client VolumesClient) ReInitializeReplicationSender(req *http.Request) (future VolumesReInitializeReplicationFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ReInitializeReplicationResponder handles the response to the ReInitializeReplication request. The method always -// closes the http.Response Body. -func (client VolumesClient) ReInitializeReplicationResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// ReplicationStatusMethod get the status of the replication -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client VolumesClient) ReplicationStatusMethod(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result ReplicationStatus, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.ReplicationStatusMethod") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "ReplicationStatusMethod", err.Error()) - } - - req, err := client.ReplicationStatusMethodPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReplicationStatusMethod", nil, "Failure preparing request") - return - } - - resp, err := client.ReplicationStatusMethodSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReplicationStatusMethod", resp, "Failure sending request") - return - } - - result, err = client.ReplicationStatusMethodResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ReplicationStatusMethod", resp, "Failure responding to request") - return - } - - return -} - -// ReplicationStatusMethodPreparer prepares the ReplicationStatusMethod request. -func (client VolumesClient) ReplicationStatusMethodPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/replicationStatus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ReplicationStatusMethodSender sends the ReplicationStatusMethod request. The method will close the -// http.Response Body if it receives an error. -func (client VolumesClient) ReplicationStatusMethodSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ReplicationStatusMethodResponder handles the response to the ReplicationStatusMethod request. The method always -// closes the http.Response Body. -func (client VolumesClient) ReplicationStatusMethodResponder(resp *http.Response) (result ReplicationStatus, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ResyncReplication resync the connection on the destination volume. If the operation is ran on the source volume it -// will reverse-resync the connection and sync from destination to source. -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client VolumesClient) ResyncReplication(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesResyncReplicationFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.ResyncReplication") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "ResyncReplication", err.Error()) - } - - req, err := client.ResyncReplicationPreparer(ctx, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ResyncReplication", nil, "Failure preparing request") - return - } - - result, err = client.ResyncReplicationSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "ResyncReplication", result.Response(), "Failure sending request") - return - } - - return -} - -// ResyncReplicationPreparer prepares the ResyncReplication request. -func (client VolumesClient) ResyncReplicationPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/resyncReplication", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResyncReplicationSender sends the ResyncReplication request. The method will close the -// http.Response Body if it receives an error. -func (client VolumesClient) ResyncReplicationSender(req *http.Request) (future VolumesResyncReplicationFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResyncReplicationResponder handles the response to the ResyncReplication request. The method always -// closes the http.Response Body. -func (client VolumesClient) ResyncReplicationResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Revert revert a volume to the snapshot specified in the body -// Parameters: -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -// body - object for snapshot to revert supplied in the body of the operation. -func (client VolumesClient) Revert(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body VolumeRevert) (result VolumesRevertFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.Revert") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "Revert", err.Error()) - } - - req, err := client.RevertPreparer(ctx, resourceGroupName, accountName, poolName, volumeName, body) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Revert", nil, "Failure preparing request") - return - } - - result, err = client.RevertSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Revert", result.Response(), "Failure sending request") - return - } - - return -} - -// RevertPreparer prepares the Revert request. -func (client VolumesClient) RevertPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, volumeName string, body VolumeRevert) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-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.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/revert", pathParameters), - autorest.WithJSON(body), - 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 VolumesClient) RevertSender(req *http.Request) (future VolumesRevertFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RevertResponder handles the response to the Revert request. The method always -// closes the http.Response Body. -func (client VolumesClient) RevertResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update patch the specified volume -// Parameters: -// body - volume object supplied in the body of the operation. -// resourceGroupName - the name of the resource group. -// accountName - the name of the NetApp account -// poolName - the name of the capacity pool -// volumeName - the name of the volume -func (client VolumesClient) Update(ctx context.Context, body VolumePatch, resourceGroupName string, accountName string, poolName string, volumeName string) (result VolumesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VolumesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, - {TargetValue: poolName, - Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}, - {TargetValue: volumeName, - Constraints: []validation.Constraint{{Target: "volumeName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "volumeName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "volumeName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9\-_]{0,63}$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("netapp.VolumesClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, body, resourceGroupName, accountName, poolName, volumeName) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "netapp.VolumesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client VolumesClient) UpdatePreparer(ctx context.Context, body VolumePatch, resourceGroupName string, accountName string, poolName string, volumeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "accountName": autorest.Encode("path", accountName), - "poolName": autorest.Encode("path", poolName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "volumeName": autorest.Encode("path", volumeName), - } - - const APIVersion = "2021-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - body.ID = nil - body.Name = nil - body.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", pathParameters), - autorest.WithJSON(body), - 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 VolumesClient) UpdateSender(req *http.Request) (future VolumesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client VolumesClient) UpdateResponder(resp *http.Response) (result Volume, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/CHANGELOG.md deleted file mode 100644 index 52911e4cc5e4..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/_meta.json deleted file mode 100644 index 78913da4cb5a..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "f7f8f5bd19939b4a11ea626f266a362b4dd5b626", - "readme": "/_/azure-rest-api-specs/specification/appplatform/resource-manager/readme.md", - "tag": "package-preview-2022-03", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-preview-2022-03 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix /_/azure-rest-api-specs/specification/appplatform/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apiportalcustomdomains.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apiportalcustomdomains.go deleted file mode 100644 index 9d3e2c186166..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apiportalcustomdomains.go +++ /dev/null @@ -1,404 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// APIPortalCustomDomainsClient is the REST API for Azure Spring Cloud -type APIPortalCustomDomainsClient struct { - BaseClient -} - -// NewAPIPortalCustomDomainsClient creates an instance of the APIPortalCustomDomainsClient client. -func NewAPIPortalCustomDomainsClient(subscriptionID string) APIPortalCustomDomainsClient { - return NewAPIPortalCustomDomainsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAPIPortalCustomDomainsClientWithBaseURI creates an instance of the APIPortalCustomDomainsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewAPIPortalCustomDomainsClientWithBaseURI(baseURI string, subscriptionID string) APIPortalCustomDomainsClient { - return APIPortalCustomDomainsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update the API portal custom domain. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// APIPortalName - the name of API portal. -// domainName - the name of the API portal custom domain. -// APIPortalCustomDomainResource - the API portal custom domain for the create or update operation -func (client APIPortalCustomDomainsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string, APIPortalCustomDomainResource APIPortalCustomDomainResource) (result APIPortalCustomDomainsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, APIPortalName, domainName, APIPortalCustomDomainResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client APIPortalCustomDomainsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string, APIPortalCustomDomainResource APIPortalCustomDomainResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "apiPortalName": autorest.Encode("path", APIPortalName), - "domainName": autorest.Encode("path", domainName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/domains/{domainName}", pathParameters), - autorest.WithJSON(APIPortalCustomDomainResource), - 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 APIPortalCustomDomainsClient) CreateOrUpdateSender(req *http.Request) (future APIPortalCustomDomainsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client APIPortalCustomDomainsClient) CreateOrUpdateResponder(resp *http.Response) (result APIPortalCustomDomainResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the API portal custom domain. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// APIPortalName - the name of API portal. -// domainName - the name of the API portal custom domain. -func (client APIPortalCustomDomainsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string) (result APIPortalCustomDomainsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, APIPortalName, domainName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client APIPortalCustomDomainsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "apiPortalName": autorest.Encode("path", APIPortalName), - "domainName": autorest.Encode("path", domainName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/domains/{domainName}", 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 APIPortalCustomDomainsClient) DeleteSender(req *http.Request) (future APIPortalCustomDomainsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client APIPortalCustomDomainsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the API portal custom domain. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// APIPortalName - the name of API portal. -// domainName - the name of the API portal custom domain. -func (client APIPortalCustomDomainsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string) (result APIPortalCustomDomainResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, APIPortalName, domainName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client APIPortalCustomDomainsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, domainName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "apiPortalName": autorest.Encode("path", APIPortalName), - "domainName": autorest.Encode("path", domainName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/domains/{domainName}", 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 APIPortalCustomDomainsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client APIPortalCustomDomainsClient) GetResponder(resp *http.Response) (result APIPortalCustomDomainResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handle requests to list all API portal custom domains. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// APIPortalName - the name of API portal. -func (client APIPortalCustomDomainsClient) List(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (result APIPortalCustomDomainResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.List") - defer func() { - sc := -1 - if result.apcdrc.Response.Response != nil { - sc = result.apcdrc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, APIPortalName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.apcdrc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "List", resp, "Failure sending request") - return - } - - result.apcdrc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "List", resp, "Failure responding to request") - return - } - if result.apcdrc.hasNextLink() && result.apcdrc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client APIPortalCustomDomainsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "apiPortalName": autorest.Encode("path", APIPortalName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/domains", 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 APIPortalCustomDomainsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client APIPortalCustomDomainsClient) ListResponder(resp *http.Response) (result APIPortalCustomDomainResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 APIPortalCustomDomainsClient) listNextResults(ctx context.Context, lastResults APIPortalCustomDomainResourceCollection) (result APIPortalCustomDomainResourceCollection, err error) { - req, err := lastResults.aPIPortalCustomDomainResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "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, "appplatform.APIPortalCustomDomainsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client APIPortalCustomDomainsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (result APIPortalCustomDomainResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName, APIPortalName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apiportals.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apiportals.go deleted file mode 100644 index a222b672f6f8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apiportals.go +++ /dev/null @@ -1,484 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// APIPortalsClient is the REST API for Azure Spring Cloud -type APIPortalsClient struct { - BaseClient -} - -// NewAPIPortalsClient creates an instance of the APIPortalsClient client. -func NewAPIPortalsClient(subscriptionID string) APIPortalsClient { - return NewAPIPortalsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAPIPortalsClientWithBaseURI creates an instance of the APIPortalsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewAPIPortalsClientWithBaseURI(baseURI string, subscriptionID string) APIPortalsClient { - return APIPortalsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create the default API portal or update the existing API portal. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// APIPortalName - the name of API portal. -// APIPortalResource - the API portal for the create or update operation -func (client APIPortalsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, APIPortalResource APIPortalResource) (result APIPortalsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, APIPortalName, APIPortalResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client APIPortalsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, APIPortalResource APIPortalResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "apiPortalName": autorest.Encode("path", APIPortalName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}", pathParameters), - autorest.WithJSON(APIPortalResource), - 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 APIPortalsClient) CreateOrUpdateSender(req *http.Request) (future APIPortalsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client APIPortalsClient) CreateOrUpdateResponder(resp *http.Response) (result APIPortalResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the default API portal. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// APIPortalName - the name of API portal. -func (client APIPortalsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (result APIPortalsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, APIPortalName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client APIPortalsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "apiPortalName": autorest.Encode("path", APIPortalName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}", 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 APIPortalsClient) DeleteSender(req *http.Request) (future APIPortalsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client APIPortalsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the API portal and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// APIPortalName - the name of API portal. -func (client APIPortalsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (result APIPortalResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, APIPortalName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client APIPortalsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "apiPortalName": autorest.Encode("path", APIPortalName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}", 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 APIPortalsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client APIPortalsClient) GetResponder(resp *http.Response) (result APIPortalResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handles requests to list all resources in a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client APIPortalsClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result APIPortalResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.List") - defer func() { - sc := -1 - if result.aprc.Response.Response != nil { - sc = result.aprc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.aprc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "List", resp, "Failure sending request") - return - } - - result.aprc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "List", resp, "Failure responding to request") - return - } - if result.aprc.hasNextLink() && result.aprc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client APIPortalsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apiPortals", 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 APIPortalsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client APIPortalsClient) ListResponder(resp *http.Response) (result APIPortalResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 APIPortalsClient) listNextResults(ctx context.Context, lastResults APIPortalResourceCollection) (result APIPortalResourceCollection, err error) { - req, err := lastResults.aPIPortalResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "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, "appplatform.APIPortalsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client APIPortalsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result APIPortalResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName) - return -} - -// ValidateDomain check the domains are valid as well as not in use. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// APIPortalName - the name of API portal. -// validatePayload - custom domain payload to be validated -func (client APIPortalsClient) ValidateDomain(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, validatePayload CustomDomainValidatePayload) (result CustomDomainValidateResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalsClient.ValidateDomain") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: validatePayload, - Constraints: []validation.Constraint{{Target: "validatePayload.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("appplatform.APIPortalsClient", "ValidateDomain", err.Error()) - } - - req, err := client.ValidateDomainPreparer(ctx, resourceGroupName, serviceName, APIPortalName, validatePayload) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "ValidateDomain", nil, "Failure preparing request") - return - } - - resp, err := client.ValidateDomainSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "ValidateDomain", resp, "Failure sending request") - return - } - - result, err = client.ValidateDomainResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsClient", "ValidateDomain", resp, "Failure responding to request") - return - } - - return -} - -// ValidateDomainPreparer prepares the ValidateDomain request. -func (client APIPortalsClient) ValidateDomainPreparer(ctx context.Context, resourceGroupName string, serviceName string, APIPortalName string, validatePayload CustomDomainValidatePayload) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "apiPortalName": autorest.Encode("path", APIPortalName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apiPortals/{apiPortalName}/validateDomain", pathParameters), - autorest.WithJSON(validatePayload), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ValidateDomainSender sends the ValidateDomain request. The method will close the -// http.Response Body if it receives an error. -func (client APIPortalsClient) ValidateDomainSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ValidateDomainResponder handles the response to the ValidateDomain request. The method always -// closes the http.Response Body. -func (client APIPortalsClient) ValidateDomainResponder(resp *http.Response) (result CustomDomainValidateResult, err error) { - err = autorest.Respond( - resp, - 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apps.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apps.go deleted file mode 100644 index 4a18015bb301..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/apps.go +++ /dev/null @@ -1,760 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AppsClient is the REST API for Azure Spring Cloud -type AppsClient struct { - BaseClient -} - -// NewAppsClient creates an instance of the AppsClient client. -func NewAppsClient(subscriptionID string) AppsClient { - return NewAppsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAppsClientWithBaseURI creates an instance of the AppsClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewAppsClientWithBaseURI(baseURI string, subscriptionID string) AppsClient { - return AppsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create a new App or update an exiting App. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// appResource - parameters for the create or update operation -func (client AppsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, appName string, appResource AppResource) (result AppsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: appResource, - Constraints: []validation.Constraint{{Target: "appResource.Properties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "appResource.Properties.TemporaryDisk", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "appResource.Properties.TemporaryDisk.SizeInGB", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "appResource.Properties.TemporaryDisk.SizeInGB", Name: validation.InclusiveMaximum, Rule: int64(5), Chain: nil}, - {Target: "appResource.Properties.TemporaryDisk.SizeInGB", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - {Target: "appResource.Properties.PersistentDisk", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "appResource.Properties.PersistentDisk.SizeInGB", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "appResource.Properties.PersistentDisk.SizeInGB", Name: validation.InclusiveMaximum, Rule: int64(50), Chain: nil}, - {Target: "appResource.Properties.PersistentDisk.SizeInGB", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - {Target: "appResource.Properties.PersistentDisk.UsedInGB", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "appResource.Properties.PersistentDisk.UsedInGB", Name: validation.InclusiveMaximum, Rule: int64(50), Chain: nil}, - {Target: "appResource.Properties.PersistentDisk.UsedInGB", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("appplatform.AppsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, appName, appResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client AppsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, appResource AppResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}", pathParameters), - autorest.WithJSON(appResource), - 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 AppsClient) CreateOrUpdateSender(req *http.Request) (future AppsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client AppsClient) CreateOrUpdateResponder(resp *http.Response) (result AppResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete operation to delete an App. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -func (client AppsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result AppsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, appName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client AppsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}", 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 AppsClient) DeleteSender(req *http.Request) (future AppsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client AppsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get an App and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// syncStatus - indicates whether sync status -func (client AppsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, appName string, syncStatus string) (result AppResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, appName, syncStatus) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client AppsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, syncStatus string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(syncStatus) > 0 { - queryParameters["syncStatus"] = autorest.Encode("query", syncStatus) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}", 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 AppsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client AppsClient) GetResponder(resp *http.Response) (result AppResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetResourceUploadURL get an resource upload URL for an App, which may be artifacts or source archive. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -func (client AppsClient) GetResourceUploadURL(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result ResourceUploadDefinition, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.GetResourceUploadURL") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetResourceUploadURLPreparer(ctx, resourceGroupName, serviceName, appName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "GetResourceUploadURL", nil, "Failure preparing request") - return - } - - resp, err := client.GetResourceUploadURLSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "GetResourceUploadURL", resp, "Failure sending request") - return - } - - result, err = client.GetResourceUploadURLResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "GetResourceUploadURL", resp, "Failure responding to request") - return - } - - return -} - -// GetResourceUploadURLPreparer prepares the GetResourceUploadURL request. -func (client AppsClient) GetResourceUploadURLPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/getResourceUploadUrl", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetResourceUploadURLSender sends the GetResourceUploadURL request. The method will close the -// http.Response Body if it receives an error. -func (client AppsClient) GetResourceUploadURLSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResourceUploadURLResponder handles the response to the GetResourceUploadURL request. The method always -// closes the http.Response Body. -func (client AppsClient) GetResourceUploadURLResponder(resp *http.Response) (result ResourceUploadDefinition, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handles requests to list all resources in a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client AppsClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result AppResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.List") - defer func() { - sc := -1 - if result.arc.Response.Response != nil { - sc = result.arc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.arc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "List", resp, "Failure sending request") - return - } - - result.arc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "List", resp, "Failure responding to request") - return - } - if result.arc.hasNextLink() && result.arc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AppsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps", 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 AppsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AppsClient) ListResponder(resp *http.Response) (result AppResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 AppsClient) listNextResults(ctx context.Context, lastResults AppResourceCollection) (result AppResourceCollection, err error) { - req, err := lastResults.appResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.AppsClient", "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, "appplatform.AppsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AppsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result AppResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName) - return -} - -// SetActiveDeployments set existing Deployment under the app as active -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// activeDeploymentCollection - a list of Deployment name to be active. -func (client AppsClient) SetActiveDeployments(ctx context.Context, resourceGroupName string, serviceName string, appName string, activeDeploymentCollection ActiveDeploymentCollection) (result AppsSetActiveDeploymentsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.SetActiveDeployments") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.SetActiveDeploymentsPreparer(ctx, resourceGroupName, serviceName, appName, activeDeploymentCollection) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "SetActiveDeployments", nil, "Failure preparing request") - return - } - - result, err = client.SetActiveDeploymentsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "SetActiveDeployments", result.Response(), "Failure sending request") - return - } - - return -} - -// SetActiveDeploymentsPreparer prepares the SetActiveDeployments request. -func (client AppsClient) SetActiveDeploymentsPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, activeDeploymentCollection ActiveDeploymentCollection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/setActiveDeployments", pathParameters), - autorest.WithJSON(activeDeploymentCollection), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetActiveDeploymentsSender sends the SetActiveDeployments request. The method will close the -// http.Response Body if it receives an error. -func (client AppsClient) SetActiveDeploymentsSender(req *http.Request) (future AppsSetActiveDeploymentsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// SetActiveDeploymentsResponder handles the response to the SetActiveDeployments request. The method always -// closes the http.Response Body. -func (client AppsClient) SetActiveDeploymentsResponder(resp *http.Response) (result AppResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Update operation to update an exiting App. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// appResource - parameters for the update operation -func (client AppsClient) Update(ctx context.Context, resourceGroupName string, serviceName string, appName string, appResource AppResource) (result AppsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, appName, appResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client AppsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, appResource AppResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}", pathParameters), - autorest.WithJSON(appResource), - 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 AppsClient) UpdateSender(req *http.Request) (future AppsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client AppsClient) UpdateResponder(resp *http.Response) (result AppResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ValidateDomain check the resource name is valid as well as not in use. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// validatePayload - custom domain payload to be validated -func (client AppsClient) ValidateDomain(ctx context.Context, resourceGroupName string, serviceName string, appName string, validatePayload CustomDomainValidatePayload) (result CustomDomainValidateResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppsClient.ValidateDomain") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: validatePayload, - Constraints: []validation.Constraint{{Target: "validatePayload.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("appplatform.AppsClient", "ValidateDomain", err.Error()) - } - - req, err := client.ValidateDomainPreparer(ctx, resourceGroupName, serviceName, appName, validatePayload) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "ValidateDomain", nil, "Failure preparing request") - return - } - - resp, err := client.ValidateDomainSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "ValidateDomain", resp, "Failure sending request") - return - } - - result, err = client.ValidateDomainResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsClient", "ValidateDomain", resp, "Failure responding to request") - return - } - - return -} - -// ValidateDomainPreparer prepares the ValidateDomain request. -func (client AppsClient) ValidateDomainPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, validatePayload CustomDomainValidatePayload) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/validateDomain", pathParameters), - autorest.WithJSON(validatePayload), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ValidateDomainSender sends the ValidateDomain request. The method will close the -// http.Response Body if it receives an error. -func (client AppsClient) ValidateDomainSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ValidateDomainResponder handles the response to the ValidateDomain request. The method always -// closes the http.Response Body. -func (client AppsClient) ValidateDomainResponder(resp *http.Response) (result CustomDomainValidateResult, err error) { - err = autorest.Respond( - resp, - 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/bindings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/bindings.go deleted file mode 100644 index 295d7db312b0..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/bindings.go +++ /dev/null @@ -1,490 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// BindingsClient is the REST API for Azure Spring Cloud -type BindingsClient struct { - BaseClient -} - -// NewBindingsClient creates an instance of the BindingsClient client. -func NewBindingsClient(subscriptionID string) BindingsClient { - return NewBindingsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewBindingsClientWithBaseURI creates an instance of the BindingsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewBindingsClientWithBaseURI(baseURI string, subscriptionID string) BindingsClient { - return BindingsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create a new Binding or update an exiting Binding. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// bindingName - the name of the Binding resource. -// bindingResource - parameters for the create or update operation -func (client BindingsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string, bindingResource BindingResource) (result BindingsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, appName, bindingName, bindingResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client BindingsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string, bindingResource BindingResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "bindingName": autorest.Encode("path", bindingName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings/{bindingName}", pathParameters), - autorest.WithJSON(bindingResource), - 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 BindingsClient) CreateOrUpdateSender(req *http.Request) (future BindingsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client BindingsClient) CreateOrUpdateResponder(resp *http.Response) (result BindingResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete operation to delete a Binding. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// bindingName - the name of the Binding resource. -func (client BindingsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string) (result BindingsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, appName, bindingName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client BindingsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "bindingName": autorest.Encode("path", bindingName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings/{bindingName}", 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 BindingsClient) DeleteSender(req *http.Request) (future BindingsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client BindingsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get a Binding and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// bindingName - the name of the Binding resource. -func (client BindingsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string) (result BindingResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, appName, bindingName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client BindingsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "bindingName": autorest.Encode("path", bindingName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings/{bindingName}", 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 BindingsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client BindingsClient) GetResponder(resp *http.Response) (result BindingResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handles requests to list all resources in an App. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -func (client BindingsClient) List(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result BindingResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.List") - defer func() { - sc := -1 - if result.brc.Response.Response != nil { - sc = result.brc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, appName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.brc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "List", resp, "Failure sending request") - return - } - - result.brc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "List", resp, "Failure responding to request") - return - } - if result.brc.hasNextLink() && result.brc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client BindingsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings", 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 BindingsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client BindingsClient) ListResponder(resp *http.Response) (result BindingResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 BindingsClient) listNextResults(ctx context.Context, lastResults BindingResourceCollection) (result BindingResourceCollection, err error) { - req, err := lastResults.bindingResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.BindingsClient", "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, "appplatform.BindingsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client BindingsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result BindingResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName, appName) - return -} - -// Update operation to update an exiting Binding. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// bindingName - the name of the Binding resource. -// bindingResource - parameters for the update operation -func (client BindingsClient) Update(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string, bindingResource BindingResource) (result BindingsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BindingsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, appName, bindingName, bindingResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client BindingsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, bindingName string, bindingResource BindingResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "bindingName": autorest.Encode("path", bindingName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/bindings/{bindingName}", pathParameters), - autorest.WithJSON(bindingResource), - 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 BindingsClient) UpdateSender(req *http.Request) (future BindingsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client BindingsClient) UpdateResponder(resp *http.Response) (result BindingResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildpackbinding.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildpackbinding.go deleted file mode 100644 index ef012ede250a..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildpackbinding.go +++ /dev/null @@ -1,412 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// BuildpackBindingClient is the REST API for Azure Spring Cloud -type BuildpackBindingClient struct { - BaseClient -} - -// NewBuildpackBindingClient creates an instance of the BuildpackBindingClient client. -func NewBuildpackBindingClient(subscriptionID string) BuildpackBindingClient { - return NewBuildpackBindingClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewBuildpackBindingClientWithBaseURI creates an instance of the BuildpackBindingClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewBuildpackBindingClientWithBaseURI(baseURI string, subscriptionID string) BuildpackBindingClient { - return BuildpackBindingClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a buildpack binding. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// builderName - the name of the builder resource. -// buildpackBindingName - the name of the Buildpack Binding Name -// buildpackBinding - the target buildpack binding for the create or update operation -func (client BuildpackBindingClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string, buildpackBinding BuildpackBindingResource) (result BuildpackBindingCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName, buildpackBindingName, buildpackBinding) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client BuildpackBindingClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string, buildpackBinding BuildpackBindingResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "builderName": autorest.Encode("path", builderName), - "buildpackBindingName": autorest.Encode("path", buildpackBindingName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}/buildpackBindings/{buildpackBindingName}", pathParameters), - autorest.WithJSON(buildpackBinding), - 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 BuildpackBindingClient) CreateOrUpdateSender(req *http.Request) (future BuildpackBindingCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client BuildpackBindingClient) CreateOrUpdateResponder(resp *http.Response) (result BuildpackBindingResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete operation to delete a Buildpack Binding -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// builderName - the name of the builder resource. -// buildpackBindingName - the name of the Buildpack Binding Name -func (client BuildpackBindingClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string) (result BuildpackBindingDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName, buildpackBindingName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client BuildpackBindingClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "builderName": autorest.Encode("path", builderName), - "buildpackBindingName": autorest.Encode("path", buildpackBindingName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}/buildpackBindings/{buildpackBindingName}", 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 BuildpackBindingClient) DeleteSender(req *http.Request) (future BuildpackBindingDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client BuildpackBindingClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get a buildpack binding by name. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// builderName - the name of the builder resource. -// buildpackBindingName - the name of the Buildpack Binding Name -func (client BuildpackBindingClient) Get(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string) (result BuildpackBindingResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName, buildpackBindingName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client BuildpackBindingClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, buildpackBindingName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "builderName": autorest.Encode("path", builderName), - "buildpackBindingName": autorest.Encode("path", buildpackBindingName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}/buildpackBindings/{buildpackBindingName}", 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 BuildpackBindingClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client BuildpackBindingClient) GetResponder(resp *http.Response) (result BuildpackBindingResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handles requests to list all buildpack bindings in a builder. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// builderName - the name of the builder resource. -func (client BuildpackBindingClient) List(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (result BuildpackBindingResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.List") - defer func() { - sc := -1 - if result.bbrc.Response.Response != nil { - sc = result.bbrc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.bbrc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "List", resp, "Failure sending request") - return - } - - result.bbrc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "List", resp, "Failure responding to request") - return - } - if result.bbrc.hasNextLink() && result.bbrc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client BuildpackBindingClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "builderName": autorest.Encode("path", builderName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}/buildpackBindings", 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 BuildpackBindingClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client BuildpackBindingClient) ListResponder(resp *http.Response) (result BuildpackBindingResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 BuildpackBindingClient) listNextResults(ctx context.Context, lastResults BuildpackBindingResourceCollection) (result BuildpackBindingResourceCollection, err error) { - req, err := lastResults.buildpackBindingResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "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, "appplatform.BuildpackBindingClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client BuildpackBindingClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (result BuildpackBindingResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName, buildServiceName, builderName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildservice.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildservice.go deleted file mode 100644 index 60108e5e3d70..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildservice.go +++ /dev/null @@ -1,1203 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// BuildServiceClient is the REST API for Azure Spring Cloud -type BuildServiceClient struct { - BaseClient -} - -// NewBuildServiceClient creates an instance of the BuildServiceClient client. -func NewBuildServiceClient(subscriptionID string) BuildServiceClient { - return NewBuildServiceClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewBuildServiceClientWithBaseURI creates an instance of the BuildServiceClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewBuildServiceClientWithBaseURI(baseURI string, subscriptionID string) BuildServiceClient { - return BuildServiceClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdateBuild create or update a KPack build. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// buildName - the name of the build resource. -// buildParameter - parameters for the create or update operation -func (client BuildServiceClient) CreateOrUpdateBuild(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildParameter Build) (result Build, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.CreateOrUpdateBuild") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdateBuildPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName, buildParameter) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "CreateOrUpdateBuild", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateBuildSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "CreateOrUpdateBuild", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateBuildResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "CreateOrUpdateBuild", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdateBuildPreparer prepares the CreateOrUpdateBuild request. -func (client BuildServiceClient) CreateOrUpdateBuildPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildParameter Build) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildName": autorest.Encode("path", buildName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}", pathParameters), - autorest.WithJSON(buildParameter), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateBuildSender sends the CreateOrUpdateBuild request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) CreateOrUpdateBuildSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateBuildResponder handles the response to the CreateOrUpdateBuild request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) CreateOrUpdateBuildResponder(resp *http.Response) (result Build, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetBuild get a KPack build. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// buildName - the name of the build resource. -func (client BuildServiceClient) GetBuild(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (result Build, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetBuild") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetBuildPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuild", nil, "Failure preparing request") - return - } - - resp, err := client.GetBuildSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuild", resp, "Failure sending request") - return - } - - result, err = client.GetBuildResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuild", resp, "Failure responding to request") - return - } - - return -} - -// GetBuildPreparer prepares the GetBuild request. -func (client BuildServiceClient) GetBuildPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildName": autorest.Encode("path", buildName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetBuildSender sends the GetBuild request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) GetBuildSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetBuildResponder handles the response to the GetBuild request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) GetBuildResponder(resp *http.Response) (result Build, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetBuildResult get a KPack build result. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// buildName - the name of the build resource. -// buildResultName - the name of the build result resource. -func (client BuildServiceClient) GetBuildResult(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildResultName string) (result BuildResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetBuildResult") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetBuildResultPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName, buildResultName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResult", nil, "Failure preparing request") - return - } - - resp, err := client.GetBuildResultSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResult", resp, "Failure sending request") - return - } - - result, err = client.GetBuildResultResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResult", resp, "Failure responding to request") - return - } - - return -} - -// GetBuildResultPreparer prepares the GetBuildResult request. -func (client BuildServiceClient) GetBuildResultPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildResultName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildName": autorest.Encode("path", buildName), - "buildResultName": autorest.Encode("path", buildResultName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}/results/{buildResultName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetBuildResultSender sends the GetBuildResult request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) GetBuildResultSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetBuildResultResponder handles the response to the GetBuildResult request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) GetBuildResultResponder(resp *http.Response) (result BuildResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetBuildResultLog get a KPack build result log download URL. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// buildName - the name of the build resource. -// buildResultName - the name of the build result resource. -func (client BuildServiceClient) GetBuildResultLog(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildResultName string) (result BuildResultLog, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetBuildResultLog") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetBuildResultLogPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName, buildResultName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResultLog", nil, "Failure preparing request") - return - } - - resp, err := client.GetBuildResultLogSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResultLog", resp, "Failure sending request") - return - } - - result, err = client.GetBuildResultLogResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildResultLog", resp, "Failure responding to request") - return - } - - return -} - -// GetBuildResultLogPreparer prepares the GetBuildResultLog request. -func (client BuildServiceClient) GetBuildResultLogPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string, buildResultName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildName": autorest.Encode("path", buildName), - "buildResultName": autorest.Encode("path", buildResultName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}/results/{buildResultName}/getLogFileUrl", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetBuildResultLogSender sends the GetBuildResultLog request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) GetBuildResultLogSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetBuildResultLogResponder handles the response to the GetBuildResultLog request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) GetBuildResultLogResponder(resp *http.Response) (result BuildResultLog, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetBuildService get a build service resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -func (client BuildServiceClient) GetBuildService(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildService, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetBuildService") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetBuildServicePreparer(ctx, resourceGroupName, serviceName, buildServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildService", nil, "Failure preparing request") - return - } - - resp, err := client.GetBuildServiceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildService", resp, "Failure sending request") - return - } - - result, err = client.GetBuildServiceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetBuildService", resp, "Failure responding to request") - return - } - - return -} - -// GetBuildServicePreparer prepares the GetBuildService request. -func (client BuildServiceClient) GetBuildServicePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetBuildServiceSender sends the GetBuildService request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) GetBuildServiceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetBuildServiceResponder handles the response to the GetBuildService request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) GetBuildServiceResponder(resp *http.Response) (result BuildService, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetResourceUploadURL get an resource upload URL for build service, which may be artifacts or source archive. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -func (client BuildServiceClient) GetResourceUploadURL(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result ResourceUploadDefinition, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetResourceUploadURL") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetResourceUploadURLPreparer(ctx, resourceGroupName, serviceName, buildServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetResourceUploadURL", nil, "Failure preparing request") - return - } - - resp, err := client.GetResourceUploadURLSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetResourceUploadURL", resp, "Failure sending request") - return - } - - result, err = client.GetResourceUploadURLResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetResourceUploadURL", resp, "Failure responding to request") - return - } - - return -} - -// GetResourceUploadURLPreparer prepares the GetResourceUploadURL request. -func (client BuildServiceClient) GetResourceUploadURLPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/getResourceUploadUrl", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetResourceUploadURLSender sends the GetResourceUploadURL request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) GetResourceUploadURLSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResourceUploadURLResponder handles the response to the GetResourceUploadURL request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) GetResourceUploadURLResponder(resp *http.Response) (result ResourceUploadDefinition, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetSupportedBuildpack get the supported buildpack resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// buildpackName - the name of the buildpack resource. -func (client BuildServiceClient) GetSupportedBuildpack(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildpackName string) (result SupportedBuildpackResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetSupportedBuildpack") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetSupportedBuildpackPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildpackName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedBuildpack", nil, "Failure preparing request") - return - } - - resp, err := client.GetSupportedBuildpackSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedBuildpack", resp, "Failure sending request") - return - } - - result, err = client.GetSupportedBuildpackResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedBuildpack", resp, "Failure responding to request") - return - } - - return -} - -// GetSupportedBuildpackPreparer prepares the GetSupportedBuildpack request. -func (client BuildServiceClient) GetSupportedBuildpackPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildpackName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildpackName": autorest.Encode("path", buildpackName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedBuildpacks/{buildpackName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSupportedBuildpackSender sends the GetSupportedBuildpack request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) GetSupportedBuildpackSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetSupportedBuildpackResponder handles the response to the GetSupportedBuildpack request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) GetSupportedBuildpackResponder(resp *http.Response) (result SupportedBuildpackResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetSupportedStack get the supported stack resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// stackName - the name of the stack resource. -func (client BuildServiceClient) GetSupportedStack(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, stackName string) (result SupportedStackResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.GetSupportedStack") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetSupportedStackPreparer(ctx, resourceGroupName, serviceName, buildServiceName, stackName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedStack", nil, "Failure preparing request") - return - } - - resp, err := client.GetSupportedStackSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedStack", resp, "Failure sending request") - return - } - - result, err = client.GetSupportedStackResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "GetSupportedStack", resp, "Failure responding to request") - return - } - - return -} - -// GetSupportedStackPreparer prepares the GetSupportedStack request. -func (client BuildServiceClient) GetSupportedStackPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, stackName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "stackName": autorest.Encode("path", stackName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedStacks/{stackName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSupportedStackSender sends the GetSupportedStack request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) GetSupportedStackSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetSupportedStackResponder handles the response to the GetSupportedStack request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) GetSupportedStackResponder(resp *http.Response) (result SupportedStackResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListBuildResults list KPack build results. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// buildName - the name of the build resource. -func (client BuildServiceClient) ListBuildResults(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (result BuildResultCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuildResults") - defer func() { - sc := -1 - if result.brc.Response.Response != nil { - sc = result.brc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBuildResultsNextResults - req, err := client.ListBuildResultsPreparer(ctx, resourceGroupName, serviceName, buildServiceName, buildName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildResults", nil, "Failure preparing request") - return - } - - resp, err := client.ListBuildResultsSender(req) - if err != nil { - result.brc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildResults", resp, "Failure sending request") - return - } - - result.brc, err = client.ListBuildResultsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildResults", resp, "Failure responding to request") - return - } - if result.brc.hasNextLink() && result.brc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBuildResultsPreparer prepares the ListBuildResults request. -func (client BuildServiceClient) ListBuildResultsPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildName": autorest.Encode("path", buildName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds/{buildName}/results", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBuildResultsSender sends the ListBuildResults request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) ListBuildResultsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBuildResultsResponder handles the response to the ListBuildResults request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) ListBuildResultsResponder(resp *http.Response) (result BuildResultCollection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBuildResultsNextResults retrieves the next set of results, if any. -func (client BuildServiceClient) listBuildResultsNextResults(ctx context.Context, lastResults BuildResultCollection) (result BuildResultCollection, err error) { - req, err := lastResults.buildResultCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildResultsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBuildResultsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildResultsNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBuildResultsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildResultsNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBuildResultsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BuildServiceClient) ListBuildResultsComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, buildName string) (result BuildResultCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuildResults") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBuildResults(ctx, resourceGroupName, serviceName, buildServiceName, buildName) - return -} - -// ListBuilds list KPack builds. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -func (client BuildServiceClient) ListBuilds(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuilds") - defer func() { - sc := -1 - if result.bc.Response.Response != nil { - sc = result.bc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBuildsNextResults - req, err := client.ListBuildsPreparer(ctx, resourceGroupName, serviceName, buildServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuilds", nil, "Failure preparing request") - return - } - - resp, err := client.ListBuildsSender(req) - if err != nil { - result.bc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuilds", resp, "Failure sending request") - return - } - - result.bc, err = client.ListBuildsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuilds", resp, "Failure responding to request") - return - } - if result.bc.hasNextLink() && result.bc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBuildsPreparer prepares the ListBuilds request. -func (client BuildServiceClient) ListBuildsPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builds", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBuildsSender sends the ListBuilds request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) ListBuildsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBuildsResponder handles the response to the ListBuilds request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) ListBuildsResponder(resp *http.Response) (result BuildCollection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBuildsNextResults retrieves the next set of results, if any. -func (client BuildServiceClient) listBuildsNextResults(ctx context.Context, lastResults BuildCollection) (result BuildCollection, err error) { - req, err := lastResults.buildCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBuildsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildsNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBuildsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildsNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBuildsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BuildServiceClient) ListBuildsComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuilds") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBuilds(ctx, resourceGroupName, serviceName, buildServiceName) - return -} - -// ListBuildServices list build services resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client BuildServiceClient) ListBuildServices(ctx context.Context, resourceGroupName string, serviceName string) (result BuildServiceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuildServices") - defer func() { - sc := -1 - if result.bsc.Response.Response != nil { - sc = result.bsc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBuildServicesNextResults - req, err := client.ListBuildServicesPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildServices", nil, "Failure preparing request") - return - } - - resp, err := client.ListBuildServicesSender(req) - if err != nil { - result.bsc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildServices", resp, "Failure sending request") - return - } - - result.bsc, err = client.ListBuildServicesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListBuildServices", resp, "Failure responding to request") - return - } - if result.bsc.hasNextLink() && result.bsc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBuildServicesPreparer prepares the ListBuildServices request. -func (client BuildServiceClient) ListBuildServicesPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBuildServicesSender sends the ListBuildServices request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) ListBuildServicesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBuildServicesResponder handles the response to the ListBuildServices request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) ListBuildServicesResponder(resp *http.Response) (result BuildServiceCollection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBuildServicesNextResults retrieves the next set of results, if any. -func (client BuildServiceClient) listBuildServicesNextResults(ctx context.Context, lastResults BuildServiceCollection) (result BuildServiceCollection, err error) { - req, err := lastResults.buildServiceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildServicesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBuildServicesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildServicesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBuildServicesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "listBuildServicesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBuildServicesComplete enumerates all values, automatically crossing page boundaries as required. -func (client BuildServiceClient) ListBuildServicesComplete(ctx context.Context, resourceGroupName string, serviceName string) (result BuildServiceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListBuildServices") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBuildServices(ctx, resourceGroupName, serviceName) - return -} - -// ListSupportedBuildpacks get all supported buildpacks. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -func (client BuildServiceClient) ListSupportedBuildpacks(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result SupportedBuildpacksCollection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListSupportedBuildpacks") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListSupportedBuildpacksPreparer(ctx, resourceGroupName, serviceName, buildServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedBuildpacks", nil, "Failure preparing request") - return - } - - resp, err := client.ListSupportedBuildpacksSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedBuildpacks", resp, "Failure sending request") - return - } - - result, err = client.ListSupportedBuildpacksResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedBuildpacks", resp, "Failure responding to request") - return - } - - return -} - -// ListSupportedBuildpacksPreparer prepares the ListSupportedBuildpacks request. -func (client BuildServiceClient) ListSupportedBuildpacksPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedBuildpacks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSupportedBuildpacksSender sends the ListSupportedBuildpacks request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) ListSupportedBuildpacksSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListSupportedBuildpacksResponder handles the response to the ListSupportedBuildpacks request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) ListSupportedBuildpacksResponder(resp *http.Response) (result SupportedBuildpacksCollection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListSupportedStacks get all supported stacks. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -func (client BuildServiceClient) ListSupportedStacks(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result SupportedStacksCollection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceClient.ListSupportedStacks") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListSupportedStacksPreparer(ctx, resourceGroupName, serviceName, buildServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedStacks", nil, "Failure preparing request") - return - } - - resp, err := client.ListSupportedStacksSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedStacks", resp, "Failure sending request") - return - } - - result, err = client.ListSupportedStacksResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceClient", "ListSupportedStacks", resp, "Failure responding to request") - return - } - - return -} - -// ListSupportedStacksPreparer prepares the ListSupportedStacks request. -func (client BuildServiceClient) ListSupportedStacksPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/supportedStacks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSupportedStacksSender sends the ListSupportedStacks request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceClient) ListSupportedStacksSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListSupportedStacksResponder handles the response to the ListSupportedStacks request. The method always -// closes the http.Response Body. -func (client BuildServiceClient) ListSupportedStacksResponder(resp *http.Response) (result SupportedStacksCollection, err error) { - err = autorest.Respond( - resp, - 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildserviceagentpool.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildserviceagentpool.go deleted file mode 100644 index 9128a9bae2bc..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildserviceagentpool.go +++ /dev/null @@ -1,321 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// BuildServiceAgentPoolClient is the REST API for Azure Spring Cloud -type BuildServiceAgentPoolClient struct { - BaseClient -} - -// NewBuildServiceAgentPoolClient creates an instance of the BuildServiceAgentPoolClient client. -func NewBuildServiceAgentPoolClient(subscriptionID string) BuildServiceAgentPoolClient { - return NewBuildServiceAgentPoolClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewBuildServiceAgentPoolClientWithBaseURI creates an instance of the BuildServiceAgentPoolClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewBuildServiceAgentPoolClientWithBaseURI(baseURI string, subscriptionID string) BuildServiceAgentPoolClient { - return BuildServiceAgentPoolClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get get build service agent pool. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// agentPoolName - the name of the build service agent pool resource. -func (client BuildServiceAgentPoolClient) Get(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, agentPoolName string) (result BuildServiceAgentPoolResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, buildServiceName, agentPoolName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client BuildServiceAgentPoolClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, agentPoolName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "agentPoolName": autorest.Encode("path", agentPoolName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/agentPools/{agentPoolName}", 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 BuildServiceAgentPoolClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client BuildServiceAgentPoolClient) GetResponder(resp *http.Response) (result BuildServiceAgentPoolResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list build service agent pool. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -func (client BuildServiceAgentPoolClient) List(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildServiceAgentPoolResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolClient.List") - defer func() { - sc := -1 - if result.bsaprc.Response.Response != nil { - sc = result.bsaprc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, buildServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.bsaprc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "List", resp, "Failure sending request") - return - } - - result.bsaprc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "List", resp, "Failure responding to request") - return - } - if result.bsaprc.hasNextLink() && result.bsaprc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client BuildServiceAgentPoolClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/agentPools", 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 BuildServiceAgentPoolClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client BuildServiceAgentPoolClient) ListResponder(resp *http.Response) (result BuildServiceAgentPoolResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 BuildServiceAgentPoolClient) listNextResults(ctx context.Context, lastResults BuildServiceAgentPoolResourceCollection) (result BuildServiceAgentPoolResourceCollection, err error) { - req, err := lastResults.buildServiceAgentPoolResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "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, "appplatform.BuildServiceAgentPoolClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client BuildServiceAgentPoolClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuildServiceAgentPoolResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName, buildServiceName) - return -} - -// UpdatePut create or update build service agent pool. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// agentPoolName - the name of the build service agent pool resource. -// agentPoolResource - parameters for the update operation -func (client BuildServiceAgentPoolClient) UpdatePut(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, agentPoolName string, agentPoolResource BuildServiceAgentPoolResource) (result BuildServiceAgentPoolUpdatePutFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolClient.UpdatePut") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePutPreparer(ctx, resourceGroupName, serviceName, buildServiceName, agentPoolName, agentPoolResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "UpdatePut", nil, "Failure preparing request") - return - } - - result, err = client.UpdatePutSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolClient", "UpdatePut", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePutPreparer prepares the UpdatePut request. -func (client BuildServiceAgentPoolClient) UpdatePutPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, agentPoolName string, agentPoolResource BuildServiceAgentPoolResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "agentPoolName": autorest.Encode("path", agentPoolName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/agentPools/{agentPoolName}", pathParameters), - autorest.WithJSON(agentPoolResource), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdatePutSender sends the UpdatePut request. The method will close the -// http.Response Body if it receives an error. -func (client BuildServiceAgentPoolClient) UpdatePutSender(req *http.Request) (future BuildServiceAgentPoolUpdatePutFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdatePutResponder handles the response to the UpdatePut request. The method always -// closes the http.Response Body. -func (client BuildServiceAgentPoolClient) UpdatePutResponder(resp *http.Response) (result BuildServiceAgentPoolResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildservicebuilder.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildservicebuilder.go deleted file mode 100644 index 072806cc59dd..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/buildservicebuilder.go +++ /dev/null @@ -1,404 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// BuildServiceBuilderClient is the REST API for Azure Spring Cloud -type BuildServiceBuilderClient struct { - BaseClient -} - -// NewBuildServiceBuilderClient creates an instance of the BuildServiceBuilderClient client. -func NewBuildServiceBuilderClient(subscriptionID string) BuildServiceBuilderClient { - return NewBuildServiceBuilderClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewBuildServiceBuilderClientWithBaseURI creates an instance of the BuildServiceBuilderClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewBuildServiceBuilderClientWithBaseURI(baseURI string, subscriptionID string) BuildServiceBuilderClient { - return BuildServiceBuilderClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a KPack builder. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// builderName - the name of the builder resource. -// builderResource - the target builder for the create or update operation -func (client BuildServiceBuilderClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, builderResource BuilderResource) (result BuildServiceBuilderCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName, builderResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client BuildServiceBuilderClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string, builderResource BuilderResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "builderName": autorest.Encode("path", builderName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}", pathParameters), - autorest.WithJSON(builderResource), - 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 BuildServiceBuilderClient) CreateOrUpdateSender(req *http.Request) (future BuildServiceBuilderCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client BuildServiceBuilderClient) CreateOrUpdateResponder(resp *http.Response) (result BuilderResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete a KPack builder. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// builderName - the name of the builder resource. -func (client BuildServiceBuilderClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (result BuildServiceBuilderDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client BuildServiceBuilderClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "builderName": autorest.Encode("path", builderName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}", 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 BuildServiceBuilderClient) DeleteSender(req *http.Request) (future BuildServiceBuilderDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client BuildServiceBuilderClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get a KPack builder. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -// builderName - the name of the builder resource. -func (client BuildServiceBuilderClient) Get(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (result BuilderResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, buildServiceName, builderName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client BuildServiceBuilderClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string, builderName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "builderName": autorest.Encode("path", builderName), - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders/{builderName}", 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 BuildServiceBuilderClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client BuildServiceBuilderClient) GetResponder(resp *http.Response) (result BuilderResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list KPack builders result. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// buildServiceName - the name of the build service resource. -func (client BuildServiceBuilderClient) List(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuilderResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.List") - defer func() { - sc := -1 - if result.brc.Response.Response != nil { - sc = result.brc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, buildServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.brc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "List", resp, "Failure sending request") - return - } - - result.brc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "List", resp, "Failure responding to request") - return - } - if result.brc.hasNextLink() && result.brc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client BuildServiceBuilderClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "buildServiceName": autorest.Encode("path", buildServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/buildServices/{buildServiceName}/builders", 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 BuildServiceBuilderClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client BuildServiceBuilderClient) ListResponder(resp *http.Response) (result BuilderResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 BuildServiceBuilderClient) listNextResults(ctx context.Context, lastResults BuilderResourceCollection) (result BuilderResourceCollection, err error) { - req, err := lastResults.builderResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "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, "appplatform.BuildServiceBuilderClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client BuildServiceBuilderClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, buildServiceName string) (result BuilderResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceBuilderClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName, buildServiceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/certificates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/certificates.go deleted file mode 100644 index f3bc4c1932fc..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/certificates.go +++ /dev/null @@ -1,395 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// CertificatesClient is the REST API for Azure Spring Cloud -type CertificatesClient struct { - BaseClient -} - -// NewCertificatesClient creates an instance of the CertificatesClient client. -func NewCertificatesClient(subscriptionID string) CertificatesClient { - return NewCertificatesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewCertificatesClientWithBaseURI creates an instance of the CertificatesClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewCertificatesClientWithBaseURI(baseURI string, subscriptionID string) CertificatesClient { - return CertificatesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update certificate resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// certificateName - the name of the certificate resource. -// certificateResource - parameters for the create or update operation -func (client CertificatesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, certificateName string, certificateResource CertificateResource) (result CertificatesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, certificateName, certificateResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client CertificatesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, certificateName string, certificateResource CertificateResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "certificateName": autorest.Encode("path", certificateName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/certificates/{certificateName}", pathParameters), - autorest.WithJSON(certificateResource), - 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 CertificatesClient) CreateOrUpdateSender(req *http.Request) (future CertificatesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client CertificatesClient) CreateOrUpdateResponder(resp *http.Response) (result CertificateResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the certificate resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// certificateName - the name of the certificate resource. -func (client CertificatesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, certificateName string) (result CertificatesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, certificateName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client CertificatesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, certificateName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "certificateName": autorest.Encode("path", certificateName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/certificates/{certificateName}", 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 CertificatesClient) DeleteSender(req *http.Request) (future CertificatesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client CertificatesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the certificate resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// certificateName - the name of the certificate resource. -func (client CertificatesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, certificateName string) (result CertificateResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, certificateName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client CertificatesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, certificateName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "certificateName": autorest.Encode("path", certificateName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/certificates/{certificateName}", 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 CertificatesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client CertificatesClient) GetResponder(resp *http.Response) (result CertificateResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all the certificates of one user. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client CertificatesClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result CertificateResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.List") - defer func() { - sc := -1 - if result.crc.Response.Response != nil { - sc = result.crc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.crc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "List", resp, "Failure sending request") - return - } - - result.crc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "List", resp, "Failure responding to request") - return - } - if result.crc.hasNextLink() && result.crc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client CertificatesClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/certificates", 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 CertificatesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client CertificatesClient) ListResponder(resp *http.Response) (result CertificateResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 CertificatesClient) listNextResults(ctx context.Context, lastResults CertificateResourceCollection) (result CertificateResourceCollection, err error) { - req, err := lastResults.certificateResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "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, "appplatform.CertificatesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client CertificatesClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result CertificateResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificatesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/client.go deleted file mode 100644 index 61b86478046f..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/client.go +++ /dev/null @@ -1,41 +0,0 @@ -// Package appplatform implements the Azure ARM Appplatform service API version 2022-03-01-preview. -// -// REST API for Azure Spring Cloud -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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 Appplatform - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Appplatform. -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 using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/configservers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/configservers.go deleted file mode 100644 index ac40cc94af31..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/configservers.go +++ /dev/null @@ -1,376 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ConfigServersClient is the REST API for Azure Spring Cloud -type ConfigServersClient struct { - BaseClient -} - -// NewConfigServersClient creates an instance of the ConfigServersClient client. -func NewConfigServersClient(subscriptionID string) ConfigServersClient { - return NewConfigServersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewConfigServersClientWithBaseURI creates an instance of the ConfigServersClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewConfigServersClientWithBaseURI(baseURI string, subscriptionID string) ConfigServersClient { - return ConfigServersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get get the config server and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ConfigServersClient) Get(ctx context.Context, resourceGroupName string, serviceName string) (result ConfigServerResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigServersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ConfigServersClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configServers/default", 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 ConfigServersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ConfigServersClient) GetResponder(resp *http.Response) (result ConfigServerResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdatePatch update the config server. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// configServerResource - parameters for the update operation -func (client ConfigServersClient) UpdatePatch(ctx context.Context, resourceGroupName string, serviceName string, configServerResource ConfigServerResource) (result ConfigServersUpdatePatchFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigServersClient.UpdatePatch") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePatchPreparer(ctx, resourceGroupName, serviceName, configServerResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "UpdatePatch", nil, "Failure preparing request") - return - } - - result, err = client.UpdatePatchSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "UpdatePatch", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePatchPreparer prepares the UpdatePatch request. -func (client ConfigServersClient) UpdatePatchPreparer(ctx context.Context, resourceGroupName string, serviceName string, configServerResource ConfigServerResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/configServers/default", pathParameters), - autorest.WithJSON(configServerResource), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdatePatchSender sends the UpdatePatch request. The method will close the -// http.Response Body if it receives an error. -func (client ConfigServersClient) UpdatePatchSender(req *http.Request) (future ConfigServersUpdatePatchFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdatePatchResponder handles the response to the UpdatePatch request. The method always -// closes the http.Response Body. -func (client ConfigServersClient) UpdatePatchResponder(resp *http.Response) (result ConfigServerResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdatePut update the config server. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// configServerResource - parameters for the update operation -func (client ConfigServersClient) UpdatePut(ctx context.Context, resourceGroupName string, serviceName string, configServerResource ConfigServerResource) (result ConfigServersUpdatePutFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigServersClient.UpdatePut") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: configServerResource, - Constraints: []validation.Constraint{{Target: "configServerResource.Properties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "configServerResource.Properties.ConfigServer", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "configServerResource.Properties.ConfigServer.GitProperty", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "configServerResource.Properties.ConfigServer.GitProperty.URI", Name: validation.Null, Rule: true, Chain: nil}}}, - }}, - }}}}}); err != nil { - return result, validation.NewError("appplatform.ConfigServersClient", "UpdatePut", err.Error()) - } - - req, err := client.UpdatePutPreparer(ctx, resourceGroupName, serviceName, configServerResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "UpdatePut", nil, "Failure preparing request") - return - } - - result, err = client.UpdatePutSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "UpdatePut", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePutPreparer prepares the UpdatePut request. -func (client ConfigServersClient) UpdatePutPreparer(ctx context.Context, resourceGroupName string, serviceName string, configServerResource ConfigServerResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/configServers/default", pathParameters), - autorest.WithJSON(configServerResource), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdatePutSender sends the UpdatePut request. The method will close the -// http.Response Body if it receives an error. -func (client ConfigServersClient) UpdatePutSender(req *http.Request) (future ConfigServersUpdatePutFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdatePutResponder handles the response to the UpdatePut request. The method always -// closes the http.Response Body. -func (client ConfigServersClient) UpdatePutResponder(resp *http.Response) (result ConfigServerResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Validate check if the config server settings are valid. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// configServerSettings - config server settings to be validated -func (client ConfigServersClient) Validate(ctx context.Context, resourceGroupName string, serviceName string, configServerSettings ConfigServerSettings) (result ConfigServersValidateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigServersClient.Validate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: configServerSettings, - Constraints: []validation.Constraint{{Target: "configServerSettings.GitProperty", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "configServerSettings.GitProperty.URI", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewError("appplatform.ConfigServersClient", "Validate", err.Error()) - } - - req, err := client.ValidatePreparer(ctx, resourceGroupName, serviceName, configServerSettings) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Validate", nil, "Failure preparing request") - return - } - - result, err = client.ValidateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersClient", "Validate", result.Response(), "Failure sending request") - return - } - - return -} - -// ValidatePreparer prepares the Validate request. -func (client ConfigServersClient) ValidatePreparer(ctx context.Context, resourceGroupName string, serviceName string, configServerSettings ConfigServerSettings) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/configServers/validate", pathParameters), - autorest.WithJSON(configServerSettings), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ValidateSender sends the Validate request. The method will close the -// http.Response Body if it receives an error. -func (client ConfigServersClient) ValidateSender(req *http.Request) (future ConfigServersValidateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ValidateResponder handles the response to the Validate request. The method always -// closes the http.Response Body. -func (client ConfigServersClient) ValidateResponder(resp *http.Response) (result ConfigServerSettingsValidateResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/configurationservices.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/configurationservices.go deleted file mode 100644 index 65ac8ae6b718..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/configurationservices.go +++ /dev/null @@ -1,482 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// ConfigurationServicesClient is the REST API for Azure Spring Cloud -type ConfigurationServicesClient struct { - BaseClient -} - -// NewConfigurationServicesClient creates an instance of the ConfigurationServicesClient client. -func NewConfigurationServicesClient(subscriptionID string) ConfigurationServicesClient { - return NewConfigurationServicesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewConfigurationServicesClientWithBaseURI creates an instance of the ConfigurationServicesClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewConfigurationServicesClientWithBaseURI(baseURI string, subscriptionID string) ConfigurationServicesClient { - return ConfigurationServicesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create the default Application Configuration Service or update the existing Application Configuration -// Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// configurationServiceName - the name of Application Configuration Service. -// configurationServiceResource - parameters for the update operation -func (client ConfigurationServicesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string, configurationServiceResource ConfigurationServiceResource) (result ConfigurationServicesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, configurationServiceName, configurationServiceResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ConfigurationServicesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string, configurationServiceResource ConfigurationServiceResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationServiceName": autorest.Encode("path", configurationServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}", pathParameters), - autorest.WithJSON(configurationServiceResource), - 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 ConfigurationServicesClient) CreateOrUpdateSender(req *http.Request) (future ConfigurationServicesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ConfigurationServicesClient) CreateOrUpdateResponder(resp *http.Response) (result ConfigurationServiceResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete disable the default Application Configuration Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// configurationServiceName - the name of Application Configuration Service. -func (client ConfigurationServicesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string) (result ConfigurationServicesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, configurationServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ConfigurationServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationServiceName": autorest.Encode("path", configurationServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}", 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 ConfigurationServicesClient) DeleteSender(req *http.Request) (future ConfigurationServicesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ConfigurationServicesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the Application Configuration Service and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// configurationServiceName - the name of Application Configuration Service. -func (client ConfigurationServicesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string) (result ConfigurationServiceResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, configurationServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ConfigurationServicesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationServiceName": autorest.Encode("path", configurationServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}", 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 ConfigurationServicesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ConfigurationServicesClient) GetResponder(resp *http.Response) (result ConfigurationServiceResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handles requests to list all resources in a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ConfigurationServicesClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result ConfigurationServiceResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.List") - defer func() { - sc := -1 - if result.csrc.Response.Response != nil { - sc = result.csrc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.csrc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "List", resp, "Failure sending request") - return - } - - result.csrc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "List", resp, "Failure responding to request") - return - } - if result.csrc.hasNextLink() && result.csrc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ConfigurationServicesClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/configurationServices", 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 ConfigurationServicesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ConfigurationServicesClient) ListResponder(resp *http.Response) (result ConfigurationServiceResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 ConfigurationServicesClient) listNextResults(ctx context.Context, lastResults ConfigurationServiceResourceCollection) (result ConfigurationServiceResourceCollection, err error) { - req, err := lastResults.configurationServiceResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "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, "appplatform.ConfigurationServicesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ConfigurationServicesClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result ConfigurationServiceResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName) - return -} - -// Validate check if the Application Configuration Service settings are valid. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// configurationServiceName - the name of Application Configuration Service. -// settings - application Configuration Service settings to be validated -func (client ConfigurationServicesClient) Validate(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string, settings ConfigurationServiceSettings) (result ConfigurationServicesValidateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServicesClient.Validate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ValidatePreparer(ctx, resourceGroupName, serviceName, configurationServiceName, settings) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Validate", nil, "Failure preparing request") - return - } - - result, err = client.ValidateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesClient", "Validate", result.Response(), "Failure sending request") - return - } - - return -} - -// ValidatePreparer prepares the Validate request. -func (client ConfigurationServicesClient) ValidatePreparer(ctx context.Context, resourceGroupName string, serviceName string, configurationServiceName string, settings ConfigurationServiceSettings) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationServiceName": autorest.Encode("path", configurationServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/configurationServices/{configurationServiceName}/validate", pathParameters), - autorest.WithJSON(settings), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ValidateSender sends the Validate request. The method will close the -// http.Response Body if it receives an error. -func (client ConfigurationServicesClient) ValidateSender(req *http.Request) (future ConfigurationServicesValidateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ValidateResponder handles the response to the Validate request. The method always -// closes the http.Response Body. -func (client ConfigurationServicesClient) ValidateResponder(resp *http.Response) (result ConfigurationServiceSettingsValidateResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/customdomains.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/customdomains.go deleted file mode 100644 index 7b3ef4244b67..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/customdomains.go +++ /dev/null @@ -1,490 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// CustomDomainsClient is the REST API for Azure Spring Cloud -type CustomDomainsClient struct { - BaseClient -} - -// NewCustomDomainsClient creates an instance of the CustomDomainsClient client. -func NewCustomDomainsClient(subscriptionID string) CustomDomainsClient { - return NewCustomDomainsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewCustomDomainsClientWithBaseURI creates an instance of the CustomDomainsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewCustomDomainsClientWithBaseURI(baseURI string, subscriptionID string) CustomDomainsClient { - return CustomDomainsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update custom domain of one lifecycle application. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// domainName - the name of the custom domain resource. -// domainResource - parameters for the create or update operation -func (client CustomDomainsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string, domainResource CustomDomainResource) (result CustomDomainsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, appName, domainName, domainResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client CustomDomainsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string, domainResource CustomDomainResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "domainName": autorest.Encode("path", domainName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/domains/{domainName}", pathParameters), - autorest.WithJSON(domainResource), - 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 CustomDomainsClient) CreateOrUpdateSender(req *http.Request) (future CustomDomainsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client CustomDomainsClient) CreateOrUpdateResponder(resp *http.Response) (result CustomDomainResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the custom domain of one lifecycle application. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// domainName - the name of the custom domain resource. -func (client CustomDomainsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string) (result CustomDomainsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, appName, domainName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client CustomDomainsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "domainName": autorest.Encode("path", domainName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/domains/{domainName}", 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 CustomDomainsClient) DeleteSender(req *http.Request) (future CustomDomainsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client CustomDomainsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the custom domain of one lifecycle application. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// domainName - the name of the custom domain resource. -func (client CustomDomainsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string) (result CustomDomainResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, appName, domainName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client CustomDomainsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "domainName": autorest.Encode("path", domainName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/domains/{domainName}", 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 CustomDomainsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client CustomDomainsClient) GetResponder(resp *http.Response) (result CustomDomainResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list the custom domains of one lifecycle application. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -func (client CustomDomainsClient) List(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result CustomDomainResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.List") - defer func() { - sc := -1 - if result.cdrc.Response.Response != nil { - sc = result.cdrc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, appName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.cdrc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "List", resp, "Failure sending request") - return - } - - result.cdrc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "List", resp, "Failure responding to request") - return - } - if result.cdrc.hasNextLink() && result.cdrc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client CustomDomainsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/domains", 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 CustomDomainsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client CustomDomainsClient) ListResponder(resp *http.Response) (result CustomDomainResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 CustomDomainsClient) listNextResults(ctx context.Context, lastResults CustomDomainResourceCollection) (result CustomDomainResourceCollection, err error) { - req, err := lastResults.customDomainResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "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, "appplatform.CustomDomainsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client CustomDomainsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, appName string) (result CustomDomainResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName, appName) - return -} - -// Update update custom domain of one lifecycle application. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// domainName - the name of the custom domain resource. -// domainResource - parameters for the create or update operation -func (client CustomDomainsClient) Update(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string, domainResource CustomDomainResource) (result CustomDomainsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, appName, domainName, domainResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client CustomDomainsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string, domainResource CustomDomainResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "domainName": autorest.Encode("path", domainName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/domains/{domainName}", pathParameters), - autorest.WithJSON(domainResource), - 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 CustomDomainsClient) UpdateSender(req *http.Request) (future CustomDomainsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client CustomDomainsClient) UpdateResponder(resp *http.Response) (result CustomDomainResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/deployments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/deployments.go deleted file mode 100644 index 188fc5203d73..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/deployments.go +++ /dev/null @@ -1,1205 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// DeploymentsClient is the REST API for Azure Spring Cloud -type DeploymentsClient struct { - BaseClient -} - -// NewDeploymentsClient creates an instance of the DeploymentsClient client. -func NewDeploymentsClient(subscriptionID string) DeploymentsClient { - return NewDeploymentsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDeploymentsClientWithBaseURI creates an instance of the DeploymentsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewDeploymentsClientWithBaseURI(baseURI string, subscriptionID string) DeploymentsClient { - return DeploymentsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create a new Deployment or update an exiting Deployment. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -// deploymentResource - parameters for the create or update operation -func (client DeploymentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (result DeploymentsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, deploymentResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DeploymentsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}", pathParameters), - autorest.WithJSON(deploymentResource), - 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 DeploymentsClient) CreateOrUpdateSender(req *http.Request) (future DeploymentsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) CreateOrUpdateResponder(resp *http.Response) (result DeploymentResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete operation to delete a Deployment. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -func (client DeploymentsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DeploymentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}", 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 DeploymentsClient) DeleteSender(req *http.Request) (future DeploymentsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// GenerateHeapDump generate Heap Dump -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -// diagnosticParameters - parameters for the diagnostic operation -func (client DeploymentsClient) GenerateHeapDump(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (result DeploymentsGenerateHeapDumpFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.GenerateHeapDump") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GenerateHeapDumpPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, diagnosticParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GenerateHeapDump", nil, "Failure preparing request") - return - } - - result, err = client.GenerateHeapDumpSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GenerateHeapDump", result.Response(), "Failure sending request") - return - } - - return -} - -// GenerateHeapDumpPreparer prepares the GenerateHeapDump request. -func (client DeploymentsClient) GenerateHeapDumpPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/generateHeapDump", pathParameters), - autorest.WithJSON(diagnosticParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GenerateHeapDumpSender sends the GenerateHeapDump request. The method will close the -// http.Response Body if it receives an error. -func (client DeploymentsClient) GenerateHeapDumpSender(req *http.Request) (future DeploymentsGenerateHeapDumpFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GenerateHeapDumpResponder handles the response to the GenerateHeapDump request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) GenerateHeapDumpResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// GenerateThreadDump generate Thread Dump -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -// diagnosticParameters - parameters for the diagnostic operation -func (client DeploymentsClient) GenerateThreadDump(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (result DeploymentsGenerateThreadDumpFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.GenerateThreadDump") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GenerateThreadDumpPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, diagnosticParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GenerateThreadDump", nil, "Failure preparing request") - return - } - - result, err = client.GenerateThreadDumpSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GenerateThreadDump", result.Response(), "Failure sending request") - return - } - - return -} - -// GenerateThreadDumpPreparer prepares the GenerateThreadDump request. -func (client DeploymentsClient) GenerateThreadDumpPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/generateThreadDump", pathParameters), - autorest.WithJSON(diagnosticParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GenerateThreadDumpSender sends the GenerateThreadDump request. The method will close the -// http.Response Body if it receives an error. -func (client DeploymentsClient) GenerateThreadDumpSender(req *http.Request) (future DeploymentsGenerateThreadDumpFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GenerateThreadDumpResponder handles the response to the GenerateThreadDump request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) GenerateThreadDumpResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get a Deployment and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -func (client DeploymentsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DeploymentsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}", 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 DeploymentsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) GetResponder(resp *http.Response) (result DeploymentResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetLogFileURL get deployment log file URL -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -func (client DeploymentsClient) GetLogFileURL(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result LogFileURLResponse, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.GetLogFileURL") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetLogFileURLPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GetLogFileURL", nil, "Failure preparing request") - return - } - - resp, err := client.GetLogFileURLSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GetLogFileURL", resp, "Failure sending request") - return - } - - result, err = client.GetLogFileURLResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "GetLogFileURL", resp, "Failure responding to request") - return - } - - return -} - -// GetLogFileURLPreparer prepares the GetLogFileURL request. -func (client DeploymentsClient) GetLogFileURLPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/getLogFileUrl", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetLogFileURLSender sends the GetLogFileURL request. The method will close the -// http.Response Body if it receives an error. -func (client DeploymentsClient) GetLogFileURLSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetLogFileURLResponder handles the response to the GetLogFileURL request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) GetLogFileURLResponder(resp *http.Response) (result LogFileURLResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handles requests to list all resources in an App. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// version - version of the deployments to be listed -func (client DeploymentsClient) List(ctx context.Context, resourceGroupName string, serviceName string, appName string, version []string) (result DeploymentResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.List") - defer func() { - sc := -1 - if result.drc.Response.Response != nil { - sc = result.drc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, appName, version) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.drc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "List", resp, "Failure sending request") - return - } - - result.drc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "List", resp, "Failure responding to request") - return - } - if result.drc.hasNextLink() && result.drc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client DeploymentsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, version []string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if version != nil && len(version) > 0 { - queryParameters["version"] = version - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments", 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 DeploymentsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) ListResponder(resp *http.Response) (result DeploymentResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 DeploymentsClient) listNextResults(ctx context.Context, lastResults DeploymentResourceCollection) (result DeploymentResourceCollection, err error) { - req, err := lastResults.deploymentResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "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, "appplatform.DeploymentsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client DeploymentsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, appName string, version []string) (result DeploymentResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName, appName, version) - return -} - -// ListForCluster list deployments for a certain service -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// version - version of the deployments to be listed -func (client DeploymentsClient) ListForCluster(ctx context.Context, resourceGroupName string, serviceName string, version []string) (result DeploymentResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.ListForCluster") - defer func() { - sc := -1 - if result.drc.Response.Response != nil { - sc = result.drc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listForClusterNextResults - req, err := client.ListForClusterPreparer(ctx, resourceGroupName, serviceName, version) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "ListForCluster", nil, "Failure preparing request") - return - } - - resp, err := client.ListForClusterSender(req) - if err != nil { - result.drc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "ListForCluster", resp, "Failure sending request") - return - } - - result.drc, err = client.ListForClusterResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "ListForCluster", resp, "Failure responding to request") - return - } - if result.drc.hasNextLink() && result.drc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListForClusterPreparer prepares the ListForCluster request. -func (client DeploymentsClient) ListForClusterPreparer(ctx context.Context, resourceGroupName string, serviceName string, version []string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if version != nil && len(version) > 0 { - queryParameters["version"] = version - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/deployments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForClusterSender sends the ListForCluster request. The method will close the -// http.Response Body if it receives an error. -func (client DeploymentsClient) ListForClusterSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListForClusterResponder handles the response to the ListForCluster request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) ListForClusterResponder(resp *http.Response) (result DeploymentResourceCollection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForClusterNextResults retrieves the next set of results, if any. -func (client DeploymentsClient) listForClusterNextResults(ctx context.Context, lastResults DeploymentResourceCollection) (result DeploymentResourceCollection, err error) { - req, err := lastResults.deploymentResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "listForClusterNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForClusterSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "listForClusterNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForClusterResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "listForClusterNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForClusterComplete enumerates all values, automatically crossing page boundaries as required. -func (client DeploymentsClient) ListForClusterComplete(ctx context.Context, resourceGroupName string, serviceName string, version []string) (result DeploymentResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.ListForCluster") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListForCluster(ctx, resourceGroupName, serviceName, version) - return -} - -// Restart restart the deployment. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -func (client DeploymentsClient) Restart(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentsRestartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Restart") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RestartPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Restart", nil, "Failure preparing request") - return - } - - result, err = client.RestartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Restart", result.Response(), "Failure sending request") - return - } - - return -} - -// RestartPreparer prepares the Restart request. -func (client DeploymentsClient) RestartPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/restart", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RestartSender sends the Restart request. The method will close the -// http.Response Body if it receives an error. -func (client DeploymentsClient) RestartSender(req *http.Request) (future DeploymentsRestartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// RestartResponder handles the response to the Restart request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Start start the deployment. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -func (client DeploymentsClient) Start(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentsStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client DeploymentsClient) StartPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client DeploymentsClient) StartSender(req *http.Request) (future DeploymentsStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// StartJFR start JFR -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -// diagnosticParameters - parameters for the diagnostic operation -func (client DeploymentsClient) StartJFR(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (result DeploymentsStartJFRFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.StartJFR") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartJFRPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, diagnosticParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "StartJFR", nil, "Failure preparing request") - return - } - - result, err = client.StartJFRSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "StartJFR", result.Response(), "Failure sending request") - return - } - - return -} - -// StartJFRPreparer prepares the StartJFR request. -func (client DeploymentsClient) StartJFRPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, diagnosticParameters DiagnosticParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/startJFR", pathParameters), - autorest.WithJSON(diagnosticParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartJFRSender sends the StartJFR request. The method will close the -// http.Response Body if it receives an error. -func (client DeploymentsClient) StartJFRSender(req *http.Request) (future DeploymentsStartJFRFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartJFRResponder handles the response to the StartJFR request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) StartJFRResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Stop stop the deployment. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -func (client DeploymentsClient) Stop(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentsStopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Stop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Stop", nil, "Failure preparing request") - return - } - - result, err = client.StopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Stop", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client DeploymentsClient) StopPreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}/stop", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopSender sends the Stop request. The method will close the -// http.Response Body if it receives an error. -func (client DeploymentsClient) StopSender(req *http.Request) (future DeploymentsStopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopResponder handles the response to the Stop request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update operation to update an exiting Deployment. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// appName - the name of the App resource. -// deploymentName - the name of the Deployment resource. -// deploymentResource - parameters for the update operation -func (client DeploymentsClient) Update(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (result DeploymentsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, appName, deploymentName, deploymentResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client DeploymentsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string, deploymentResource DeploymentResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "appName": autorest.Encode("path", appName), - "deploymentName": autorest.Encode("path", deploymentName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/apps/{appName}/deployments/{deploymentName}", pathParameters), - autorest.WithJSON(deploymentResource), - 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 DeploymentsClient) UpdateSender(req *http.Request) (future DeploymentsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client DeploymentsClient) UpdateResponder(resp *http.Response) (result DeploymentResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/enums.go deleted file mode 100644 index 2b7bdae0196d..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/enums.go +++ /dev/null @@ -1,634 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// ActionType enumerates the values for action type. -type ActionType string - -const ( - // ActionTypeInternal ... - ActionTypeInternal ActionType = "Internal" -) - -// PossibleActionTypeValues returns an array of possible values for the ActionType const type. -func PossibleActionTypeValues() []ActionType { - return []ActionType{ActionTypeInternal} -} - -// APIPortalProvisioningState enumerates the values for api portal provisioning state. -type APIPortalProvisioningState string - -const ( - // APIPortalProvisioningStateCreating ... - APIPortalProvisioningStateCreating APIPortalProvisioningState = "Creating" - // APIPortalProvisioningStateDeleting ... - APIPortalProvisioningStateDeleting APIPortalProvisioningState = "Deleting" - // APIPortalProvisioningStateFailed ... - APIPortalProvisioningStateFailed APIPortalProvisioningState = "Failed" - // APIPortalProvisioningStateSucceeded ... - APIPortalProvisioningStateSucceeded APIPortalProvisioningState = "Succeeded" - // APIPortalProvisioningStateUpdating ... - APIPortalProvisioningStateUpdating APIPortalProvisioningState = "Updating" -) - -// PossibleAPIPortalProvisioningStateValues returns an array of possible values for the APIPortalProvisioningState const type. -func PossibleAPIPortalProvisioningStateValues() []APIPortalProvisioningState { - return []APIPortalProvisioningState{APIPortalProvisioningStateCreating, APIPortalProvisioningStateDeleting, APIPortalProvisioningStateFailed, APIPortalProvisioningStateSucceeded, APIPortalProvisioningStateUpdating} -} - -// AppResourceProvisioningState enumerates the values for app resource provisioning state. -type AppResourceProvisioningState string - -const ( - // AppResourceProvisioningStateCreating ... - AppResourceProvisioningStateCreating AppResourceProvisioningState = "Creating" - // AppResourceProvisioningStateDeleting ... - AppResourceProvisioningStateDeleting AppResourceProvisioningState = "Deleting" - // AppResourceProvisioningStateFailed ... - AppResourceProvisioningStateFailed AppResourceProvisioningState = "Failed" - // AppResourceProvisioningStateSucceeded ... - AppResourceProvisioningStateSucceeded AppResourceProvisioningState = "Succeeded" - // AppResourceProvisioningStateUpdating ... - AppResourceProvisioningStateUpdating AppResourceProvisioningState = "Updating" -) - -// PossibleAppResourceProvisioningStateValues returns an array of possible values for the AppResourceProvisioningState const type. -func PossibleAppResourceProvisioningStateValues() []AppResourceProvisioningState { - return []AppResourceProvisioningState{AppResourceProvisioningStateCreating, AppResourceProvisioningStateDeleting, AppResourceProvisioningStateFailed, AppResourceProvisioningStateSucceeded, AppResourceProvisioningStateUpdating} -} - -// BindingType enumerates the values for binding type. -type BindingType string - -const ( - // BindingTypeApacheSkyWalking ... - BindingTypeApacheSkyWalking BindingType = "ApacheSkyWalking" - // BindingTypeAppDynamics ... - BindingTypeAppDynamics BindingType = "AppDynamics" - // BindingTypeApplicationInsights ... - BindingTypeApplicationInsights BindingType = "ApplicationInsights" - // BindingTypeDynatrace ... - BindingTypeDynatrace BindingType = "Dynatrace" - // BindingTypeElasticAPM ... - BindingTypeElasticAPM BindingType = "ElasticAPM" - // BindingTypeNewRelic ... - BindingTypeNewRelic BindingType = "NewRelic" -) - -// PossibleBindingTypeValues returns an array of possible values for the BindingType const type. -func PossibleBindingTypeValues() []BindingType { - return []BindingType{BindingTypeApacheSkyWalking, BindingTypeAppDynamics, BindingTypeApplicationInsights, BindingTypeDynatrace, BindingTypeElasticAPM, BindingTypeNewRelic} -} - -// BuilderProvisioningState enumerates the values for builder provisioning state. -type BuilderProvisioningState string - -const ( - // BuilderProvisioningStateCreating ... - BuilderProvisioningStateCreating BuilderProvisioningState = "Creating" - // BuilderProvisioningStateDeleting ... - BuilderProvisioningStateDeleting BuilderProvisioningState = "Deleting" - // BuilderProvisioningStateFailed ... - BuilderProvisioningStateFailed BuilderProvisioningState = "Failed" - // BuilderProvisioningStateSucceeded ... - BuilderProvisioningStateSucceeded BuilderProvisioningState = "Succeeded" - // BuilderProvisioningStateUpdating ... - BuilderProvisioningStateUpdating BuilderProvisioningState = "Updating" -) - -// PossibleBuilderProvisioningStateValues returns an array of possible values for the BuilderProvisioningState const type. -func PossibleBuilderProvisioningStateValues() []BuilderProvisioningState { - return []BuilderProvisioningState{BuilderProvisioningStateCreating, BuilderProvisioningStateDeleting, BuilderProvisioningStateFailed, BuilderProvisioningStateSucceeded, BuilderProvisioningStateUpdating} -} - -// BuildpackBindingProvisioningState enumerates the values for buildpack binding provisioning state. -type BuildpackBindingProvisioningState string - -const ( - // BuildpackBindingProvisioningStateCreating ... - BuildpackBindingProvisioningStateCreating BuildpackBindingProvisioningState = "Creating" - // BuildpackBindingProvisioningStateDeleting ... - BuildpackBindingProvisioningStateDeleting BuildpackBindingProvisioningState = "Deleting" - // BuildpackBindingProvisioningStateFailed ... - BuildpackBindingProvisioningStateFailed BuildpackBindingProvisioningState = "Failed" - // BuildpackBindingProvisioningStateSucceeded ... - BuildpackBindingProvisioningStateSucceeded BuildpackBindingProvisioningState = "Succeeded" - // BuildpackBindingProvisioningStateUpdating ... - BuildpackBindingProvisioningStateUpdating BuildpackBindingProvisioningState = "Updating" -) - -// PossibleBuildpackBindingProvisioningStateValues returns an array of possible values for the BuildpackBindingProvisioningState const type. -func PossibleBuildpackBindingProvisioningStateValues() []BuildpackBindingProvisioningState { - return []BuildpackBindingProvisioningState{BuildpackBindingProvisioningStateCreating, BuildpackBindingProvisioningStateDeleting, BuildpackBindingProvisioningStateFailed, BuildpackBindingProvisioningStateSucceeded, BuildpackBindingProvisioningStateUpdating} -} - -// BuildProvisioningState enumerates the values for build provisioning state. -type BuildProvisioningState string - -const ( - // BuildProvisioningStateCreating ... - BuildProvisioningStateCreating BuildProvisioningState = "Creating" - // BuildProvisioningStateDeleting ... - BuildProvisioningStateDeleting BuildProvisioningState = "Deleting" - // BuildProvisioningStateFailed ... - BuildProvisioningStateFailed BuildProvisioningState = "Failed" - // BuildProvisioningStateSucceeded ... - BuildProvisioningStateSucceeded BuildProvisioningState = "Succeeded" - // BuildProvisioningStateUpdating ... - BuildProvisioningStateUpdating BuildProvisioningState = "Updating" -) - -// PossibleBuildProvisioningStateValues returns an array of possible values for the BuildProvisioningState const type. -func PossibleBuildProvisioningStateValues() []BuildProvisioningState { - return []BuildProvisioningState{BuildProvisioningStateCreating, BuildProvisioningStateDeleting, BuildProvisioningStateFailed, BuildProvisioningStateSucceeded, BuildProvisioningStateUpdating} -} - -// BuildResultProvisioningState enumerates the values for build result provisioning state. -type BuildResultProvisioningState string - -const ( - // BuildResultProvisioningStateBuilding ... - BuildResultProvisioningStateBuilding BuildResultProvisioningState = "Building" - // BuildResultProvisioningStateDeleting ... - BuildResultProvisioningStateDeleting BuildResultProvisioningState = "Deleting" - // BuildResultProvisioningStateFailed ... - BuildResultProvisioningStateFailed BuildResultProvisioningState = "Failed" - // BuildResultProvisioningStateQueuing ... - BuildResultProvisioningStateQueuing BuildResultProvisioningState = "Queuing" - // BuildResultProvisioningStateSucceeded ... - BuildResultProvisioningStateSucceeded BuildResultProvisioningState = "Succeeded" -) - -// PossibleBuildResultProvisioningStateValues returns an array of possible values for the BuildResultProvisioningState const type. -func PossibleBuildResultProvisioningStateValues() []BuildResultProvisioningState { - return []BuildResultProvisioningState{BuildResultProvisioningStateBuilding, BuildResultProvisioningStateDeleting, BuildResultProvisioningStateFailed, BuildResultProvisioningStateQueuing, BuildResultProvisioningStateSucceeded} -} - -// BuildServiceProvisioningState enumerates the values for build service provisioning state. -type BuildServiceProvisioningState string - -const ( - // BuildServiceProvisioningStateCreating ... - BuildServiceProvisioningStateCreating BuildServiceProvisioningState = "Creating" - // BuildServiceProvisioningStateDeleting ... - BuildServiceProvisioningStateDeleting BuildServiceProvisioningState = "Deleting" - // BuildServiceProvisioningStateFailed ... - BuildServiceProvisioningStateFailed BuildServiceProvisioningState = "Failed" - // BuildServiceProvisioningStateSucceeded ... - BuildServiceProvisioningStateSucceeded BuildServiceProvisioningState = "Succeeded" - // BuildServiceProvisioningStateUpdating ... - BuildServiceProvisioningStateUpdating BuildServiceProvisioningState = "Updating" -) - -// PossibleBuildServiceProvisioningStateValues returns an array of possible values for the BuildServiceProvisioningState const type. -func PossibleBuildServiceProvisioningStateValues() []BuildServiceProvisioningState { - return []BuildServiceProvisioningState{BuildServiceProvisioningStateCreating, BuildServiceProvisioningStateDeleting, BuildServiceProvisioningStateFailed, BuildServiceProvisioningStateSucceeded, BuildServiceProvisioningStateUpdating} -} - -// ConfigServerState enumerates the values for config server state. -type ConfigServerState string - -const ( - // ConfigServerStateDeleted ... - ConfigServerStateDeleted ConfigServerState = "Deleted" - // ConfigServerStateFailed ... - ConfigServerStateFailed ConfigServerState = "Failed" - // ConfigServerStateNotAvailable ... - ConfigServerStateNotAvailable ConfigServerState = "NotAvailable" - // ConfigServerStateSucceeded ... - ConfigServerStateSucceeded ConfigServerState = "Succeeded" - // ConfigServerStateUpdating ... - ConfigServerStateUpdating ConfigServerState = "Updating" -) - -// PossibleConfigServerStateValues returns an array of possible values for the ConfigServerState const type. -func PossibleConfigServerStateValues() []ConfigServerState { - return []ConfigServerState{ConfigServerStateDeleted, ConfigServerStateFailed, ConfigServerStateNotAvailable, ConfigServerStateSucceeded, ConfigServerStateUpdating} -} - -// ConfigurationServiceProvisioningState enumerates the values for configuration service provisioning state. -type ConfigurationServiceProvisioningState string - -const ( - // ConfigurationServiceProvisioningStateCreating ... - ConfigurationServiceProvisioningStateCreating ConfigurationServiceProvisioningState = "Creating" - // ConfigurationServiceProvisioningStateDeleting ... - ConfigurationServiceProvisioningStateDeleting ConfigurationServiceProvisioningState = "Deleting" - // ConfigurationServiceProvisioningStateFailed ... - ConfigurationServiceProvisioningStateFailed ConfigurationServiceProvisioningState = "Failed" - // ConfigurationServiceProvisioningStateSucceeded ... - ConfigurationServiceProvisioningStateSucceeded ConfigurationServiceProvisioningState = "Succeeded" - // ConfigurationServiceProvisioningStateUpdating ... - ConfigurationServiceProvisioningStateUpdating ConfigurationServiceProvisioningState = "Updating" -) - -// PossibleConfigurationServiceProvisioningStateValues returns an array of possible values for the ConfigurationServiceProvisioningState const type. -func PossibleConfigurationServiceProvisioningStateValues() []ConfigurationServiceProvisioningState { - return []ConfigurationServiceProvisioningState{ConfigurationServiceProvisioningStateCreating, ConfigurationServiceProvisioningStateDeleting, ConfigurationServiceProvisioningStateFailed, ConfigurationServiceProvisioningStateSucceeded, ConfigurationServiceProvisioningStateUpdating} -} - -// CreatedByType enumerates the values for created by type. -type CreatedByType string - -const ( - // CreatedByTypeApplication ... - CreatedByTypeApplication CreatedByType = "Application" - // CreatedByTypeKey ... - CreatedByTypeKey CreatedByType = "Key" - // CreatedByTypeManagedIdentity ... - CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" - // CreatedByTypeUser ... - CreatedByTypeUser CreatedByType = "User" -) - -// PossibleCreatedByTypeValues returns an array of possible values for the CreatedByType const type. -func PossibleCreatedByTypeValues() []CreatedByType { - return []CreatedByType{CreatedByTypeApplication, CreatedByTypeKey, CreatedByTypeManagedIdentity, CreatedByTypeUser} -} - -// DeploymentResourceProvisioningState enumerates the values for deployment resource provisioning state. -type DeploymentResourceProvisioningState string - -const ( - // DeploymentResourceProvisioningStateCreating ... - DeploymentResourceProvisioningStateCreating DeploymentResourceProvisioningState = "Creating" - // DeploymentResourceProvisioningStateFailed ... - DeploymentResourceProvisioningStateFailed DeploymentResourceProvisioningState = "Failed" - // DeploymentResourceProvisioningStateSucceeded ... - DeploymentResourceProvisioningStateSucceeded DeploymentResourceProvisioningState = "Succeeded" - // DeploymentResourceProvisioningStateUpdating ... - DeploymentResourceProvisioningStateUpdating DeploymentResourceProvisioningState = "Updating" -) - -// PossibleDeploymentResourceProvisioningStateValues returns an array of possible values for the DeploymentResourceProvisioningState const type. -func PossibleDeploymentResourceProvisioningStateValues() []DeploymentResourceProvisioningState { - return []DeploymentResourceProvisioningState{DeploymentResourceProvisioningStateCreating, DeploymentResourceProvisioningStateFailed, DeploymentResourceProvisioningStateSucceeded, DeploymentResourceProvisioningStateUpdating} -} - -// DeploymentResourceStatus enumerates the values for deployment resource status. -type DeploymentResourceStatus string - -const ( - // DeploymentResourceStatusRunning ... - DeploymentResourceStatusRunning DeploymentResourceStatus = "Running" - // DeploymentResourceStatusStopped ... - DeploymentResourceStatusStopped DeploymentResourceStatus = "Stopped" -) - -// PossibleDeploymentResourceStatusValues returns an array of possible values for the DeploymentResourceStatus const type. -func PossibleDeploymentResourceStatusValues() []DeploymentResourceStatus { - return []DeploymentResourceStatus{DeploymentResourceStatusRunning, DeploymentResourceStatusStopped} -} - -// GatewayProvisioningState enumerates the values for gateway provisioning state. -type GatewayProvisioningState string - -const ( - // GatewayProvisioningStateCreating ... - GatewayProvisioningStateCreating GatewayProvisioningState = "Creating" - // GatewayProvisioningStateDeleting ... - GatewayProvisioningStateDeleting GatewayProvisioningState = "Deleting" - // GatewayProvisioningStateFailed ... - GatewayProvisioningStateFailed GatewayProvisioningState = "Failed" - // GatewayProvisioningStateSucceeded ... - GatewayProvisioningStateSucceeded GatewayProvisioningState = "Succeeded" - // GatewayProvisioningStateUpdating ... - GatewayProvisioningStateUpdating GatewayProvisioningState = "Updating" -) - -// PossibleGatewayProvisioningStateValues returns an array of possible values for the GatewayProvisioningState const type. -func PossibleGatewayProvisioningStateValues() []GatewayProvisioningState { - return []GatewayProvisioningState{GatewayProvisioningStateCreating, GatewayProvisioningStateDeleting, GatewayProvisioningStateFailed, GatewayProvisioningStateSucceeded, GatewayProvisioningStateUpdating} -} - -// KPackBuildStageProvisioningState enumerates the values for k pack build stage provisioning state. -type KPackBuildStageProvisioningState string - -const ( - // KPackBuildStageProvisioningStateFailed ... - KPackBuildStageProvisioningStateFailed KPackBuildStageProvisioningState = "Failed" - // KPackBuildStageProvisioningStateNotStarted ... - KPackBuildStageProvisioningStateNotStarted KPackBuildStageProvisioningState = "NotStarted" - // KPackBuildStageProvisioningStateRunning ... - KPackBuildStageProvisioningStateRunning KPackBuildStageProvisioningState = "Running" - // KPackBuildStageProvisioningStateSucceeded ... - KPackBuildStageProvisioningStateSucceeded KPackBuildStageProvisioningState = "Succeeded" -) - -// PossibleKPackBuildStageProvisioningStateValues returns an array of possible values for the KPackBuildStageProvisioningState const type. -func PossibleKPackBuildStageProvisioningStateValues() []KPackBuildStageProvisioningState { - return []KPackBuildStageProvisioningState{KPackBuildStageProvisioningStateFailed, KPackBuildStageProvisioningStateNotStarted, KPackBuildStageProvisioningStateRunning, KPackBuildStageProvisioningStateSucceeded} -} - -// LastModifiedByType enumerates the values for last modified by type. -type LastModifiedByType string - -const ( - // LastModifiedByTypeApplication ... - LastModifiedByTypeApplication LastModifiedByType = "Application" - // LastModifiedByTypeKey ... - LastModifiedByTypeKey LastModifiedByType = "Key" - // LastModifiedByTypeManagedIdentity ... - LastModifiedByTypeManagedIdentity LastModifiedByType = "ManagedIdentity" - // LastModifiedByTypeUser ... - LastModifiedByTypeUser LastModifiedByType = "User" -) - -// PossibleLastModifiedByTypeValues returns an array of possible values for the LastModifiedByType const type. -func PossibleLastModifiedByTypeValues() []LastModifiedByType { - return []LastModifiedByType{LastModifiedByTypeApplication, LastModifiedByTypeKey, LastModifiedByTypeManagedIdentity, LastModifiedByTypeUser} -} - -// ManagedIdentityType enumerates the values for managed identity type. -type ManagedIdentityType string - -const ( - // ManagedIdentityTypeNone ... - ManagedIdentityTypeNone ManagedIdentityType = "None" - // ManagedIdentityTypeSystemAssigned ... - ManagedIdentityTypeSystemAssigned ManagedIdentityType = "SystemAssigned" - // ManagedIdentityTypeSystemAssignedUserAssigned ... - ManagedIdentityTypeSystemAssignedUserAssigned ManagedIdentityType = "SystemAssigned,UserAssigned" - // ManagedIdentityTypeUserAssigned ... - ManagedIdentityTypeUserAssigned ManagedIdentityType = "UserAssigned" -) - -// PossibleManagedIdentityTypeValues returns an array of possible values for the ManagedIdentityType const type. -func PossibleManagedIdentityTypeValues() []ManagedIdentityType { - return []ManagedIdentityType{ManagedIdentityTypeNone, ManagedIdentityTypeSystemAssigned, ManagedIdentityTypeSystemAssignedUserAssigned, ManagedIdentityTypeUserAssigned} -} - -// MonitoringSettingState enumerates the values for monitoring setting state. -type MonitoringSettingState string - -const ( - // MonitoringSettingStateFailed ... - MonitoringSettingStateFailed MonitoringSettingState = "Failed" - // MonitoringSettingStateNotAvailable ... - MonitoringSettingStateNotAvailable MonitoringSettingState = "NotAvailable" - // MonitoringSettingStateSucceeded ... - MonitoringSettingStateSucceeded MonitoringSettingState = "Succeeded" - // MonitoringSettingStateUpdating ... - MonitoringSettingStateUpdating MonitoringSettingState = "Updating" -) - -// PossibleMonitoringSettingStateValues returns an array of possible values for the MonitoringSettingState const type. -func PossibleMonitoringSettingStateValues() []MonitoringSettingState { - return []MonitoringSettingState{MonitoringSettingStateFailed, MonitoringSettingStateNotAvailable, MonitoringSettingStateSucceeded, MonitoringSettingStateUpdating} -} - -// PowerState enumerates the values for power state. -type PowerState string - -const ( - // PowerStateRunning ... - PowerStateRunning PowerState = "Running" - // PowerStateStopped ... - PowerStateStopped PowerState = "Stopped" -) - -// PossiblePowerStateValues returns an array of possible values for the PowerState const type. -func PossiblePowerStateValues() []PowerState { - return []PowerState{PowerStateRunning, PowerStateStopped} -} - -// ProvisioningState enumerates the values for provisioning state. -type ProvisioningState string - -const ( - // ProvisioningStateCreating ... - ProvisioningStateCreating ProvisioningState = "Creating" - // ProvisioningStateDeleted ... - ProvisioningStateDeleted ProvisioningState = "Deleted" - // ProvisioningStateDeleting ... - ProvisioningStateDeleting ProvisioningState = "Deleting" - // ProvisioningStateFailed ... - ProvisioningStateFailed ProvisioningState = "Failed" - // ProvisioningStateMoved ... - ProvisioningStateMoved ProvisioningState = "Moved" - // ProvisioningStateMoveFailed ... - ProvisioningStateMoveFailed ProvisioningState = "MoveFailed" - // ProvisioningStateMoving ... - ProvisioningStateMoving ProvisioningState = "Moving" - // ProvisioningStateStarting ... - ProvisioningStateStarting ProvisioningState = "Starting" - // ProvisioningStateStopping ... - ProvisioningStateStopping ProvisioningState = "Stopping" - // ProvisioningStateSucceeded ... - ProvisioningStateSucceeded ProvisioningState = "Succeeded" - // ProvisioningStateUpdating ... - ProvisioningStateUpdating ProvisioningState = "Updating" -) - -// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. -func PossibleProvisioningStateValues() []ProvisioningState { - return []ProvisioningState{ProvisioningStateCreating, ProvisioningStateDeleted, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateMoved, ProvisioningStateMoveFailed, ProvisioningStateMoving, ProvisioningStateStarting, ProvisioningStateStopping, ProvisioningStateSucceeded, ProvisioningStateUpdating} -} - -// ResourceSkuRestrictionsReasonCode enumerates the values for resource sku restrictions reason code. -type ResourceSkuRestrictionsReasonCode string - -const ( - // ResourceSkuRestrictionsReasonCodeNotAvailableForSubscription ... - ResourceSkuRestrictionsReasonCodeNotAvailableForSubscription ResourceSkuRestrictionsReasonCode = "NotAvailableForSubscription" - // ResourceSkuRestrictionsReasonCodeQuotaID ... - ResourceSkuRestrictionsReasonCodeQuotaID ResourceSkuRestrictionsReasonCode = "QuotaId" -) - -// PossibleResourceSkuRestrictionsReasonCodeValues returns an array of possible values for the ResourceSkuRestrictionsReasonCode const type. -func PossibleResourceSkuRestrictionsReasonCodeValues() []ResourceSkuRestrictionsReasonCode { - return []ResourceSkuRestrictionsReasonCode{ResourceSkuRestrictionsReasonCodeNotAvailableForSubscription, ResourceSkuRestrictionsReasonCodeQuotaID} -} - -// ResourceSkuRestrictionsType enumerates the values for resource sku restrictions type. -type ResourceSkuRestrictionsType string - -const ( - // ResourceSkuRestrictionsTypeLocation ... - ResourceSkuRestrictionsTypeLocation ResourceSkuRestrictionsType = "Location" - // ResourceSkuRestrictionsTypeZone ... - ResourceSkuRestrictionsTypeZone ResourceSkuRestrictionsType = "Zone" -) - -// PossibleResourceSkuRestrictionsTypeValues returns an array of possible values for the ResourceSkuRestrictionsType const type. -func PossibleResourceSkuRestrictionsTypeValues() []ResourceSkuRestrictionsType { - return []ResourceSkuRestrictionsType{ResourceSkuRestrictionsTypeLocation, ResourceSkuRestrictionsTypeZone} -} - -// ServiceRegistryProvisioningState enumerates the values for service registry provisioning state. -type ServiceRegistryProvisioningState string - -const ( - // ServiceRegistryProvisioningStateCreating ... - ServiceRegistryProvisioningStateCreating ServiceRegistryProvisioningState = "Creating" - // ServiceRegistryProvisioningStateDeleting ... - ServiceRegistryProvisioningStateDeleting ServiceRegistryProvisioningState = "Deleting" - // ServiceRegistryProvisioningStateFailed ... - ServiceRegistryProvisioningStateFailed ServiceRegistryProvisioningState = "Failed" - // ServiceRegistryProvisioningStateSucceeded ... - ServiceRegistryProvisioningStateSucceeded ServiceRegistryProvisioningState = "Succeeded" - // ServiceRegistryProvisioningStateUpdating ... - ServiceRegistryProvisioningStateUpdating ServiceRegistryProvisioningState = "Updating" -) - -// PossibleServiceRegistryProvisioningStateValues returns an array of possible values for the ServiceRegistryProvisioningState const type. -func PossibleServiceRegistryProvisioningStateValues() []ServiceRegistryProvisioningState { - return []ServiceRegistryProvisioningState{ServiceRegistryProvisioningStateCreating, ServiceRegistryProvisioningStateDeleting, ServiceRegistryProvisioningStateFailed, ServiceRegistryProvisioningStateSucceeded, ServiceRegistryProvisioningStateUpdating} -} - -// SkuScaleType enumerates the values for sku scale type. -type SkuScaleType string - -const ( - // SkuScaleTypeAutomatic ... - SkuScaleTypeAutomatic SkuScaleType = "Automatic" - // SkuScaleTypeManual ... - SkuScaleTypeManual SkuScaleType = "Manual" - // SkuScaleTypeNone ... - SkuScaleTypeNone SkuScaleType = "None" -) - -// PossibleSkuScaleTypeValues returns an array of possible values for the SkuScaleType const type. -func PossibleSkuScaleTypeValues() []SkuScaleType { - return []SkuScaleType{SkuScaleTypeAutomatic, SkuScaleTypeManual, SkuScaleTypeNone} -} - -// StorageType enumerates the values for storage type. -type StorageType string - -const ( - // StorageTypeStorageAccount ... - StorageTypeStorageAccount StorageType = "StorageAccount" - // StorageTypeStorageProperties ... - StorageTypeStorageProperties StorageType = "StorageProperties" -) - -// PossibleStorageTypeValues returns an array of possible values for the StorageType const type. -func PossibleStorageTypeValues() []StorageType { - return []StorageType{StorageTypeStorageAccount, StorageTypeStorageProperties} -} - -// SupportedRuntimePlatform enumerates the values for supported runtime platform. -type SupportedRuntimePlatform string - -const ( - // SupportedRuntimePlatformJava ... - SupportedRuntimePlatformJava SupportedRuntimePlatform = "Java" - // SupportedRuntimePlatformNETCore ... - SupportedRuntimePlatformNETCore SupportedRuntimePlatform = ".NET Core" -) - -// PossibleSupportedRuntimePlatformValues returns an array of possible values for the SupportedRuntimePlatform const type. -func PossibleSupportedRuntimePlatformValues() []SupportedRuntimePlatform { - return []SupportedRuntimePlatform{SupportedRuntimePlatformJava, SupportedRuntimePlatformNETCore} -} - -// SupportedRuntimeValue enumerates the values for supported runtime value. -type SupportedRuntimeValue string - -const ( - // SupportedRuntimeValueJava11 ... - SupportedRuntimeValueJava11 SupportedRuntimeValue = "Java_11" - // SupportedRuntimeValueJava17 ... - SupportedRuntimeValueJava17 SupportedRuntimeValue = "Java_17" - // SupportedRuntimeValueJava8 ... - SupportedRuntimeValueJava8 SupportedRuntimeValue = "Java_8" - // SupportedRuntimeValueNetCore31 ... - SupportedRuntimeValueNetCore31 SupportedRuntimeValue = "NetCore_31" -) - -// PossibleSupportedRuntimeValueValues returns an array of possible values for the SupportedRuntimeValue const type. -func PossibleSupportedRuntimeValueValues() []SupportedRuntimeValue { - return []SupportedRuntimeValue{SupportedRuntimeValueJava11, SupportedRuntimeValueJava17, SupportedRuntimeValueJava8, SupportedRuntimeValueNetCore31} -} - -// TestKeyType enumerates the values for test key type. -type TestKeyType string - -const ( - // TestKeyTypePrimary ... - TestKeyTypePrimary TestKeyType = "Primary" - // TestKeyTypeSecondary ... - TestKeyTypeSecondary TestKeyType = "Secondary" -) - -// PossibleTestKeyTypeValues returns an array of possible values for the TestKeyType const type. -func PossibleTestKeyTypeValues() []TestKeyType { - return []TestKeyType{TestKeyTypePrimary, TestKeyTypeSecondary} -} - -// TrafficDirection enumerates the values for traffic direction. -type TrafficDirection string - -const ( - // TrafficDirectionInbound ... - TrafficDirectionInbound TrafficDirection = "Inbound" - // TrafficDirectionOutbound ... - TrafficDirectionOutbound TrafficDirection = "Outbound" -) - -// PossibleTrafficDirectionValues returns an array of possible values for the TrafficDirection const type. -func PossibleTrafficDirectionValues() []TrafficDirection { - return []TrafficDirection{TrafficDirectionInbound, TrafficDirectionOutbound} -} - -// Type enumerates the values for type. -type Type string - -const ( - // TypeAzureFileVolume ... - TypeAzureFileVolume Type = "AzureFileVolume" - // TypeCustomPersistentDiskProperties ... - TypeCustomPersistentDiskProperties Type = "CustomPersistentDiskProperties" -) - -// PossibleTypeValues returns an array of possible values for the Type const type. -func PossibleTypeValues() []Type { - return []Type{TypeAzureFileVolume, TypeCustomPersistentDiskProperties} -} - -// TypeBasicCertificateProperties enumerates the values for type basic certificate properties. -type TypeBasicCertificateProperties string - -const ( - // TypeBasicCertificatePropertiesTypeCertificateProperties ... - TypeBasicCertificatePropertiesTypeCertificateProperties TypeBasicCertificateProperties = "CertificateProperties" - // TypeBasicCertificatePropertiesTypeContentCertificate ... - TypeBasicCertificatePropertiesTypeContentCertificate TypeBasicCertificateProperties = "ContentCertificate" - // TypeBasicCertificatePropertiesTypeKeyVaultCertificate ... - TypeBasicCertificatePropertiesTypeKeyVaultCertificate TypeBasicCertificateProperties = "KeyVaultCertificate" -) - -// PossibleTypeBasicCertificatePropertiesValues returns an array of possible values for the TypeBasicCertificateProperties const type. -func PossibleTypeBasicCertificatePropertiesValues() []TypeBasicCertificateProperties { - return []TypeBasicCertificateProperties{TypeBasicCertificatePropertiesTypeCertificateProperties, TypeBasicCertificatePropertiesTypeContentCertificate, TypeBasicCertificatePropertiesTypeKeyVaultCertificate} -} - -// TypeBasicUserSourceInfo enumerates the values for type basic user source info. -type TypeBasicUserSourceInfo string - -const ( - // TypeBasicUserSourceInfoTypeBuildResult ... - TypeBasicUserSourceInfoTypeBuildResult TypeBasicUserSourceInfo = "BuildResult" - // TypeBasicUserSourceInfoTypeContainer ... - TypeBasicUserSourceInfoTypeContainer TypeBasicUserSourceInfo = "Container" - // TypeBasicUserSourceInfoTypeJar ... - TypeBasicUserSourceInfoTypeJar TypeBasicUserSourceInfo = "Jar" - // TypeBasicUserSourceInfoTypeNetCoreZip ... - TypeBasicUserSourceInfoTypeNetCoreZip TypeBasicUserSourceInfo = "NetCoreZip" - // TypeBasicUserSourceInfoTypeSource ... - TypeBasicUserSourceInfoTypeSource TypeBasicUserSourceInfo = "Source" - // TypeBasicUserSourceInfoTypeUploadedUserSourceInfo ... - TypeBasicUserSourceInfoTypeUploadedUserSourceInfo TypeBasicUserSourceInfo = "UploadedUserSourceInfo" - // TypeBasicUserSourceInfoTypeUserSourceInfo ... - TypeBasicUserSourceInfoTypeUserSourceInfo TypeBasicUserSourceInfo = "UserSourceInfo" -) - -// PossibleTypeBasicUserSourceInfoValues returns an array of possible values for the TypeBasicUserSourceInfo const type. -func PossibleTypeBasicUserSourceInfoValues() []TypeBasicUserSourceInfo { - return []TypeBasicUserSourceInfo{TypeBasicUserSourceInfoTypeBuildResult, TypeBasicUserSourceInfoTypeContainer, TypeBasicUserSourceInfoTypeJar, TypeBasicUserSourceInfoTypeNetCoreZip, TypeBasicUserSourceInfoTypeSource, TypeBasicUserSourceInfoTypeUploadedUserSourceInfo, TypeBasicUserSourceInfoTypeUserSourceInfo} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gatewaycustomdomains.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gatewaycustomdomains.go deleted file mode 100644 index 92e276558e5f..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gatewaycustomdomains.go +++ /dev/null @@ -1,404 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// GatewayCustomDomainsClient is the REST API for Azure Spring Cloud -type GatewayCustomDomainsClient struct { - BaseClient -} - -// NewGatewayCustomDomainsClient creates an instance of the GatewayCustomDomainsClient client. -func NewGatewayCustomDomainsClient(subscriptionID string) GatewayCustomDomainsClient { - return NewGatewayCustomDomainsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewGatewayCustomDomainsClientWithBaseURI creates an instance of the GatewayCustomDomainsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewGatewayCustomDomainsClientWithBaseURI(baseURI string, subscriptionID string) GatewayCustomDomainsClient { - return GatewayCustomDomainsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update the Spring Cloud Gateway custom domain. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -// domainName - the name of the Spring Cloud Gateway custom domain. -// gatewayCustomDomainResource - the gateway custom domain resource for the create or update operation -func (client GatewayCustomDomainsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string, gatewayCustomDomainResource GatewayCustomDomainResource) (result GatewayCustomDomainsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, gatewayName, domainName, gatewayCustomDomainResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client GatewayCustomDomainsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string, gatewayCustomDomainResource GatewayCustomDomainResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "domainName": autorest.Encode("path", domainName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/domains/{domainName}", pathParameters), - autorest.WithJSON(gatewayCustomDomainResource), - 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 GatewayCustomDomainsClient) CreateOrUpdateSender(req *http.Request) (future GatewayCustomDomainsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client GatewayCustomDomainsClient) CreateOrUpdateResponder(resp *http.Response) (result GatewayCustomDomainResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the Spring Cloud Gateway custom domain. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -// domainName - the name of the Spring Cloud Gateway custom domain. -func (client GatewayCustomDomainsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string) (result GatewayCustomDomainsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, gatewayName, domainName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client GatewayCustomDomainsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "domainName": autorest.Encode("path", domainName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/domains/{domainName}", 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 GatewayCustomDomainsClient) DeleteSender(req *http.Request) (future GatewayCustomDomainsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client GatewayCustomDomainsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the Spring Cloud Gateway custom domain. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -// domainName - the name of the Spring Cloud Gateway custom domain. -func (client GatewayCustomDomainsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string) (result GatewayCustomDomainResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, gatewayName, domainName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client GatewayCustomDomainsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, domainName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "domainName": autorest.Encode("path", domainName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/domains/{domainName}", 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 GatewayCustomDomainsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client GatewayCustomDomainsClient) GetResponder(resp *http.Response) (result GatewayCustomDomainResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handle requests to list all Spring Cloud Gateway custom domains. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -func (client GatewayCustomDomainsClient) List(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayCustomDomainResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.List") - defer func() { - sc := -1 - if result.gcdrc.Response.Response != nil { - sc = result.gcdrc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.gcdrc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "List", resp, "Failure sending request") - return - } - - result.gcdrc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "List", resp, "Failure responding to request") - return - } - if result.gcdrc.hasNextLink() && result.gcdrc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client GatewayCustomDomainsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/domains", 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 GatewayCustomDomainsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client GatewayCustomDomainsClient) ListResponder(resp *http.Response) (result GatewayCustomDomainResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 GatewayCustomDomainsClient) listNextResults(ctx context.Context, lastResults GatewayCustomDomainResourceCollection) (result GatewayCustomDomainResourceCollection, err error) { - req, err := lastResults.gatewayCustomDomainResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "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, "appplatform.GatewayCustomDomainsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client GatewayCustomDomainsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayCustomDomainResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName, gatewayName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gatewayrouteconfigs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gatewayrouteconfigs.go deleted file mode 100644 index c38a3d4171e8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gatewayrouteconfigs.go +++ /dev/null @@ -1,405 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// GatewayRouteConfigsClient is the REST API for Azure Spring Cloud -type GatewayRouteConfigsClient struct { - BaseClient -} - -// NewGatewayRouteConfigsClient creates an instance of the GatewayRouteConfigsClient client. -func NewGatewayRouteConfigsClient(subscriptionID string) GatewayRouteConfigsClient { - return NewGatewayRouteConfigsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewGatewayRouteConfigsClientWithBaseURI creates an instance of the GatewayRouteConfigsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewGatewayRouteConfigsClientWithBaseURI(baseURI string, subscriptionID string) GatewayRouteConfigsClient { - return GatewayRouteConfigsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create the default Spring Cloud Gateway route configs or update the existing Spring Cloud Gateway -// route configs. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -// routeConfigName - the name of the Spring Cloud Gateway route config. -// gatewayRouteConfigResource - the Spring Cloud Gateway route config for the create or update operation -func (client GatewayRouteConfigsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string, gatewayRouteConfigResource GatewayRouteConfigResource) (result GatewayRouteConfigsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, gatewayName, routeConfigName, gatewayRouteConfigResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client GatewayRouteConfigsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string, gatewayRouteConfigResource GatewayRouteConfigResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeConfigName": autorest.Encode("path", routeConfigName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/routeConfigs/{routeConfigName}", pathParameters), - autorest.WithJSON(gatewayRouteConfigResource), - 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 GatewayRouteConfigsClient) CreateOrUpdateSender(req *http.Request) (future GatewayRouteConfigsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client GatewayRouteConfigsClient) CreateOrUpdateResponder(resp *http.Response) (result GatewayRouteConfigResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the Spring Cloud Gateway route config. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -// routeConfigName - the name of the Spring Cloud Gateway route config. -func (client GatewayRouteConfigsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string) (result GatewayRouteConfigsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, gatewayName, routeConfigName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client GatewayRouteConfigsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeConfigName": autorest.Encode("path", routeConfigName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/routeConfigs/{routeConfigName}", 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 GatewayRouteConfigsClient) DeleteSender(req *http.Request) (future GatewayRouteConfigsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client GatewayRouteConfigsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the Spring Cloud Gateway route configs. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -// routeConfigName - the name of the Spring Cloud Gateway route config. -func (client GatewayRouteConfigsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string) (result GatewayRouteConfigResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, gatewayName, routeConfigName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client GatewayRouteConfigsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, routeConfigName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeConfigName": autorest.Encode("path", routeConfigName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/routeConfigs/{routeConfigName}", 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 GatewayRouteConfigsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client GatewayRouteConfigsClient) GetResponder(resp *http.Response) (result GatewayRouteConfigResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handle requests to list all Spring Cloud Gateway route configs. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -func (client GatewayRouteConfigsClient) List(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayRouteConfigResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.List") - defer func() { - sc := -1 - if result.grcrc.Response.Response != nil { - sc = result.grcrc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.grcrc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "List", resp, "Failure sending request") - return - } - - result.grcrc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "List", resp, "Failure responding to request") - return - } - if result.grcrc.hasNextLink() && result.grcrc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client GatewayRouteConfigsClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/routeConfigs", 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 GatewayRouteConfigsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client GatewayRouteConfigsClient) ListResponder(resp *http.Response) (result GatewayRouteConfigResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 GatewayRouteConfigsClient) listNextResults(ctx context.Context, lastResults GatewayRouteConfigResourceCollection) (result GatewayRouteConfigResourceCollection, err error) { - req, err := lastResults.gatewayRouteConfigResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "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, "appplatform.GatewayRouteConfigsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client GatewayRouteConfigsClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayRouteConfigResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName, gatewayName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gateways.go deleted file mode 100644 index 15cc5153762d..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/gateways.go +++ /dev/null @@ -1,484 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// GatewaysClient is the REST API for Azure Spring Cloud -type GatewaysClient struct { - BaseClient -} - -// NewGatewaysClient creates an instance of the GatewaysClient client. -func NewGatewaysClient(subscriptionID string) GatewaysClient { - return NewGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewGatewaysClientWithBaseURI creates an instance of the GatewaysClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewGatewaysClientWithBaseURI(baseURI string, subscriptionID string) GatewaysClient { - return GatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create the default Spring Cloud Gateway or update the existing Spring Cloud Gateway. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -// gatewayResource - the gateway for the create or update operation -func (client GatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, gatewayResource GatewayResource) (result GatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, gatewayName, gatewayResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client GatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, gatewayResource GatewayResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}", pathParameters), - autorest.WithJSON(gatewayResource), - 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 GatewaysClient) CreateOrUpdateSender(req *http.Request) (future GatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client GatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result GatewayResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete disable the default Spring Cloud Gateway. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -func (client GatewaysClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client GatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}", 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 GatewaysClient) DeleteSender(req *http.Request) (future GatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client GatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the Spring Cloud Gateway and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -func (client GatewaysClient) Get(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (result GatewayResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client GatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}", 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 GatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client GatewaysClient) GetResponder(resp *http.Response) (result GatewayResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handles requests to list all resources in a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client GatewaysClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result GatewayResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.List") - defer func() { - sc := -1 - if result.grc.Response.Response != nil { - sc = result.grc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.grc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "List", resp, "Failure sending request") - return - } - - result.grc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.grc.hasNextLink() && result.grc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client GatewaysClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/gateways", 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 GatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client GatewaysClient) ListResponder(resp *http.Response) (result GatewayResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 GatewaysClient) listNextResults(ctx context.Context, lastResults GatewayResourceCollection) (result GatewayResourceCollection, err error) { - req, err := lastResults.gatewayResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "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, "appplatform.GatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client GatewaysClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result GatewayResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName) - return -} - -// ValidateDomain check the domains are valid as well as not in use. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// gatewayName - the name of Spring Cloud Gateway. -// validatePayload - custom domain payload to be validated -func (client GatewaysClient) ValidateDomain(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, validatePayload CustomDomainValidatePayload) (result CustomDomainValidateResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewaysClient.ValidateDomain") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: validatePayload, - Constraints: []validation.Constraint{{Target: "validatePayload.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("appplatform.GatewaysClient", "ValidateDomain", err.Error()) - } - - req, err := client.ValidateDomainPreparer(ctx, resourceGroupName, serviceName, gatewayName, validatePayload) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "ValidateDomain", nil, "Failure preparing request") - return - } - - resp, err := client.ValidateDomainSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "ValidateDomain", resp, "Failure sending request") - return - } - - result, err = client.ValidateDomainResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysClient", "ValidateDomain", resp, "Failure responding to request") - return - } - - return -} - -// ValidateDomainPreparer prepares the ValidateDomain request. -func (client GatewaysClient) ValidateDomainPreparer(ctx context.Context, resourceGroupName string, serviceName string, gatewayName string, validatePayload CustomDomainValidatePayload) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/gateways/{gatewayName}/validateDomain", pathParameters), - autorest.WithJSON(validatePayload), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ValidateDomainSender sends the ValidateDomain request. The method will close the -// http.Response Body if it receives an error. -func (client GatewaysClient) ValidateDomainSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ValidateDomainResponder handles the response to the ValidateDomain request. The method always -// closes the http.Response Body. -func (client GatewaysClient) ValidateDomainResponder(resp *http.Response) (result CustomDomainValidateResult, err error) { - err = autorest.Respond( - resp, - 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/models.go deleted file mode 100644 index 071b9dbb6b5d..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/models.go +++ /dev/null @@ -1,9391 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform" - -// ActiveDeploymentCollection object that includes an array of Deployment resource name and set them as -// active. -type ActiveDeploymentCollection struct { - // ActiveDeploymentNames - Collection of Deployment name. - ActiveDeploymentNames *[]string `json:"activeDeploymentNames,omitempty"` -} - -// APIPortalCustomDomainProperties the properties of custom domain for API portal -type APIPortalCustomDomainProperties struct { - // Thumbprint - The thumbprint of bound certificate. - Thumbprint *string `json:"thumbprint,omitempty"` -} - -// APIPortalCustomDomainResource custom domain of the API portal -type APIPortalCustomDomainResource struct { - autorest.Response `json:"-"` - Properties *APIPortalCustomDomainProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for APIPortalCustomDomainResource. -func (apcdr APIPortalCustomDomainResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if apcdr.Properties != nil { - objectMap["properties"] = apcdr.Properties - } - if apcdr.SystemData != nil { - objectMap["systemData"] = apcdr.SystemData - } - return json.Marshal(objectMap) -} - -// APIPortalCustomDomainResourceCollection object that includes an array of API portal custom domain -// resources and a possible link for next set -type APIPortalCustomDomainResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of API portal custom domain resources - Value *[]APIPortalCustomDomainResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// APIPortalCustomDomainResourceCollectionIterator provides access to a complete listing of -// APIPortalCustomDomainResource values. -type APIPortalCustomDomainResourceCollectionIterator struct { - i int - page APIPortalCustomDomainResourceCollectionPage -} - -// NextWithContext 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 *APIPortalCustomDomainResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *APIPortalCustomDomainResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter APIPortalCustomDomainResourceCollectionIterator) 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 APIPortalCustomDomainResourceCollectionIterator) Response() APIPortalCustomDomainResourceCollection { - 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 APIPortalCustomDomainResourceCollectionIterator) Value() APIPortalCustomDomainResource { - if !iter.page.NotDone() { - return APIPortalCustomDomainResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the APIPortalCustomDomainResourceCollectionIterator type. -func NewAPIPortalCustomDomainResourceCollectionIterator(page APIPortalCustomDomainResourceCollectionPage) APIPortalCustomDomainResourceCollectionIterator { - return APIPortalCustomDomainResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (apcdrc APIPortalCustomDomainResourceCollection) IsEmpty() bool { - return apcdrc.Value == nil || len(*apcdrc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (apcdrc APIPortalCustomDomainResourceCollection) hasNextLink() bool { - return apcdrc.NextLink != nil && len(*apcdrc.NextLink) != 0 -} - -// aPIPortalCustomDomainResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (apcdrc APIPortalCustomDomainResourceCollection) aPIPortalCustomDomainResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !apcdrc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(apcdrc.NextLink))) -} - -// APIPortalCustomDomainResourceCollectionPage contains a page of APIPortalCustomDomainResource values. -type APIPortalCustomDomainResourceCollectionPage struct { - fn func(context.Context, APIPortalCustomDomainResourceCollection) (APIPortalCustomDomainResourceCollection, error) - apcdrc APIPortalCustomDomainResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *APIPortalCustomDomainResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalCustomDomainResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.apcdrc) - if err != nil { - return err - } - page.apcdrc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *APIPortalCustomDomainResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page APIPortalCustomDomainResourceCollectionPage) NotDone() bool { - return !page.apcdrc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page APIPortalCustomDomainResourceCollectionPage) Response() APIPortalCustomDomainResourceCollection { - return page.apcdrc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page APIPortalCustomDomainResourceCollectionPage) Values() []APIPortalCustomDomainResource { - if page.apcdrc.IsEmpty() { - return nil - } - return *page.apcdrc.Value -} - -// Creates a new instance of the APIPortalCustomDomainResourceCollectionPage type. -func NewAPIPortalCustomDomainResourceCollectionPage(cur APIPortalCustomDomainResourceCollection, getNextPage func(context.Context, APIPortalCustomDomainResourceCollection) (APIPortalCustomDomainResourceCollection, error)) APIPortalCustomDomainResourceCollectionPage { - return APIPortalCustomDomainResourceCollectionPage{ - fn: getNextPage, - apcdrc: cur, - } -} - -// APIPortalCustomDomainsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type APIPortalCustomDomainsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(APIPortalCustomDomainsClient) (APIPortalCustomDomainResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *APIPortalCustomDomainsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for APIPortalCustomDomainsCreateOrUpdateFuture.Result. -func (future *APIPortalCustomDomainsCreateOrUpdateFuture) result(client APIPortalCustomDomainsClient) (apcdr APIPortalCustomDomainResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - apcdr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.APIPortalCustomDomainsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if apcdr.Response.Response, err = future.GetResult(sender); err == nil && apcdr.Response.Response.StatusCode != http.StatusNoContent { - apcdr, err = client.CreateOrUpdateResponder(apcdr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsCreateOrUpdateFuture", "Result", apcdr.Response.Response, "Failure responding to request") - } - } - return -} - -// APIPortalCustomDomainsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type APIPortalCustomDomainsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(APIPortalCustomDomainsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *APIPortalCustomDomainsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for APIPortalCustomDomainsDeleteFuture.Result. -func (future *APIPortalCustomDomainsDeleteFuture) result(client APIPortalCustomDomainsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalCustomDomainsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.APIPortalCustomDomainsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// APIPortalInstance collection of instances belong to the API portal -type APIPortalInstance struct { - // Name - READ-ONLY; Name of the API portal instance - Name *string `json:"name,omitempty"` - // Status - READ-ONLY; Status of the API portal instance - Status *string `json:"status,omitempty"` -} - -// MarshalJSON is the custom marshaler for APIPortalInstance. -func (API APIPortalInstance) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// APIPortalProperties API portal properties payload -type APIPortalProperties struct { - // ProvisioningState - READ-ONLY; State of the API portal. Possible values include: 'APIPortalProvisioningStateCreating', 'APIPortalProvisioningStateUpdating', 'APIPortalProvisioningStateSucceeded', 'APIPortalProvisioningStateFailed', 'APIPortalProvisioningStateDeleting' - ProvisioningState APIPortalProvisioningState `json:"provisioningState,omitempty"` - // Public - Indicates whether the API portal exposes endpoint. - Public *bool `json:"public,omitempty"` - // URL - READ-ONLY; URL of the API portal, exposed when 'public' is true. - URL *string `json:"url,omitempty"` - // HTTPSOnly - Indicate if only https is allowed. - HTTPSOnly *bool `json:"httpsOnly,omitempty"` - // GatewayIds - The array of resource Ids of gateway to integrate with API portal. - GatewayIds *[]string `json:"gatewayIds,omitempty"` - // SourceUrls - Collection of OpenAPI source URL locations. - SourceUrls *[]string `json:"sourceUrls,omitempty"` - SsoProperties *SsoProperties `json:"ssoProperties,omitempty"` - // ResourceRequests - READ-ONLY; The requested resource quantity for required CPU and Memory. - ResourceRequests *APIPortalResourceRequests `json:"resourceRequests,omitempty"` - // Instances - READ-ONLY; Collection of instances belong to API portal. - Instances *[]APIPortalInstance `json:"instances,omitempty"` -} - -// MarshalJSON is the custom marshaler for APIPortalProperties. -func (app APIPortalProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if app.Public != nil { - objectMap["public"] = app.Public - } - if app.HTTPSOnly != nil { - objectMap["httpsOnly"] = app.HTTPSOnly - } - if app.GatewayIds != nil { - objectMap["gatewayIds"] = app.GatewayIds - } - if app.SourceUrls != nil { - objectMap["sourceUrls"] = app.SourceUrls - } - if app.SsoProperties != nil { - objectMap["ssoProperties"] = app.SsoProperties - } - return json.Marshal(objectMap) -} - -// APIPortalResource API portal resource -type APIPortalResource struct { - autorest.Response `json:"-"` - Properties *APIPortalProperties `json:"properties,omitempty"` - // Sku - Sku of the API portal resource - Sku *Sku `json:"sku,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for APIPortalResource. -func (apr APIPortalResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if apr.Properties != nil { - objectMap["properties"] = apr.Properties - } - if apr.Sku != nil { - objectMap["sku"] = apr.Sku - } - if apr.SystemData != nil { - objectMap["systemData"] = apr.SystemData - } - return json.Marshal(objectMap) -} - -// APIPortalResourceCollection object that includes an array of API portal resources and a possible link -// for next set -type APIPortalResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of API portal resources - Value *[]APIPortalResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// APIPortalResourceCollectionIterator provides access to a complete listing of APIPortalResource values. -type APIPortalResourceCollectionIterator struct { - i int - page APIPortalResourceCollectionPage -} - -// NextWithContext 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 *APIPortalResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *APIPortalResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter APIPortalResourceCollectionIterator) 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 APIPortalResourceCollectionIterator) Response() APIPortalResourceCollection { - 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 APIPortalResourceCollectionIterator) Value() APIPortalResource { - if !iter.page.NotDone() { - return APIPortalResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the APIPortalResourceCollectionIterator type. -func NewAPIPortalResourceCollectionIterator(page APIPortalResourceCollectionPage) APIPortalResourceCollectionIterator { - return APIPortalResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (aprc APIPortalResourceCollection) IsEmpty() bool { - return aprc.Value == nil || len(*aprc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (aprc APIPortalResourceCollection) hasNextLink() bool { - return aprc.NextLink != nil && len(*aprc.NextLink) != 0 -} - -// aPIPortalResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (aprc APIPortalResourceCollection) aPIPortalResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !aprc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(aprc.NextLink))) -} - -// APIPortalResourceCollectionPage contains a page of APIPortalResource values. -type APIPortalResourceCollectionPage struct { - fn func(context.Context, APIPortalResourceCollection) (APIPortalResourceCollection, error) - aprc APIPortalResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *APIPortalResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/APIPortalResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.aprc) - if err != nil { - return err - } - page.aprc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *APIPortalResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page APIPortalResourceCollectionPage) NotDone() bool { - return !page.aprc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page APIPortalResourceCollectionPage) Response() APIPortalResourceCollection { - return page.aprc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page APIPortalResourceCollectionPage) Values() []APIPortalResource { - if page.aprc.IsEmpty() { - return nil - } - return *page.aprc.Value -} - -// Creates a new instance of the APIPortalResourceCollectionPage type. -func NewAPIPortalResourceCollectionPage(cur APIPortalResourceCollection, getNextPage func(context.Context, APIPortalResourceCollection) (APIPortalResourceCollection, error)) APIPortalResourceCollectionPage { - return APIPortalResourceCollectionPage{ - fn: getNextPage, - aprc: cur, - } -} - -// APIPortalResourceRequests resource requests of the API portal -type APIPortalResourceRequests struct { - // CPU - READ-ONLY; Cpu allocated to each API portal instance - CPU *string `json:"cpu,omitempty"` - // Memory - READ-ONLY; Memory allocated to each API portal instance - Memory *string `json:"memory,omitempty"` -} - -// MarshalJSON is the custom marshaler for APIPortalResourceRequests. -func (aprr APIPortalResourceRequests) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// APIPortalsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type APIPortalsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(APIPortalsClient) (APIPortalResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *APIPortalsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for APIPortalsCreateOrUpdateFuture.Result. -func (future *APIPortalsCreateOrUpdateFuture) result(client APIPortalsClient) (apr APIPortalResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - apr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.APIPortalsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if apr.Response.Response, err = future.GetResult(sender); err == nil && apr.Response.Response.StatusCode != http.StatusNoContent { - apr, err = client.CreateOrUpdateResponder(apr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsCreateOrUpdateFuture", "Result", apr.Response.Response, "Failure responding to request") - } - } - return -} - -// APIPortalsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type APIPortalsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(APIPortalsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *APIPortalsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for APIPortalsDeleteFuture.Result. -func (future *APIPortalsDeleteFuture) result(client APIPortalsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.APIPortalsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.APIPortalsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ApplicationInsightsAgentVersions application Insights agent versions properties payload -type ApplicationInsightsAgentVersions struct { - // Java - READ-ONLY; Indicates the version of application insight java agent - Java *string `json:"java,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationInsightsAgentVersions. -func (aiav ApplicationInsightsAgentVersions) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// AppResource app resource payload -type AppResource struct { - autorest.Response `json:"-"` - // Properties - Properties of the App resource - Properties *AppResourceProperties `json:"properties,omitempty"` - // Identity - The Managed Identity type of the app resource - Identity *ManagedIdentityProperties `json:"identity,omitempty"` - // Location - The GEO location of the application, always the same with its parent resource - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for AppResource. -func (ar AppResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ar.Properties != nil { - objectMap["properties"] = ar.Properties - } - if ar.Identity != nil { - objectMap["identity"] = ar.Identity - } - if ar.Location != nil { - objectMap["location"] = ar.Location - } - if ar.SystemData != nil { - objectMap["systemData"] = ar.SystemData - } - return json.Marshal(objectMap) -} - -// AppResourceCollection object that includes an array of App resources and a possible link for next set -type AppResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of App resources - Value *[]AppResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// AppResourceCollectionIterator provides access to a complete listing of AppResource values. -type AppResourceCollectionIterator struct { - i int - page AppResourceCollectionPage -} - -// NextWithContext 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 *AppResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AppResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AppResourceCollectionIterator) 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 AppResourceCollectionIterator) Response() AppResourceCollection { - 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 AppResourceCollectionIterator) Value() AppResource { - if !iter.page.NotDone() { - return AppResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AppResourceCollectionIterator type. -func NewAppResourceCollectionIterator(page AppResourceCollectionPage) AppResourceCollectionIterator { - return AppResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (arc AppResourceCollection) IsEmpty() bool { - return arc.Value == nil || len(*arc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (arc AppResourceCollection) hasNextLink() bool { - return arc.NextLink != nil && len(*arc.NextLink) != 0 -} - -// appResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (arc AppResourceCollection) appResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !arc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(arc.NextLink))) -} - -// AppResourceCollectionPage contains a page of AppResource values. -type AppResourceCollectionPage struct { - fn func(context.Context, AppResourceCollection) (AppResourceCollection, error) - arc AppResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AppResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AppResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.arc) - if err != nil { - return err - } - page.arc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AppResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AppResourceCollectionPage) NotDone() bool { - return !page.arc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AppResourceCollectionPage) Response() AppResourceCollection { - return page.arc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AppResourceCollectionPage) Values() []AppResource { - if page.arc.IsEmpty() { - return nil - } - return *page.arc.Value -} - -// Creates a new instance of the AppResourceCollectionPage type. -func NewAppResourceCollectionPage(cur AppResourceCollection, getNextPage func(context.Context, AppResourceCollection) (AppResourceCollection, error)) AppResourceCollectionPage { - return AppResourceCollectionPage{ - fn: getNextPage, - arc: cur, - } -} - -// AppResourceProperties app resource properties payload -type AppResourceProperties struct { - // Public - Indicates whether the App exposes public endpoint - Public *bool `json:"public,omitempty"` - // URL - READ-ONLY; URL of the App - URL *string `json:"url,omitempty"` - // AddonConfigs - Collection of addons - AddonConfigs map[string]map[string]interface{} `json:"addonConfigs"` - // ProvisioningState - READ-ONLY; Provisioning state of the App. Possible values include: 'AppResourceProvisioningStateSucceeded', 'AppResourceProvisioningStateFailed', 'AppResourceProvisioningStateCreating', 'AppResourceProvisioningStateUpdating', 'AppResourceProvisioningStateDeleting' - ProvisioningState AppResourceProvisioningState `json:"provisioningState,omitempty"` - // Fqdn - Fully qualified dns Name. - Fqdn *string `json:"fqdn,omitempty"` - // HTTPSOnly - Indicate if only https is allowed. - HTTPSOnly *bool `json:"httpsOnly,omitempty"` - // TemporaryDisk - Temporary disk settings - TemporaryDisk *TemporaryDisk `json:"temporaryDisk,omitempty"` - // PersistentDisk - Persistent disk settings - PersistentDisk *PersistentDisk `json:"persistentDisk,omitempty"` - // CustomPersistentDisks - List of custom persistent disks - CustomPersistentDisks *[]CustomPersistentDiskResource `json:"customPersistentDisks,omitempty"` - // EnableEndToEndTLS - Indicate if end to end TLS is enabled. - EnableEndToEndTLS *bool `json:"enableEndToEndTLS,omitempty"` - // LoadedCertificates - Collection of loaded certificates - LoadedCertificates *[]LoadedCertificate `json:"loadedCertificates,omitempty"` -} - -// MarshalJSON is the custom marshaler for AppResourceProperties. -func (arp AppResourceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if arp.Public != nil { - objectMap["public"] = arp.Public - } - if arp.AddonConfigs != nil { - objectMap["addonConfigs"] = arp.AddonConfigs - } - if arp.Fqdn != nil { - objectMap["fqdn"] = arp.Fqdn - } - if arp.HTTPSOnly != nil { - objectMap["httpsOnly"] = arp.HTTPSOnly - } - if arp.TemporaryDisk != nil { - objectMap["temporaryDisk"] = arp.TemporaryDisk - } - if arp.PersistentDisk != nil { - objectMap["persistentDisk"] = arp.PersistentDisk - } - if arp.CustomPersistentDisks != nil { - objectMap["customPersistentDisks"] = arp.CustomPersistentDisks - } - if arp.EnableEndToEndTLS != nil { - objectMap["enableEndToEndTLS"] = arp.EnableEndToEndTLS - } - if arp.LoadedCertificates != nil { - objectMap["loadedCertificates"] = arp.LoadedCertificates - } - return json.Marshal(objectMap) -} - -// AppsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type AppsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AppsClient) (AppResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AppsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AppsCreateOrUpdateFuture.Result. -func (future *AppsCreateOrUpdateFuture) result(client AppsClient) (ar AppResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.AppsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ar.Response.Response, err = future.GetResult(sender); err == nil && ar.Response.Response.StatusCode != http.StatusNoContent { - ar, err = client.CreateOrUpdateResponder(ar.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsCreateOrUpdateFuture", "Result", ar.Response.Response, "Failure responding to request") - } - } - return -} - -// AppsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type AppsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AppsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AppsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AppsDeleteFuture.Result. -func (future *AppsDeleteFuture) result(client AppsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.AppsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// AppsSetActiveDeploymentsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type AppsSetActiveDeploymentsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AppsClient) (AppResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AppsSetActiveDeploymentsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AppsSetActiveDeploymentsFuture.Result. -func (future *AppsSetActiveDeploymentsFuture) result(client AppsClient) (ar AppResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsSetActiveDeploymentsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.AppsSetActiveDeploymentsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ar.Response.Response, err = future.GetResult(sender); err == nil && ar.Response.Response.StatusCode != http.StatusNoContent { - ar, err = client.SetActiveDeploymentsResponder(ar.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsSetActiveDeploymentsFuture", "Result", ar.Response.Response, "Failure responding to request") - } - } - return -} - -// AppsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type AppsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AppsClient) (AppResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AppsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AppsUpdateFuture.Result. -func (future *AppsUpdateFuture) result(client AppsClient) (ar AppResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.AppsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ar.Response.Response, err = future.GetResult(sender); err == nil && ar.Response.Response.StatusCode != http.StatusNoContent { - ar, err = client.UpdateResponder(ar.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.AppsUpdateFuture", "Result", ar.Response.Response, "Failure responding to request") - } - } - return -} - -// AvailableOperations available operations of the service -type AvailableOperations struct { - autorest.Response `json:"-"` - // Value - Collection of available operation details - Value *[]OperationDetail `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// AvailableOperationsIterator provides access to a complete listing of OperationDetail values. -type AvailableOperationsIterator struct { - i int - page AvailableOperationsPage -} - -// NextWithContext 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 *AvailableOperationsIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableOperationsIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AvailableOperationsIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AvailableOperationsIterator) 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 AvailableOperationsIterator) Response() AvailableOperations { - 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 AvailableOperationsIterator) Value() OperationDetail { - if !iter.page.NotDone() { - return OperationDetail{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AvailableOperationsIterator type. -func NewAvailableOperationsIterator(page AvailableOperationsPage) AvailableOperationsIterator { - return AvailableOperationsIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ao AvailableOperations) IsEmpty() bool { - return ao.Value == nil || len(*ao.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ao AvailableOperations) hasNextLink() bool { - return ao.NextLink != nil && len(*ao.NextLink) != 0 -} - -// availableOperationsPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ao AvailableOperations) availableOperationsPreparer(ctx context.Context) (*http.Request, error) { - if !ao.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ao.NextLink))) -} - -// AvailableOperationsPage contains a page of OperationDetail values. -type AvailableOperationsPage struct { - fn func(context.Context, AvailableOperations) (AvailableOperations, error) - ao AvailableOperations -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AvailableOperationsPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableOperationsPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ao) - if err != nil { - return err - } - page.ao = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AvailableOperationsPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AvailableOperationsPage) NotDone() bool { - return !page.ao.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AvailableOperationsPage) Response() AvailableOperations { - return page.ao -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AvailableOperationsPage) Values() []OperationDetail { - if page.ao.IsEmpty() { - return nil - } - return *page.ao.Value -} - -// Creates a new instance of the AvailableOperationsPage type. -func NewAvailableOperationsPage(cur AvailableOperations, getNextPage func(context.Context, AvailableOperations) (AvailableOperations, error)) AvailableOperationsPage { - return AvailableOperationsPage{ - fn: getNextPage, - ao: cur, - } -} - -// AvailableRuntimeVersions ... -type AvailableRuntimeVersions struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A list of all supported runtime versions. - Value *[]SupportedRuntimeVersion `json:"value,omitempty"` -} - -// MarshalJSON is the custom marshaler for AvailableRuntimeVersions. -func (arv AvailableRuntimeVersions) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// AzureFileVolume the properties of the Azure File volume. Azure File shares are mounted as volumes. -type AzureFileVolume struct { - // ShareName - The share name of the Azure File share. - ShareName *string `json:"shareName,omitempty"` - // MountPath - The mount path of the persistent disk. - MountPath *string `json:"mountPath,omitempty"` - // ReadOnly - Indicates whether the persistent disk is a readOnly one. - ReadOnly *bool `json:"readOnly,omitempty"` - // MountOptions - These are the mount options for a persistent disk. - MountOptions *[]string `json:"mountOptions,omitempty"` - // Type - Possible values include: 'TypeCustomPersistentDiskProperties', 'TypeAzureFileVolume' - Type Type `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFileVolume. -func (afv AzureFileVolume) MarshalJSON() ([]byte, error) { - afv.Type = TypeAzureFileVolume - objectMap := make(map[string]interface{}) - if afv.ShareName != nil { - objectMap["shareName"] = afv.ShareName - } - if afv.MountPath != nil { - objectMap["mountPath"] = afv.MountPath - } - if afv.ReadOnly != nil { - objectMap["readOnly"] = afv.ReadOnly - } - if afv.MountOptions != nil { - objectMap["mountOptions"] = afv.MountOptions - } - if afv.Type != "" { - objectMap["type"] = afv.Type - } - return json.Marshal(objectMap) -} - -// AsAzureFileVolume is the BasicCustomPersistentDiskProperties implementation for AzureFileVolume. -func (afv AzureFileVolume) AsAzureFileVolume() (*AzureFileVolume, bool) { - return &afv, true -} - -// AsCustomPersistentDiskProperties is the BasicCustomPersistentDiskProperties implementation for AzureFileVolume. -func (afv AzureFileVolume) AsCustomPersistentDiskProperties() (*CustomPersistentDiskProperties, bool) { - return nil, false -} - -// AsBasicCustomPersistentDiskProperties is the BasicCustomPersistentDiskProperties implementation for AzureFileVolume. -func (afv AzureFileVolume) AsBasicCustomPersistentDiskProperties() (BasicCustomPersistentDiskProperties, bool) { - return &afv, true -} - -// BindingResource binding resource payload -type BindingResource struct { - autorest.Response `json:"-"` - // Properties - Properties of the Binding resource - Properties *BindingResourceProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for BindingResource. -func (br BindingResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if br.Properties != nil { - objectMap["properties"] = br.Properties - } - if br.SystemData != nil { - objectMap["systemData"] = br.SystemData - } - return json.Marshal(objectMap) -} - -// BindingResourceCollection object that includes an array of Binding resources and a possible link for -// next set -type BindingResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of Binding resources - Value *[]BindingResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// BindingResourceCollectionIterator provides access to a complete listing of BindingResource values. -type BindingResourceCollectionIterator struct { - i int - page BindingResourceCollectionPage -} - -// NextWithContext 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 *BindingResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BindingResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BindingResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BindingResourceCollectionIterator) 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 BindingResourceCollectionIterator) Response() BindingResourceCollection { - 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 BindingResourceCollectionIterator) Value() BindingResource { - if !iter.page.NotDone() { - return BindingResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BindingResourceCollectionIterator type. -func NewBindingResourceCollectionIterator(page BindingResourceCollectionPage) BindingResourceCollectionIterator { - return BindingResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (brc BindingResourceCollection) IsEmpty() bool { - return brc.Value == nil || len(*brc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (brc BindingResourceCollection) hasNextLink() bool { - return brc.NextLink != nil && len(*brc.NextLink) != 0 -} - -// bindingResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (brc BindingResourceCollection) bindingResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !brc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(brc.NextLink))) -} - -// BindingResourceCollectionPage contains a page of BindingResource values. -type BindingResourceCollectionPage struct { - fn func(context.Context, BindingResourceCollection) (BindingResourceCollection, error) - brc BindingResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BindingResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BindingResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.brc) - if err != nil { - return err - } - page.brc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BindingResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BindingResourceCollectionPage) NotDone() bool { - return !page.brc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BindingResourceCollectionPage) Response() BindingResourceCollection { - return page.brc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BindingResourceCollectionPage) Values() []BindingResource { - if page.brc.IsEmpty() { - return nil - } - return *page.brc.Value -} - -// Creates a new instance of the BindingResourceCollectionPage type. -func NewBindingResourceCollectionPage(cur BindingResourceCollection, getNextPage func(context.Context, BindingResourceCollection) (BindingResourceCollection, error)) BindingResourceCollectionPage { - return BindingResourceCollectionPage{ - fn: getNextPage, - brc: cur, - } -} - -// BindingResourceProperties binding resource properties payload -type BindingResourceProperties struct { - // ResourceName - READ-ONLY; The name of the bound resource - ResourceName *string `json:"resourceName,omitempty"` - // ResourceType - READ-ONLY; The standard Azure resource type of the bound resource - ResourceType *string `json:"resourceType,omitempty"` - // ResourceID - The Azure resource id of the bound resource - ResourceID *string `json:"resourceId,omitempty"` - // Key - The key of the bound resource - Key *string `json:"key,omitempty"` - // BindingParameters - Binding parameters of the Binding resource - BindingParameters map[string]interface{} `json:"bindingParameters"` - // GeneratedProperties - READ-ONLY; The generated Spring Boot property file for this binding. The secret will be deducted. - GeneratedProperties *string `json:"generatedProperties,omitempty"` - // CreatedAt - READ-ONLY; Creation time of the Binding resource - CreatedAt *string `json:"createdAt,omitempty"` - // UpdatedAt - READ-ONLY; Update time of the Binding resource - UpdatedAt *string `json:"updatedAt,omitempty"` -} - -// MarshalJSON is the custom marshaler for BindingResourceProperties. -func (brp BindingResourceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if brp.ResourceID != nil { - objectMap["resourceId"] = brp.ResourceID - } - if brp.Key != nil { - objectMap["key"] = brp.Key - } - if brp.BindingParameters != nil { - objectMap["bindingParameters"] = brp.BindingParameters - } - return json.Marshal(objectMap) -} - -// BindingsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BindingsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BindingsClient) (BindingResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BindingsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BindingsCreateOrUpdateFuture.Result. -func (future *BindingsCreateOrUpdateFuture) result(client BindingsClient) (br BindingResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - br.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.BindingsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if br.Response.Response, err = future.GetResult(sender); err == nil && br.Response.Response.StatusCode != http.StatusNoContent { - br, err = client.CreateOrUpdateResponder(br.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsCreateOrUpdateFuture", "Result", br.Response.Response, "Failure responding to request") - } - } - return -} - -// BindingsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BindingsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BindingsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BindingsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BindingsDeleteFuture.Result. -func (future *BindingsDeleteFuture) result(client BindingsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.BindingsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// BindingsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BindingsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BindingsClient) (BindingResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BindingsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BindingsUpdateFuture.Result. -func (future *BindingsUpdateFuture) result(client BindingsClient) (br BindingResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - br.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.BindingsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if br.Response.Response, err = future.GetResult(sender); err == nil && br.Response.Response.StatusCode != http.StatusNoContent { - br, err = client.UpdateResponder(br.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BindingsUpdateFuture", "Result", br.Response.Response, "Failure responding to request") - } - } - return -} - -// Build build resource payload -type Build struct { - autorest.Response `json:"-"` - // Properties - Properties of the build resource - Properties *BuildProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for Build. -func (b Build) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if b.Properties != nil { - objectMap["properties"] = b.Properties - } - if b.SystemData != nil { - objectMap["systemData"] = b.SystemData - } - return json.Marshal(objectMap) -} - -// BuildCollection object that includes an array of Build resources and a possible link for next set -type BuildCollection struct { - autorest.Response `json:"-"` - // Value - Collection of Build resources - Value *[]Build `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// BuildCollectionIterator provides access to a complete listing of Build values. -type BuildCollectionIterator struct { - i int - page BuildCollectionPage -} - -// NextWithContext 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 *BuildCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BuildCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BuildCollectionIterator) 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 BuildCollectionIterator) Response() BuildCollection { - 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 BuildCollectionIterator) Value() Build { - if !iter.page.NotDone() { - return Build{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BuildCollectionIterator type. -func NewBuildCollectionIterator(page BuildCollectionPage) BuildCollectionIterator { - return BuildCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (bc BuildCollection) IsEmpty() bool { - return bc.Value == nil || len(*bc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (bc BuildCollection) hasNextLink() bool { - return bc.NextLink != nil && len(*bc.NextLink) != 0 -} - -// buildCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (bc BuildCollection) buildCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !bc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(bc.NextLink))) -} - -// BuildCollectionPage contains a page of Build values. -type BuildCollectionPage struct { - fn func(context.Context, BuildCollection) (BuildCollection, error) - bc BuildCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BuildCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.bc) - if err != nil { - return err - } - page.bc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BuildCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BuildCollectionPage) NotDone() bool { - return !page.bc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BuildCollectionPage) Response() BuildCollection { - return page.bc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BuildCollectionPage) Values() []Build { - if page.bc.IsEmpty() { - return nil - } - return *page.bc.Value -} - -// Creates a new instance of the BuildCollectionPage type. -func NewBuildCollectionPage(cur BuildCollection, getNextPage func(context.Context, BuildCollection) (BuildCollection, error)) BuildCollectionPage { - return BuildCollectionPage{ - fn: getNextPage, - bc: cur, - } -} - -// BuilderProperties kPack Builder properties payload -type BuilderProperties struct { - // ProvisioningState - READ-ONLY; Builder provision status. Possible values include: 'BuilderProvisioningStateCreating', 'BuilderProvisioningStateUpdating', 'BuilderProvisioningStateSucceeded', 'BuilderProvisioningStateFailed', 'BuilderProvisioningStateDeleting' - ProvisioningState BuilderProvisioningState `json:"provisioningState,omitempty"` - // Stack - Builder cluster stack property. - Stack *StackProperties `json:"stack,omitempty"` - // BuildpackGroups - Builder buildpack groups. - BuildpackGroups *[]BuildpacksGroupProperties `json:"buildpackGroups,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuilderProperties. -func (bp BuilderProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bp.Stack != nil { - objectMap["stack"] = bp.Stack - } - if bp.BuildpackGroups != nil { - objectMap["buildpackGroups"] = bp.BuildpackGroups - } - return json.Marshal(objectMap) -} - -// BuilderResource kPack Builder resource -type BuilderResource struct { - autorest.Response `json:"-"` - // Properties - Property of the Builder resource. - Properties *BuilderProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuilderResource. -func (br BuilderResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if br.Properties != nil { - objectMap["properties"] = br.Properties - } - if br.SystemData != nil { - objectMap["systemData"] = br.SystemData - } - return json.Marshal(objectMap) -} - -// BuilderResourceCollection object that includes an array of Builder resources and a possible link for -// next set -type BuilderResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of Builder resources - Value *[]BuilderResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// BuilderResourceCollectionIterator provides access to a complete listing of BuilderResource values. -type BuilderResourceCollectionIterator struct { - i int - page BuilderResourceCollectionPage -} - -// NextWithContext 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 *BuilderResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuilderResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BuilderResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BuilderResourceCollectionIterator) 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 BuilderResourceCollectionIterator) Response() BuilderResourceCollection { - 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 BuilderResourceCollectionIterator) Value() BuilderResource { - if !iter.page.NotDone() { - return BuilderResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BuilderResourceCollectionIterator type. -func NewBuilderResourceCollectionIterator(page BuilderResourceCollectionPage) BuilderResourceCollectionIterator { - return BuilderResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (brc BuilderResourceCollection) IsEmpty() bool { - return brc.Value == nil || len(*brc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (brc BuilderResourceCollection) hasNextLink() bool { - return brc.NextLink != nil && len(*brc.NextLink) != 0 -} - -// builderResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (brc BuilderResourceCollection) builderResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !brc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(brc.NextLink))) -} - -// BuilderResourceCollectionPage contains a page of BuilderResource values. -type BuilderResourceCollectionPage struct { - fn func(context.Context, BuilderResourceCollection) (BuilderResourceCollection, error) - brc BuilderResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BuilderResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuilderResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.brc) - if err != nil { - return err - } - page.brc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BuilderResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BuilderResourceCollectionPage) NotDone() bool { - return !page.brc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BuilderResourceCollectionPage) Response() BuilderResourceCollection { - return page.brc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BuilderResourceCollectionPage) Values() []BuilderResource { - if page.brc.IsEmpty() { - return nil - } - return *page.brc.Value -} - -// Creates a new instance of the BuilderResourceCollectionPage type. -func NewBuilderResourceCollectionPage(cur BuilderResourceCollection, getNextPage func(context.Context, BuilderResourceCollection) (BuilderResourceCollection, error)) BuilderResourceCollectionPage { - return BuilderResourceCollectionPage{ - fn: getNextPage, - brc: cur, - } -} - -// BuildpackBindingCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type BuildpackBindingCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BuildpackBindingClient) (BuildpackBindingResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BuildpackBindingCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BuildpackBindingCreateOrUpdateFuture.Result. -func (future *BuildpackBindingCreateOrUpdateFuture) result(client BuildpackBindingClient) (bbr BuildpackBindingResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bbr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.BuildpackBindingCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bbr.Response.Response, err = future.GetResult(sender); err == nil && bbr.Response.Response.StatusCode != http.StatusNoContent { - bbr, err = client.CreateOrUpdateResponder(bbr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingCreateOrUpdateFuture", "Result", bbr.Response.Response, "Failure responding to request") - } - } - return -} - -// BuildpackBindingDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BuildpackBindingDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BuildpackBindingClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BuildpackBindingDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BuildpackBindingDeleteFuture.Result. -func (future *BuildpackBindingDeleteFuture) result(client BuildpackBindingClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildpackBindingDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.BuildpackBindingDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// BuildpackBindingLaunchProperties buildpack Binding Launch Properties -type BuildpackBindingLaunchProperties struct { - // Properties - Non-sensitive properties for launchProperties - Properties map[string]*string `json:"properties"` - // Secrets - Sensitive properties for launchProperties - Secrets map[string]*string `json:"secrets"` -} - -// MarshalJSON is the custom marshaler for BuildpackBindingLaunchProperties. -func (bblp BuildpackBindingLaunchProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bblp.Properties != nil { - objectMap["properties"] = bblp.Properties - } - if bblp.Secrets != nil { - objectMap["secrets"] = bblp.Secrets - } - return json.Marshal(objectMap) -} - -// BuildpackBindingProperties properties of a buildpack binding -type BuildpackBindingProperties struct { - // BindingType - Buildpack Binding Type. Possible values include: 'BindingTypeApplicationInsights', 'BindingTypeApacheSkyWalking', 'BindingTypeAppDynamics', 'BindingTypeDynatrace', 'BindingTypeNewRelic', 'BindingTypeElasticAPM' - BindingType BindingType `json:"bindingType,omitempty"` - // ProvisioningState - READ-ONLY; State of the Buildpack Binding. Possible values include: 'BuildpackBindingProvisioningStateCreating', 'BuildpackBindingProvisioningStateUpdating', 'BuildpackBindingProvisioningStateSucceeded', 'BuildpackBindingProvisioningStateFailed', 'BuildpackBindingProvisioningStateDeleting' - ProvisioningState BuildpackBindingProvisioningState `json:"provisioningState,omitempty"` - // LaunchProperties - The object describes the buildpack binding launch properties - LaunchProperties *BuildpackBindingLaunchProperties `json:"launchProperties,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildpackBindingProperties. -func (bbp BuildpackBindingProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bbp.BindingType != "" { - objectMap["bindingType"] = bbp.BindingType - } - if bbp.LaunchProperties != nil { - objectMap["launchProperties"] = bbp.LaunchProperties - } - return json.Marshal(objectMap) -} - -// BuildpackBindingResource buildpack Binding Resource object -type BuildpackBindingResource struct { - autorest.Response `json:"-"` - // Properties - Properties of a buildpack binding - Properties *BuildpackBindingProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildpackBindingResource. -func (bbr BuildpackBindingResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bbr.Properties != nil { - objectMap["properties"] = bbr.Properties - } - if bbr.SystemData != nil { - objectMap["systemData"] = bbr.SystemData - } - return json.Marshal(objectMap) -} - -// BuildpackBindingResourceCollection object that includes an array of BuildpackBinding resources and a -// possible link for next set -type BuildpackBindingResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of BuildpackBinding resources - Value *[]BuildpackBindingResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// BuildpackBindingResourceCollectionIterator provides access to a complete listing of -// BuildpackBindingResource values. -type BuildpackBindingResourceCollectionIterator struct { - i int - page BuildpackBindingResourceCollectionPage -} - -// NextWithContext 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 *BuildpackBindingResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BuildpackBindingResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BuildpackBindingResourceCollectionIterator) 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 BuildpackBindingResourceCollectionIterator) Response() BuildpackBindingResourceCollection { - 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 BuildpackBindingResourceCollectionIterator) Value() BuildpackBindingResource { - if !iter.page.NotDone() { - return BuildpackBindingResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BuildpackBindingResourceCollectionIterator type. -func NewBuildpackBindingResourceCollectionIterator(page BuildpackBindingResourceCollectionPage) BuildpackBindingResourceCollectionIterator { - return BuildpackBindingResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (bbrc BuildpackBindingResourceCollection) IsEmpty() bool { - return bbrc.Value == nil || len(*bbrc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (bbrc BuildpackBindingResourceCollection) hasNextLink() bool { - return bbrc.NextLink != nil && len(*bbrc.NextLink) != 0 -} - -// buildpackBindingResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (bbrc BuildpackBindingResourceCollection) buildpackBindingResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !bbrc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(bbrc.NextLink))) -} - -// BuildpackBindingResourceCollectionPage contains a page of BuildpackBindingResource values. -type BuildpackBindingResourceCollectionPage struct { - fn func(context.Context, BuildpackBindingResourceCollection) (BuildpackBindingResourceCollection, error) - bbrc BuildpackBindingResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BuildpackBindingResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildpackBindingResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.bbrc) - if err != nil { - return err - } - page.bbrc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BuildpackBindingResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BuildpackBindingResourceCollectionPage) NotDone() bool { - return !page.bbrc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BuildpackBindingResourceCollectionPage) Response() BuildpackBindingResourceCollection { - return page.bbrc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BuildpackBindingResourceCollectionPage) Values() []BuildpackBindingResource { - if page.bbrc.IsEmpty() { - return nil - } - return *page.bbrc.Value -} - -// Creates a new instance of the BuildpackBindingResourceCollectionPage type. -func NewBuildpackBindingResourceCollectionPage(cur BuildpackBindingResourceCollection, getNextPage func(context.Context, BuildpackBindingResourceCollection) (BuildpackBindingResourceCollection, error)) BuildpackBindingResourceCollectionPage { - return BuildpackBindingResourceCollectionPage{ - fn: getNextPage, - bbrc: cur, - } -} - -// BuildpackProperties buildpack properties payload -type BuildpackProperties struct { - // ID - Id of the buildpack - ID *string `json:"id,omitempty"` -} - -// BuildpacksGroupProperties buildpack group properties of the Builder -type BuildpacksGroupProperties struct { - // Name - Buildpack group name - Name *string `json:"name,omitempty"` - // Buildpacks - Buildpacks in the buildpack group - Buildpacks *[]BuildpackProperties `json:"buildpacks,omitempty"` -} - -// BuildProperties build resource properties payload -type BuildProperties struct { - // RelativePath - The relative path of source code - RelativePath *string `json:"relativePath,omitempty"` - // Builder - The resource id of builder to build the source code - Builder *string `json:"builder,omitempty"` - // AgentPool - The resource id of agent pool - AgentPool *string `json:"agentPool,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the KPack build result. Possible values include: 'BuildProvisioningStateCreating', 'BuildProvisioningStateUpdating', 'BuildProvisioningStateSucceeded', 'BuildProvisioningStateFailed', 'BuildProvisioningStateDeleting' - ProvisioningState BuildProvisioningState `json:"provisioningState,omitempty"` - // Env - The environment variables for this build - Env map[string]*string `json:"env"` - // TriggeredBuildResult - The build result triggered by this build - TriggeredBuildResult *TriggeredBuildResult `json:"triggeredBuildResult,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildProperties. -func (bp BuildProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bp.RelativePath != nil { - objectMap["relativePath"] = bp.RelativePath - } - if bp.Builder != nil { - objectMap["builder"] = bp.Builder - } - if bp.AgentPool != nil { - objectMap["agentPool"] = bp.AgentPool - } - if bp.Env != nil { - objectMap["env"] = bp.Env - } - if bp.TriggeredBuildResult != nil { - objectMap["triggeredBuildResult"] = bp.TriggeredBuildResult - } - return json.Marshal(objectMap) -} - -// BuildResult build result resource payload -type BuildResult struct { - autorest.Response `json:"-"` - // Properties - Properties of the build result resource - Properties *BuildResultProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildResult. -func (br BuildResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if br.Properties != nil { - objectMap["properties"] = br.Properties - } - if br.SystemData != nil { - objectMap["systemData"] = br.SystemData - } - return json.Marshal(objectMap) -} - -// BuildResultCollection object that includes an array of Build result resources and a possible link for -// next set -type BuildResultCollection struct { - autorest.Response `json:"-"` - // Value - Collection of Build result resources - Value *[]BuildResult `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// BuildResultCollectionIterator provides access to a complete listing of BuildResult values. -type BuildResultCollectionIterator struct { - i int - page BuildResultCollectionPage -} - -// NextWithContext 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 *BuildResultCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildResultCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BuildResultCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BuildResultCollectionIterator) 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 BuildResultCollectionIterator) Response() BuildResultCollection { - 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 BuildResultCollectionIterator) Value() BuildResult { - if !iter.page.NotDone() { - return BuildResult{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BuildResultCollectionIterator type. -func NewBuildResultCollectionIterator(page BuildResultCollectionPage) BuildResultCollectionIterator { - return BuildResultCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (brc BuildResultCollection) IsEmpty() bool { - return brc.Value == nil || len(*brc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (brc BuildResultCollection) hasNextLink() bool { - return brc.NextLink != nil && len(*brc.NextLink) != 0 -} - -// buildResultCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (brc BuildResultCollection) buildResultCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !brc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(brc.NextLink))) -} - -// BuildResultCollectionPage contains a page of BuildResult values. -type BuildResultCollectionPage struct { - fn func(context.Context, BuildResultCollection) (BuildResultCollection, error) - brc BuildResultCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BuildResultCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildResultCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.brc) - if err != nil { - return err - } - page.brc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BuildResultCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BuildResultCollectionPage) NotDone() bool { - return !page.brc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BuildResultCollectionPage) Response() BuildResultCollection { - return page.brc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BuildResultCollectionPage) Values() []BuildResult { - if page.brc.IsEmpty() { - return nil - } - return *page.brc.Value -} - -// Creates a new instance of the BuildResultCollectionPage type. -func NewBuildResultCollectionPage(cur BuildResultCollection, getNextPage func(context.Context, BuildResultCollection) (BuildResultCollection, error)) BuildResultCollectionPage { - return BuildResultCollectionPage{ - fn: getNextPage, - brc: cur, - } -} - -// BuildResultLog build result log resource properties payload -type BuildResultLog struct { - autorest.Response `json:"-"` - // BlobURL - The public download URL of this build result log - BlobURL *string `json:"blobUrl,omitempty"` -} - -// BuildResultProperties build result resource properties payload -type BuildResultProperties struct { - // Name - The name of this build result - Name *string `json:"name,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the KPack build result. Possible values include: 'BuildResultProvisioningStateQueuing', 'BuildResultProvisioningStateBuilding', 'BuildResultProvisioningStateSucceeded', 'BuildResultProvisioningStateFailed', 'BuildResultProvisioningStateDeleting' - ProvisioningState BuildResultProvisioningState `json:"provisioningState,omitempty"` - // BuildPodName - The build pod name which can be used to get the build log streaming. - BuildPodName *string `json:"buildPodName,omitempty"` - // BuildStages - READ-ONLY; All of the build stage (init-container and container) resources in build pod. - BuildStages *[]BuildStageProperties `json:"buildStages,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildResultProperties. -func (brp BuildResultProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if brp.Name != nil { - objectMap["name"] = brp.Name - } - if brp.BuildPodName != nil { - objectMap["buildPodName"] = brp.BuildPodName - } - return json.Marshal(objectMap) -} - -// BuildResultUserSourceInfo reference to a build result -type BuildResultUserSourceInfo struct { - // BuildResultID - Resource id of an existing succeeded build result under the same Spring instance. - BuildResultID *string `json:"buildResultId,omitempty"` - // Version - Version of the source - Version *string `json:"version,omitempty"` - // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' - Type TypeBasicUserSourceInfo `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) MarshalJSON() ([]byte, error) { - brusi.Type = TypeBasicUserSourceInfoTypeBuildResult - objectMap := make(map[string]interface{}) - if brusi.BuildResultID != nil { - objectMap["buildResultId"] = brusi.BuildResultID - } - if brusi.Version != nil { - objectMap["version"] = brusi.Version - } - if brusi.Type != "" { - objectMap["type"] = brusi.Type - } - return json.Marshal(objectMap) -} - -// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { - return &brusi, true -} - -// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { - return nil, false -} - -// AsUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { - return nil, false -} - -// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for BuildResultUserSourceInfo. -func (brusi BuildResultUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { - return &brusi, true -} - -// BuildService build service resource payload -type BuildService struct { - autorest.Response `json:"-"` - // Properties - Properties of the build resource - Properties *BuildServiceProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildService. -func (bs BuildService) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bs.Properties != nil { - objectMap["properties"] = bs.Properties - } - if bs.SystemData != nil { - objectMap["systemData"] = bs.SystemData - } - return json.Marshal(objectMap) -} - -// BuildServiceAgentPoolProperties build service agent pool properties -type BuildServiceAgentPoolProperties struct { - // ProvisioningState - READ-ONLY; Provisioning state of the build service agent pool - ProvisioningState *string `json:"provisioningState,omitempty"` - // PoolSize - build service agent pool size properties - PoolSize *BuildServiceAgentPoolSizeProperties `json:"poolSize,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildServiceAgentPoolProperties. -func (bsapp BuildServiceAgentPoolProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bsapp.PoolSize != nil { - objectMap["poolSize"] = bsapp.PoolSize - } - return json.Marshal(objectMap) -} - -// BuildServiceAgentPoolResource the build service agent pool resource -type BuildServiceAgentPoolResource struct { - autorest.Response `json:"-"` - // Properties - build service agent pool properties - Properties *BuildServiceAgentPoolProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildServiceAgentPoolResource. -func (bsapr BuildServiceAgentPoolResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bsapr.Properties != nil { - objectMap["properties"] = bsapr.Properties - } - if bsapr.SystemData != nil { - objectMap["systemData"] = bsapr.SystemData - } - return json.Marshal(objectMap) -} - -// BuildServiceAgentPoolResourceCollection object that includes an array of build service agent pool -// resources and a possible link for next set -type BuildServiceAgentPoolResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of build service agent pool resource - Value *[]BuildServiceAgentPoolResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// BuildServiceAgentPoolResourceCollectionIterator provides access to a complete listing of -// BuildServiceAgentPoolResource values. -type BuildServiceAgentPoolResourceCollectionIterator struct { - i int - page BuildServiceAgentPoolResourceCollectionPage -} - -// NextWithContext 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 *BuildServiceAgentPoolResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BuildServiceAgentPoolResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BuildServiceAgentPoolResourceCollectionIterator) 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 BuildServiceAgentPoolResourceCollectionIterator) Response() BuildServiceAgentPoolResourceCollection { - 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 BuildServiceAgentPoolResourceCollectionIterator) Value() BuildServiceAgentPoolResource { - if !iter.page.NotDone() { - return BuildServiceAgentPoolResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BuildServiceAgentPoolResourceCollectionIterator type. -func NewBuildServiceAgentPoolResourceCollectionIterator(page BuildServiceAgentPoolResourceCollectionPage) BuildServiceAgentPoolResourceCollectionIterator { - return BuildServiceAgentPoolResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (bsaprc BuildServiceAgentPoolResourceCollection) IsEmpty() bool { - return bsaprc.Value == nil || len(*bsaprc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (bsaprc BuildServiceAgentPoolResourceCollection) hasNextLink() bool { - return bsaprc.NextLink != nil && len(*bsaprc.NextLink) != 0 -} - -// buildServiceAgentPoolResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (bsaprc BuildServiceAgentPoolResourceCollection) buildServiceAgentPoolResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !bsaprc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(bsaprc.NextLink))) -} - -// BuildServiceAgentPoolResourceCollectionPage contains a page of BuildServiceAgentPoolResource values. -type BuildServiceAgentPoolResourceCollectionPage struct { - fn func(context.Context, BuildServiceAgentPoolResourceCollection) (BuildServiceAgentPoolResourceCollection, error) - bsaprc BuildServiceAgentPoolResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BuildServiceAgentPoolResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceAgentPoolResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.bsaprc) - if err != nil { - return err - } - page.bsaprc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BuildServiceAgentPoolResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BuildServiceAgentPoolResourceCollectionPage) NotDone() bool { - return !page.bsaprc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BuildServiceAgentPoolResourceCollectionPage) Response() BuildServiceAgentPoolResourceCollection { - return page.bsaprc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BuildServiceAgentPoolResourceCollectionPage) Values() []BuildServiceAgentPoolResource { - if page.bsaprc.IsEmpty() { - return nil - } - return *page.bsaprc.Value -} - -// Creates a new instance of the BuildServiceAgentPoolResourceCollectionPage type. -func NewBuildServiceAgentPoolResourceCollectionPage(cur BuildServiceAgentPoolResourceCollection, getNextPage func(context.Context, BuildServiceAgentPoolResourceCollection) (BuildServiceAgentPoolResourceCollection, error)) BuildServiceAgentPoolResourceCollectionPage { - return BuildServiceAgentPoolResourceCollectionPage{ - fn: getNextPage, - bsaprc: cur, - } -} - -// BuildServiceAgentPoolSizeProperties build service agent pool size properties -type BuildServiceAgentPoolSizeProperties struct { - // Name - The name of build service agent pool size - Name *string `json:"name,omitempty"` - // CPU - READ-ONLY; The cpu property of build service agent pool size - CPU *string `json:"cpu,omitempty"` - // Memory - READ-ONLY; The memory property of build service agent pool size - Memory *string `json:"memory,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildServiceAgentPoolSizeProperties. -func (bsapsp BuildServiceAgentPoolSizeProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bsapsp.Name != nil { - objectMap["name"] = bsapsp.Name - } - return json.Marshal(objectMap) -} - -// BuildServiceAgentPoolUpdatePutFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type BuildServiceAgentPoolUpdatePutFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BuildServiceAgentPoolClient) (BuildServiceAgentPoolResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BuildServiceAgentPoolUpdatePutFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BuildServiceAgentPoolUpdatePutFuture.Result. -func (future *BuildServiceAgentPoolUpdatePutFuture) result(client BuildServiceAgentPoolClient) (bsapr BuildServiceAgentPoolResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolUpdatePutFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bsapr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.BuildServiceAgentPoolUpdatePutFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bsapr.Response.Response, err = future.GetResult(sender); err == nil && bsapr.Response.Response.StatusCode != http.StatusNoContent { - bsapr, err = client.UpdatePutResponder(bsapr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceAgentPoolUpdatePutFuture", "Result", bsapr.Response.Response, "Failure responding to request") - } - } - return -} - -// BuildServiceBuilderCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type BuildServiceBuilderCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BuildServiceBuilderClient) (BuilderResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BuildServiceBuilderCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BuildServiceBuilderCreateOrUpdateFuture.Result. -func (future *BuildServiceBuilderCreateOrUpdateFuture) result(client BuildServiceBuilderClient) (br BuilderResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - br.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.BuildServiceBuilderCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if br.Response.Response, err = future.GetResult(sender); err == nil && br.Response.Response.StatusCode != http.StatusNoContent { - br, err = client.CreateOrUpdateResponder(br.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderCreateOrUpdateFuture", "Result", br.Response.Response, "Failure responding to request") - } - } - return -} - -// BuildServiceBuilderDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type BuildServiceBuilderDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BuildServiceBuilderClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BuildServiceBuilderDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BuildServiceBuilderDeleteFuture.Result. -func (future *BuildServiceBuilderDeleteFuture) result(client BuildServiceBuilderClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.BuildServiceBuilderDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.BuildServiceBuilderDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// BuildServiceCollection object that includes an array of Build service resources and a possible link for -// next set -type BuildServiceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of Build service resources - Value *[]BuildService `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// BuildServiceCollectionIterator provides access to a complete listing of BuildService values. -type BuildServiceCollectionIterator struct { - i int - page BuildServiceCollectionPage -} - -// NextWithContext 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 *BuildServiceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BuildServiceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BuildServiceCollectionIterator) 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 BuildServiceCollectionIterator) Response() BuildServiceCollection { - 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 BuildServiceCollectionIterator) Value() BuildService { - if !iter.page.NotDone() { - return BuildService{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BuildServiceCollectionIterator type. -func NewBuildServiceCollectionIterator(page BuildServiceCollectionPage) BuildServiceCollectionIterator { - return BuildServiceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (bsc BuildServiceCollection) IsEmpty() bool { - return bsc.Value == nil || len(*bsc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (bsc BuildServiceCollection) hasNextLink() bool { - return bsc.NextLink != nil && len(*bsc.NextLink) != 0 -} - -// buildServiceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (bsc BuildServiceCollection) buildServiceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !bsc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(bsc.NextLink))) -} - -// BuildServiceCollectionPage contains a page of BuildService values. -type BuildServiceCollectionPage struct { - fn func(context.Context, BuildServiceCollection) (BuildServiceCollection, error) - bsc BuildServiceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BuildServiceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BuildServiceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.bsc) - if err != nil { - return err - } - page.bsc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BuildServiceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BuildServiceCollectionPage) NotDone() bool { - return !page.bsc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BuildServiceCollectionPage) Response() BuildServiceCollection { - return page.bsc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BuildServiceCollectionPage) Values() []BuildService { - if page.bsc.IsEmpty() { - return nil - } - return *page.bsc.Value -} - -// Creates a new instance of the BuildServiceCollectionPage type. -func NewBuildServiceCollectionPage(cur BuildServiceCollection, getNextPage func(context.Context, BuildServiceCollection) (BuildServiceCollection, error)) BuildServiceCollectionPage { - return BuildServiceCollectionPage{ - fn: getNextPage, - bsc: cur, - } -} - -// BuildServiceProperties build service resource properties payload -type BuildServiceProperties struct { - // KPackVersion - The installed KPack version in this build service. - KPackVersion *string `json:"kPackVersion,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the KPack build result. Possible values include: 'BuildServiceProvisioningStateCreating', 'BuildServiceProvisioningStateUpdating', 'BuildServiceProvisioningStateSucceeded', 'BuildServiceProvisioningStateFailed', 'BuildServiceProvisioningStateDeleting' - ProvisioningState BuildServiceProvisioningState `json:"provisioningState,omitempty"` - // ResourceRequests - The runtime resource configuration of this build service. - ResourceRequests *BuildServicePropertiesResourceRequests `json:"resourceRequests,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildServiceProperties. -func (bsp BuildServiceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bsp.KPackVersion != nil { - objectMap["kPackVersion"] = bsp.KPackVersion - } - if bsp.ResourceRequests != nil { - objectMap["resourceRequests"] = bsp.ResourceRequests - } - return json.Marshal(objectMap) -} - -// BuildServicePropertiesResourceRequests the runtime resource configuration of this build service. -type BuildServicePropertiesResourceRequests struct { - // CPU - READ-ONLY; vCPU allocated to the entire build service node pool. - CPU *string `json:"cpu,omitempty"` - // Memory - READ-ONLY; Memory allocated to the entire build service node pool. - Memory *string `json:"memory,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildServicePropertiesResourceRequests. -func (bspR BuildServicePropertiesResourceRequests) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// BuildStageProperties the build stage (init-container and container) resources in build pod. -type BuildStageProperties struct { - // Name - READ-ONLY; The name of this build stage resource. - Name *string `json:"name,omitempty"` - // Status - READ-ONLY; The provisioning state of this build stage resource. Possible values include: 'KPackBuildStageProvisioningStateNotStarted', 'KPackBuildStageProvisioningStateRunning', 'KPackBuildStageProvisioningStateSucceeded', 'KPackBuildStageProvisioningStateFailed' - Status KPackBuildStageProvisioningState `json:"status,omitempty"` -} - -// MarshalJSON is the custom marshaler for BuildStageProperties. -func (bsp BuildStageProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// BasicCertificateProperties certificate resource payload. -type BasicCertificateProperties interface { - AsKeyVaultCertificateProperties() (*KeyVaultCertificateProperties, bool) - AsContentCertificateProperties() (*ContentCertificateProperties, bool) - AsCertificateProperties() (*CertificateProperties, bool) -} - -// CertificateProperties certificate resource payload. -type CertificateProperties struct { - // Thumbprint - READ-ONLY; The thumbprint of certificate. - Thumbprint *string `json:"thumbprint,omitempty"` - // Issuer - READ-ONLY; The issuer of certificate. - Issuer *string `json:"issuer,omitempty"` - // IssuedDate - READ-ONLY; The issue date of certificate. - IssuedDate *string `json:"issuedDate,omitempty"` - // ExpirationDate - READ-ONLY; The expiration date of certificate. - ExpirationDate *string `json:"expirationDate,omitempty"` - // ActivateDate - READ-ONLY; The activate date of certificate. - ActivateDate *string `json:"activateDate,omitempty"` - // SubjectName - READ-ONLY; The subject name of certificate. - SubjectName *string `json:"subjectName,omitempty"` - // DNSNames - READ-ONLY; The domain list of certificate. - DNSNames *[]string `json:"dnsNames,omitempty"` - // Type - Possible values include: 'TypeBasicCertificatePropertiesTypeCertificateProperties', 'TypeBasicCertificatePropertiesTypeKeyVaultCertificate', 'TypeBasicCertificatePropertiesTypeContentCertificate' - Type TypeBasicCertificateProperties `json:"type,omitempty"` -} - -func unmarshalBasicCertificateProperties(body []byte) (BasicCertificateProperties, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["type"] { - case string(TypeBasicCertificatePropertiesTypeKeyVaultCertificate): - var kvcp KeyVaultCertificateProperties - err := json.Unmarshal(body, &kvcp) - return kvcp, err - case string(TypeBasicCertificatePropertiesTypeContentCertificate): - var ccp ContentCertificateProperties - err := json.Unmarshal(body, &ccp) - return ccp, err - default: - var cp CertificateProperties - err := json.Unmarshal(body, &cp) - return cp, err - } -} -func unmarshalBasicCertificatePropertiesArray(body []byte) ([]BasicCertificateProperties, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - cpArray := make([]BasicCertificateProperties, len(rawMessages)) - - for index, rawMessage := range rawMessages { - cp, err := unmarshalBasicCertificateProperties(*rawMessage) - if err != nil { - return nil, err - } - cpArray[index] = cp - } - return cpArray, nil -} - -// MarshalJSON is the custom marshaler for CertificateProperties. -func (cp CertificateProperties) MarshalJSON() ([]byte, error) { - cp.Type = TypeBasicCertificatePropertiesTypeCertificateProperties - objectMap := make(map[string]interface{}) - if cp.Type != "" { - objectMap["type"] = cp.Type - } - return json.Marshal(objectMap) -} - -// AsKeyVaultCertificateProperties is the BasicCertificateProperties implementation for CertificateProperties. -func (cp CertificateProperties) AsKeyVaultCertificateProperties() (*KeyVaultCertificateProperties, bool) { - return nil, false -} - -// AsContentCertificateProperties is the BasicCertificateProperties implementation for CertificateProperties. -func (cp CertificateProperties) AsContentCertificateProperties() (*ContentCertificateProperties, bool) { - return nil, false -} - -// AsCertificateProperties is the BasicCertificateProperties implementation for CertificateProperties. -func (cp CertificateProperties) AsCertificateProperties() (*CertificateProperties, bool) { - return &cp, true -} - -// AsBasicCertificateProperties is the BasicCertificateProperties implementation for CertificateProperties. -func (cp CertificateProperties) AsBasicCertificateProperties() (BasicCertificateProperties, bool) { - return &cp, true -} - -// CertificateResource certificate resource payload. -type CertificateResource struct { - autorest.Response `json:"-"` - // Properties - Properties of the certificate resource payload. - Properties BasicCertificateProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for CertificateResource. -func (cr CertificateResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - objectMap["properties"] = cr.Properties - if cr.SystemData != nil { - objectMap["systemData"] = cr.SystemData - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for CertificateResource struct. -func (cr *CertificateResource) 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 { - properties, err := unmarshalBasicCertificateProperties(*v) - if err != nil { - return err - } - cr.Properties = properties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cr.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cr.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cr.Type = &typeVar - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - cr.SystemData = &systemData - } - } - } - - return nil -} - -// CertificateResourceCollection collection compose of certificate resources list and a possible link for -// next page. -type CertificateResourceCollection struct { - autorest.Response `json:"-"` - // Value - The certificate resources list. - Value *[]CertificateResource `json:"value,omitempty"` - // NextLink - The link to next page of certificate list. - NextLink *string `json:"nextLink,omitempty"` -} - -// CertificateResourceCollectionIterator provides access to a complete listing of CertificateResource -// values. -type CertificateResourceCollectionIterator struct { - i int - page CertificateResourceCollectionPage -} - -// NextWithContext 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 *CertificateResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificateResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *CertificateResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter CertificateResourceCollectionIterator) 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 CertificateResourceCollectionIterator) Response() CertificateResourceCollection { - 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 CertificateResourceCollectionIterator) Value() CertificateResource { - if !iter.page.NotDone() { - return CertificateResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the CertificateResourceCollectionIterator type. -func NewCertificateResourceCollectionIterator(page CertificateResourceCollectionPage) CertificateResourceCollectionIterator { - return CertificateResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (crc CertificateResourceCollection) IsEmpty() bool { - return crc.Value == nil || len(*crc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (crc CertificateResourceCollection) hasNextLink() bool { - return crc.NextLink != nil && len(*crc.NextLink) != 0 -} - -// certificateResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (crc CertificateResourceCollection) certificateResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !crc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(crc.NextLink))) -} - -// CertificateResourceCollectionPage contains a page of CertificateResource values. -type CertificateResourceCollectionPage struct { - fn func(context.Context, CertificateResourceCollection) (CertificateResourceCollection, error) - crc CertificateResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *CertificateResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificateResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.crc) - if err != nil { - return err - } - page.crc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *CertificateResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page CertificateResourceCollectionPage) NotDone() bool { - return !page.crc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page CertificateResourceCollectionPage) Response() CertificateResourceCollection { - return page.crc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page CertificateResourceCollectionPage) Values() []CertificateResource { - if page.crc.IsEmpty() { - return nil - } - return *page.crc.Value -} - -// Creates a new instance of the CertificateResourceCollectionPage type. -func NewCertificateResourceCollectionPage(cur CertificateResourceCollection, getNextPage func(context.Context, CertificateResourceCollection) (CertificateResourceCollection, error)) CertificateResourceCollectionPage { - return CertificateResourceCollectionPage{ - fn: getNextPage, - crc: cur, - } -} - -// CertificatesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type CertificatesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(CertificatesClient) (CertificateResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *CertificatesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for CertificatesCreateOrUpdateFuture.Result. -func (future *CertificatesCreateOrUpdateFuture) result(client CertificatesClient) (cr CertificateResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.CertificatesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cr.Response.Response, err = future.GetResult(sender); err == nil && cr.Response.Response.StatusCode != http.StatusNoContent { - cr, err = client.CreateOrUpdateResponder(cr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesCreateOrUpdateFuture", "Result", cr.Response.Response, "Failure responding to request") - } - } - return -} - -// CertificatesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type CertificatesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(CertificatesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *CertificatesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for CertificatesDeleteFuture.Result. -func (future *CertificatesDeleteFuture) result(client CertificatesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CertificatesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.CertificatesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// CloudError an error response from the service. -type CloudError struct { - // Error - An error response from the service. - Error *CloudErrorBody `json:"error,omitempty"` -} - -// CloudErrorBody an error response from the service. -type CloudErrorBody struct { - // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. - Code *string `json:"code,omitempty"` - // Message - A message describing the error, intended to be suitable for display in a user interface. - Message *string `json:"message,omitempty"` - // Target - The target of the particular error. For example, the name of the property in error. - Target *string `json:"target,omitempty"` - // Details - A list of additional details about the error. - Details *[]CloudErrorBody `json:"details,omitempty"` -} - -// ClusterResourceProperties service properties payload -type ClusterResourceProperties struct { - // ProvisioningState - READ-ONLY; Provisioning state of the Service. Possible values include: 'ProvisioningStateCreating', 'ProvisioningStateUpdating', 'ProvisioningStateStarting', 'ProvisioningStateStopping', 'ProvisioningStateDeleting', 'ProvisioningStateDeleted', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateMoving', 'ProvisioningStateMoved', 'ProvisioningStateMoveFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // NetworkProfile - Network profile of the Service - NetworkProfile *NetworkProfile `json:"networkProfile,omitempty"` - // Version - READ-ONLY; Version of the Service - Version *int32 `json:"version,omitempty"` - // ServiceID - READ-ONLY; ServiceInstanceEntity GUID which uniquely identifies a created resource - ServiceID *string `json:"serviceId,omitempty"` - // PowerState - READ-ONLY; Power state of the Service. Possible values include: 'PowerStateRunning', 'PowerStateStopped' - PowerState PowerState `json:"powerState,omitempty"` - ZoneRedundant *bool `json:"zoneRedundant,omitempty"` - // Fqdn - READ-ONLY; Fully qualified dns name of the service instance - Fqdn *string `json:"fqdn,omitempty"` -} - -// MarshalJSON is the custom marshaler for ClusterResourceProperties. -func (crp ClusterResourceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if crp.NetworkProfile != nil { - objectMap["networkProfile"] = crp.NetworkProfile - } - if crp.ZoneRedundant != nil { - objectMap["zoneRedundant"] = crp.ZoneRedundant - } - return json.Marshal(objectMap) -} - -// ConfigServerGitProperty property of git. -type ConfigServerGitProperty struct { - // Repositories - Repositories of git. - Repositories *[]GitPatternRepository `json:"repositories,omitempty"` - // URI - URI of the repository - URI *string `json:"uri,omitempty"` - // Label - Label of the repository - Label *string `json:"label,omitempty"` - // SearchPaths - Searching path of the repository - SearchPaths *[]string `json:"searchPaths,omitempty"` - // Username - Username of git repository basic auth. - Username *string `json:"username,omitempty"` - // Password - Password of git repository basic auth. - Password *string `json:"password,omitempty"` - // HostKey - Public sshKey of git repository. - HostKey *string `json:"hostKey,omitempty"` - // HostKeyAlgorithm - SshKey algorithm of git repository. - HostKeyAlgorithm *string `json:"hostKeyAlgorithm,omitempty"` - // PrivateKey - Private sshKey algorithm of git repository. - PrivateKey *string `json:"privateKey,omitempty"` - // StrictHostKeyChecking - Strict host key checking or not. - StrictHostKeyChecking *bool `json:"strictHostKeyChecking,omitempty"` -} - -// ConfigServerProperties config server git properties payload -type ConfigServerProperties struct { - // ProvisioningState - READ-ONLY; State of the config server. Possible values include: 'ConfigServerStateNotAvailable', 'ConfigServerStateDeleted', 'ConfigServerStateFailed', 'ConfigServerStateSucceeded', 'ConfigServerStateUpdating' - ProvisioningState ConfigServerState `json:"provisioningState,omitempty"` - // Error - Error when apply config server settings. - Error *Error `json:"error,omitempty"` - // ConfigServer - Settings of config server. - ConfigServer *ConfigServerSettings `json:"configServer,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConfigServerProperties. -func (csp ConfigServerProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if csp.Error != nil { - objectMap["error"] = csp.Error - } - if csp.ConfigServer != nil { - objectMap["configServer"] = csp.ConfigServer - } - return json.Marshal(objectMap) -} - -// ConfigServerResource config Server resource -type ConfigServerResource struct { - autorest.Response `json:"-"` - // Properties - Properties of the Config Server resource - Properties *ConfigServerProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConfigServerResource. -func (csr ConfigServerResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if csr.Properties != nil { - objectMap["properties"] = csr.Properties - } - if csr.SystemData != nil { - objectMap["systemData"] = csr.SystemData - } - return json.Marshal(objectMap) -} - -// ConfigServerSettings the settings of config server. -type ConfigServerSettings struct { - // GitProperty - Property of git environment. - GitProperty *ConfigServerGitProperty `json:"gitProperty,omitempty"` -} - -// ConfigServerSettingsErrorRecord error record of the config server settings -type ConfigServerSettingsErrorRecord struct { - // Name - The name of the config server settings error record - Name *string `json:"name,omitempty"` - // URI - The uri of the config server settings error record - URI *string `json:"uri,omitempty"` - // Messages - The detail error messages of the record - Messages *[]string `json:"messages,omitempty"` -} - -// ConfigServerSettingsValidateResult validation result for config server settings -type ConfigServerSettingsValidateResult struct { - autorest.Response `json:"-"` - // IsValid - Indicate if the config server settings are valid - IsValid *bool `json:"isValid,omitempty"` - // Details - The detail validation results - Details *[]ConfigServerSettingsErrorRecord `json:"details,omitempty"` -} - -// ConfigServersUpdatePatchFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConfigServersUpdatePatchFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConfigServersClient) (ConfigServerResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConfigServersUpdatePatchFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConfigServersUpdatePatchFuture.Result. -func (future *ConfigServersUpdatePatchFuture) result(client ConfigServersClient) (csr ConfigServerResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersUpdatePatchFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - csr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ConfigServersUpdatePatchFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if csr.Response.Response, err = future.GetResult(sender); err == nil && csr.Response.Response.StatusCode != http.StatusNoContent { - csr, err = client.UpdatePatchResponder(csr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersUpdatePatchFuture", "Result", csr.Response.Response, "Failure responding to request") - } - } - return -} - -// ConfigServersUpdatePutFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ConfigServersUpdatePutFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConfigServersClient) (ConfigServerResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConfigServersUpdatePutFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConfigServersUpdatePutFuture.Result. -func (future *ConfigServersUpdatePutFuture) result(client ConfigServersClient) (csr ConfigServerResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersUpdatePutFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - csr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ConfigServersUpdatePutFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if csr.Response.Response, err = future.GetResult(sender); err == nil && csr.Response.Response.StatusCode != http.StatusNoContent { - csr, err = client.UpdatePutResponder(csr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersUpdatePutFuture", "Result", csr.Response.Response, "Failure responding to request") - } - } - return -} - -// ConfigServersValidateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ConfigServersValidateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConfigServersClient) (ConfigServerSettingsValidateResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConfigServersValidateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConfigServersValidateFuture.Result. -func (future *ConfigServersValidateFuture) result(client ConfigServersClient) (cssvr ConfigServerSettingsValidateResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersValidateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cssvr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ConfigServersValidateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cssvr.Response.Response, err = future.GetResult(sender); err == nil && cssvr.Response.Response.StatusCode != http.StatusNoContent { - cssvr, err = client.ValidateResponder(cssvr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigServersValidateFuture", "Result", cssvr.Response.Response, "Failure responding to request") - } - } - return -} - -// ConfigurationServiceGitProperty property of git environment. -type ConfigurationServiceGitProperty struct { - Repositories *[]ConfigurationServiceGitRepository `json:"repositories,omitempty"` -} - -// ConfigurationServiceGitPropertyValidateResult validation result for configuration service settings -type ConfigurationServiceGitPropertyValidateResult struct { - // IsValid - Indicate if the configuration service settings are valid - IsValid *bool `json:"isValid,omitempty"` - // GitReposValidationResult - The detail validation results - GitReposValidationResult *[]ValidationMessages `json:"gitReposValidationResult,omitempty"` -} - -// ConfigurationServiceGitRepository git repository property payload for Application Configuration Service -type ConfigurationServiceGitRepository struct { - // Name - Name of the repository - Name *string `json:"name,omitempty"` - // Patterns - Collection of patterns of the repository - Patterns *[]string `json:"patterns,omitempty"` - // URI - URI of the repository - URI *string `json:"uri,omitempty"` - // Label - Label of the repository - Label *string `json:"label,omitempty"` - // SearchPaths - Searching path of the repository - SearchPaths *[]string `json:"searchPaths,omitempty"` - // Username - Username of git repository basic auth. - Username *string `json:"username,omitempty"` - // Password - Password of git repository basic auth. - Password *string `json:"password,omitempty"` - // HostKey - Public sshKey of git repository. - HostKey *string `json:"hostKey,omitempty"` - // HostKeyAlgorithm - SshKey algorithm of git repository. - HostKeyAlgorithm *string `json:"hostKeyAlgorithm,omitempty"` - // PrivateKey - Private sshKey algorithm of git repository. - PrivateKey *string `json:"privateKey,omitempty"` - // StrictHostKeyChecking - Strict host key checking or not. - StrictHostKeyChecking *bool `json:"strictHostKeyChecking,omitempty"` -} - -// ConfigurationServiceInstance collection of instances belong to the Application Configuration Service -type ConfigurationServiceInstance struct { - // Name - READ-ONLY; Name of the Application Configuration Service instance - Name *string `json:"name,omitempty"` - // Status - READ-ONLY; Status of the Application Configuration Service instance - Status *string `json:"status,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConfigurationServiceInstance. -func (csi ConfigurationServiceInstance) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConfigurationServiceProperties application Configuration Service properties payload -type ConfigurationServiceProperties struct { - // ProvisioningState - READ-ONLY; State of the Application Configuration Service. Possible values include: 'ConfigurationServiceProvisioningStateCreating', 'ConfigurationServiceProvisioningStateUpdating', 'ConfigurationServiceProvisioningStateSucceeded', 'ConfigurationServiceProvisioningStateFailed', 'ConfigurationServiceProvisioningStateDeleting' - ProvisioningState ConfigurationServiceProvisioningState `json:"provisioningState,omitempty"` - // ResourceRequests - The requested resource quantity for required CPU and Memory. - ResourceRequests *ConfigurationServiceResourceRequests `json:"resourceRequests,omitempty"` - // Instances - READ-ONLY; Collection of instances belong to Application Configuration Service. - Instances *[]ConfigurationServiceInstance `json:"instances,omitempty"` - Settings *ConfigurationServiceSettings `json:"settings,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConfigurationServiceProperties. -func (csp ConfigurationServiceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if csp.ResourceRequests != nil { - objectMap["resourceRequests"] = csp.ResourceRequests - } - if csp.Settings != nil { - objectMap["settings"] = csp.Settings - } - return json.Marshal(objectMap) -} - -// ConfigurationServiceResource application Configuration Service resource -type ConfigurationServiceResource struct { - autorest.Response `json:"-"` - Properties *ConfigurationServiceProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConfigurationServiceResource. -func (csr ConfigurationServiceResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if csr.Properties != nil { - objectMap["properties"] = csr.Properties - } - if csr.SystemData != nil { - objectMap["systemData"] = csr.SystemData - } - return json.Marshal(objectMap) -} - -// ConfigurationServiceResourceCollection object that includes an array of configuration service resources -// and a possible link for next set -type ConfigurationServiceResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of configuration service resources - Value *[]ConfigurationServiceResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// ConfigurationServiceResourceCollectionIterator provides access to a complete listing of -// ConfigurationServiceResource values. -type ConfigurationServiceResourceCollectionIterator struct { - i int - page ConfigurationServiceResourceCollectionPage -} - -// NextWithContext 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 *ConfigurationServiceResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServiceResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ConfigurationServiceResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ConfigurationServiceResourceCollectionIterator) 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 ConfigurationServiceResourceCollectionIterator) Response() ConfigurationServiceResourceCollection { - 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 ConfigurationServiceResourceCollectionIterator) Value() ConfigurationServiceResource { - if !iter.page.NotDone() { - return ConfigurationServiceResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ConfigurationServiceResourceCollectionIterator type. -func NewConfigurationServiceResourceCollectionIterator(page ConfigurationServiceResourceCollectionPage) ConfigurationServiceResourceCollectionIterator { - return ConfigurationServiceResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (csrc ConfigurationServiceResourceCollection) IsEmpty() bool { - return csrc.Value == nil || len(*csrc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (csrc ConfigurationServiceResourceCollection) hasNextLink() bool { - return csrc.NextLink != nil && len(*csrc.NextLink) != 0 -} - -// configurationServiceResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (csrc ConfigurationServiceResourceCollection) configurationServiceResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !csrc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(csrc.NextLink))) -} - -// ConfigurationServiceResourceCollectionPage contains a page of ConfigurationServiceResource values. -type ConfigurationServiceResourceCollectionPage struct { - fn func(context.Context, ConfigurationServiceResourceCollection) (ConfigurationServiceResourceCollection, error) - csrc ConfigurationServiceResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ConfigurationServiceResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationServiceResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.csrc) - if err != nil { - return err - } - page.csrc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ConfigurationServiceResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ConfigurationServiceResourceCollectionPage) NotDone() bool { - return !page.csrc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ConfigurationServiceResourceCollectionPage) Response() ConfigurationServiceResourceCollection { - return page.csrc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ConfigurationServiceResourceCollectionPage) Values() []ConfigurationServiceResource { - if page.csrc.IsEmpty() { - return nil - } - return *page.csrc.Value -} - -// Creates a new instance of the ConfigurationServiceResourceCollectionPage type. -func NewConfigurationServiceResourceCollectionPage(cur ConfigurationServiceResourceCollection, getNextPage func(context.Context, ConfigurationServiceResourceCollection) (ConfigurationServiceResourceCollection, error)) ConfigurationServiceResourceCollectionPage { - return ConfigurationServiceResourceCollectionPage{ - fn: getNextPage, - csrc: cur, - } -} - -// ConfigurationServiceResourceRequests resource request payload of Application Configuration Service -type ConfigurationServiceResourceRequests struct { - // CPU - READ-ONLY; Cpu allocated to each Application Configuration Service instance - CPU *string `json:"cpu,omitempty"` - // Memory - READ-ONLY; Memory allocated to each Application Configuration Service instance - Memory *string `json:"memory,omitempty"` - // InstanceCount - READ-ONLY; Instance count of the Application Configuration Service - InstanceCount *int32 `json:"instanceCount,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConfigurationServiceResourceRequests. -func (csrr ConfigurationServiceResourceRequests) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConfigurationServicesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConfigurationServicesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConfigurationServicesClient) (ConfigurationServiceResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConfigurationServicesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConfigurationServicesCreateOrUpdateFuture.Result. -func (future *ConfigurationServicesCreateOrUpdateFuture) result(client ConfigurationServicesClient) (csr ConfigurationServiceResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - csr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ConfigurationServicesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if csr.Response.Response, err = future.GetResult(sender); err == nil && csr.Response.Response.StatusCode != http.StatusNoContent { - csr, err = client.CreateOrUpdateResponder(csr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesCreateOrUpdateFuture", "Result", csr.Response.Response, "Failure responding to request") - } - } - return -} - -// ConfigurationServicesDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConfigurationServicesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConfigurationServicesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConfigurationServicesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConfigurationServicesDeleteFuture.Result. -func (future *ConfigurationServicesDeleteFuture) result(client ConfigurationServicesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ConfigurationServicesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ConfigurationServiceSettings the settings of Application Configuration Service. -type ConfigurationServiceSettings struct { - GitProperty *ConfigurationServiceGitProperty `json:"gitProperty,omitempty"` -} - -// ConfigurationServiceSettingsValidateResult validation result for configuration service settings -type ConfigurationServiceSettingsValidateResult struct { - autorest.Response `json:"-"` - GitPropertyValidationResult *ConfigurationServiceGitPropertyValidateResult `json:"gitPropertyValidationResult,omitempty"` -} - -// ConfigurationServicesValidateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConfigurationServicesValidateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConfigurationServicesClient) (ConfigurationServiceSettingsValidateResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConfigurationServicesValidateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConfigurationServicesValidateFuture.Result. -func (future *ConfigurationServicesValidateFuture) result(client ConfigurationServicesClient) (cssvr ConfigurationServiceSettingsValidateResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesValidateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cssvr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ConfigurationServicesValidateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cssvr.Response.Response, err = future.GetResult(sender); err == nil && cssvr.Response.Response.StatusCode != http.StatusNoContent { - cssvr, err = client.ValidateResponder(cssvr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ConfigurationServicesValidateFuture", "Result", cssvr.Response.Response, "Failure responding to request") - } - } - return -} - -// ContainerProbeSettings container liveness and readiness probe settings -type ContainerProbeSettings struct { - // DisableProbe - Indicates whether disable the liveness and readiness probe - DisableProbe *bool `json:"disableProbe,omitempty"` -} - -// ContentCertificateProperties properties of certificate imported from key vault. -type ContentCertificateProperties struct { - // Content - The content of uploaded certificate. - Content *string `json:"content,omitempty"` - // Thumbprint - READ-ONLY; The thumbprint of certificate. - Thumbprint *string `json:"thumbprint,omitempty"` - // Issuer - READ-ONLY; The issuer of certificate. - Issuer *string `json:"issuer,omitempty"` - // IssuedDate - READ-ONLY; The issue date of certificate. - IssuedDate *string `json:"issuedDate,omitempty"` - // ExpirationDate - READ-ONLY; The expiration date of certificate. - ExpirationDate *string `json:"expirationDate,omitempty"` - // ActivateDate - READ-ONLY; The activate date of certificate. - ActivateDate *string `json:"activateDate,omitempty"` - // SubjectName - READ-ONLY; The subject name of certificate. - SubjectName *string `json:"subjectName,omitempty"` - // DNSNames - READ-ONLY; The domain list of certificate. - DNSNames *[]string `json:"dnsNames,omitempty"` - // Type - Possible values include: 'TypeBasicCertificatePropertiesTypeCertificateProperties', 'TypeBasicCertificatePropertiesTypeKeyVaultCertificate', 'TypeBasicCertificatePropertiesTypeContentCertificate' - Type TypeBasicCertificateProperties `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContentCertificateProperties. -func (ccp ContentCertificateProperties) MarshalJSON() ([]byte, error) { - ccp.Type = TypeBasicCertificatePropertiesTypeContentCertificate - objectMap := make(map[string]interface{}) - if ccp.Content != nil { - objectMap["content"] = ccp.Content - } - if ccp.Type != "" { - objectMap["type"] = ccp.Type - } - return json.Marshal(objectMap) -} - -// AsKeyVaultCertificateProperties is the BasicCertificateProperties implementation for ContentCertificateProperties. -func (ccp ContentCertificateProperties) AsKeyVaultCertificateProperties() (*KeyVaultCertificateProperties, bool) { - return nil, false -} - -// AsContentCertificateProperties is the BasicCertificateProperties implementation for ContentCertificateProperties. -func (ccp ContentCertificateProperties) AsContentCertificateProperties() (*ContentCertificateProperties, bool) { - return &ccp, true -} - -// AsCertificateProperties is the BasicCertificateProperties implementation for ContentCertificateProperties. -func (ccp ContentCertificateProperties) AsCertificateProperties() (*CertificateProperties, bool) { - return nil, false -} - -// AsBasicCertificateProperties is the BasicCertificateProperties implementation for ContentCertificateProperties. -func (ccp ContentCertificateProperties) AsBasicCertificateProperties() (BasicCertificateProperties, bool) { - return &ccp, true -} - -// CustomContainer custom container payload -type CustomContainer struct { - // Server - The name of the registry that contains the container image - Server *string `json:"server,omitempty"` - // ContainerImage - Container image of the custom container. This should be in the form of : without the server name of the registry - ContainerImage *string `json:"containerImage,omitempty"` - // Command - Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. - Command *[]string `json:"command,omitempty"` - // Args - Arguments to the entrypoint. The docker image's CMD is used if this is not provided. - Args *[]string `json:"args,omitempty"` - // ImageRegistryCredential - Credential of the image registry - ImageRegistryCredential *ImageRegistryCredential `json:"imageRegistryCredential,omitempty"` - // LanguageFramework - Language framework of the container image uploaded - LanguageFramework *string `json:"languageFramework,omitempty"` -} - -// CustomContainerUserSourceInfo custom container user source info -type CustomContainerUserSourceInfo struct { - CustomContainer *CustomContainer `json:"customContainer,omitempty"` - // Version - Version of the source - Version *string `json:"version,omitempty"` - // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' - Type TypeBasicUserSourceInfo `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) MarshalJSON() ([]byte, error) { - ccusi.Type = TypeBasicUserSourceInfoTypeContainer - objectMap := make(map[string]interface{}) - if ccusi.CustomContainer != nil { - objectMap["customContainer"] = ccusi.CustomContainer - } - if ccusi.Version != nil { - objectMap["version"] = ccusi.Version - } - if ccusi.Type != "" { - objectMap["type"] = ccusi.Type - } - return json.Marshal(objectMap) -} - -// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { - return nil, false -} - -// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { - return &ccusi, true -} - -// AsUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { - return nil, false -} - -// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for CustomContainerUserSourceInfo. -func (ccusi CustomContainerUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { - return &ccusi, true -} - -// CustomDomainProperties custom domain of app resource payload. -type CustomDomainProperties struct { - // Thumbprint - The thumbprint of bound certificate. - Thumbprint *string `json:"thumbprint,omitempty"` - // AppName - READ-ONLY; The app name of domain. - AppName *string `json:"appName,omitempty"` - // CertName - The bound certificate name of domain. - CertName *string `json:"certName,omitempty"` -} - -// MarshalJSON is the custom marshaler for CustomDomainProperties. -func (cdp CustomDomainProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cdp.Thumbprint != nil { - objectMap["thumbprint"] = cdp.Thumbprint - } - if cdp.CertName != nil { - objectMap["certName"] = cdp.CertName - } - return json.Marshal(objectMap) -} - -// CustomDomainResource custom domain resource payload. -type CustomDomainResource struct { - autorest.Response `json:"-"` - // Properties - Properties of the custom domain resource. - Properties *CustomDomainProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for CustomDomainResource. -func (cdr CustomDomainResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cdr.Properties != nil { - objectMap["properties"] = cdr.Properties - } - if cdr.SystemData != nil { - objectMap["systemData"] = cdr.SystemData - } - return json.Marshal(objectMap) -} - -// CustomDomainResourceCollection collection compose of a custom domain resources list and a possible link -// for next page. -type CustomDomainResourceCollection struct { - autorest.Response `json:"-"` - // Value - The custom domain resources list. - Value *[]CustomDomainResource `json:"value,omitempty"` - // NextLink - The link to next page of custom domain list. - NextLink *string `json:"nextLink,omitempty"` -} - -// CustomDomainResourceCollectionIterator provides access to a complete listing of CustomDomainResource -// values. -type CustomDomainResourceCollectionIterator struct { - i int - page CustomDomainResourceCollectionPage -} - -// NextWithContext 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 *CustomDomainResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *CustomDomainResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter CustomDomainResourceCollectionIterator) 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 CustomDomainResourceCollectionIterator) Response() CustomDomainResourceCollection { - 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 CustomDomainResourceCollectionIterator) Value() CustomDomainResource { - if !iter.page.NotDone() { - return CustomDomainResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the CustomDomainResourceCollectionIterator type. -func NewCustomDomainResourceCollectionIterator(page CustomDomainResourceCollectionPage) CustomDomainResourceCollectionIterator { - return CustomDomainResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (cdrc CustomDomainResourceCollection) IsEmpty() bool { - return cdrc.Value == nil || len(*cdrc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (cdrc CustomDomainResourceCollection) hasNextLink() bool { - return cdrc.NextLink != nil && len(*cdrc.NextLink) != 0 -} - -// customDomainResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (cdrc CustomDomainResourceCollection) customDomainResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !cdrc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(cdrc.NextLink))) -} - -// CustomDomainResourceCollectionPage contains a page of CustomDomainResource values. -type CustomDomainResourceCollectionPage struct { - fn func(context.Context, CustomDomainResourceCollection) (CustomDomainResourceCollection, error) - cdrc CustomDomainResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *CustomDomainResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomDomainResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.cdrc) - if err != nil { - return err - } - page.cdrc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *CustomDomainResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page CustomDomainResourceCollectionPage) NotDone() bool { - return !page.cdrc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page CustomDomainResourceCollectionPage) Response() CustomDomainResourceCollection { - return page.cdrc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page CustomDomainResourceCollectionPage) Values() []CustomDomainResource { - if page.cdrc.IsEmpty() { - return nil - } - return *page.cdrc.Value -} - -// Creates a new instance of the CustomDomainResourceCollectionPage type. -func NewCustomDomainResourceCollectionPage(cur CustomDomainResourceCollection, getNextPage func(context.Context, CustomDomainResourceCollection) (CustomDomainResourceCollection, error)) CustomDomainResourceCollectionPage { - return CustomDomainResourceCollectionPage{ - fn: getNextPage, - cdrc: cur, - } -} - -// CustomDomainsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type CustomDomainsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(CustomDomainsClient) (CustomDomainResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *CustomDomainsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for CustomDomainsCreateOrUpdateFuture.Result. -func (future *CustomDomainsCreateOrUpdateFuture) result(client CustomDomainsClient) (cdr CustomDomainResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cdr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.CustomDomainsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cdr.Response.Response, err = future.GetResult(sender); err == nil && cdr.Response.Response.StatusCode != http.StatusNoContent { - cdr, err = client.CreateOrUpdateResponder(cdr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsCreateOrUpdateFuture", "Result", cdr.Response.Response, "Failure responding to request") - } - } - return -} - -// CustomDomainsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type CustomDomainsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(CustomDomainsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *CustomDomainsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for CustomDomainsDeleteFuture.Result. -func (future *CustomDomainsDeleteFuture) result(client CustomDomainsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.CustomDomainsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// CustomDomainsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type CustomDomainsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(CustomDomainsClient) (CustomDomainResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *CustomDomainsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for CustomDomainsUpdateFuture.Result. -func (future *CustomDomainsUpdateFuture) result(client CustomDomainsClient) (cdr CustomDomainResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cdr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.CustomDomainsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cdr.Response.Response, err = future.GetResult(sender); err == nil && cdr.Response.Response.StatusCode != http.StatusNoContent { - cdr, err = client.UpdateResponder(cdr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.CustomDomainsUpdateFuture", "Result", cdr.Response.Response, "Failure responding to request") - } - } - return -} - -// CustomDomainValidatePayload custom domain validate payload. -type CustomDomainValidatePayload struct { - // Name - Name to be validated - Name *string `json:"name,omitempty"` -} - -// CustomDomainValidateResult validation result for custom domain. -type CustomDomainValidateResult struct { - autorest.Response `json:"-"` - // IsValid - Indicates if domain name is valid. - IsValid *bool `json:"isValid,omitempty"` - // Message - Message of why domain name is invalid. - Message *string `json:"message,omitempty"` -} - -// BasicCustomPersistentDiskProperties custom persistent disk resource payload. -type BasicCustomPersistentDiskProperties interface { - AsAzureFileVolume() (*AzureFileVolume, bool) - AsCustomPersistentDiskProperties() (*CustomPersistentDiskProperties, bool) -} - -// CustomPersistentDiskProperties custom persistent disk resource payload. -type CustomPersistentDiskProperties struct { - // MountPath - The mount path of the persistent disk. - MountPath *string `json:"mountPath,omitempty"` - // ReadOnly - Indicates whether the persistent disk is a readOnly one. - ReadOnly *bool `json:"readOnly,omitempty"` - // MountOptions - These are the mount options for a persistent disk. - MountOptions *[]string `json:"mountOptions,omitempty"` - // Type - Possible values include: 'TypeCustomPersistentDiskProperties', 'TypeAzureFileVolume' - Type Type `json:"type,omitempty"` -} - -func unmarshalBasicCustomPersistentDiskProperties(body []byte) (BasicCustomPersistentDiskProperties, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["type"] { - case string(TypeAzureFileVolume): - var afv AzureFileVolume - err := json.Unmarshal(body, &afv) - return afv, err - default: - var cpdp CustomPersistentDiskProperties - err := json.Unmarshal(body, &cpdp) - return cpdp, err - } -} -func unmarshalBasicCustomPersistentDiskPropertiesArray(body []byte) ([]BasicCustomPersistentDiskProperties, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - cpdpArray := make([]BasicCustomPersistentDiskProperties, len(rawMessages)) - - for index, rawMessage := range rawMessages { - cpdp, err := unmarshalBasicCustomPersistentDiskProperties(*rawMessage) - if err != nil { - return nil, err - } - cpdpArray[index] = cpdp - } - return cpdpArray, nil -} - -// MarshalJSON is the custom marshaler for CustomPersistentDiskProperties. -func (cpdp CustomPersistentDiskProperties) MarshalJSON() ([]byte, error) { - cpdp.Type = TypeCustomPersistentDiskProperties - objectMap := make(map[string]interface{}) - if cpdp.MountPath != nil { - objectMap["mountPath"] = cpdp.MountPath - } - if cpdp.ReadOnly != nil { - objectMap["readOnly"] = cpdp.ReadOnly - } - if cpdp.MountOptions != nil { - objectMap["mountOptions"] = cpdp.MountOptions - } - if cpdp.Type != "" { - objectMap["type"] = cpdp.Type - } - return json.Marshal(objectMap) -} - -// AsAzureFileVolume is the BasicCustomPersistentDiskProperties implementation for CustomPersistentDiskProperties. -func (cpdp CustomPersistentDiskProperties) AsAzureFileVolume() (*AzureFileVolume, bool) { - return nil, false -} - -// AsCustomPersistentDiskProperties is the BasicCustomPersistentDiskProperties implementation for CustomPersistentDiskProperties. -func (cpdp CustomPersistentDiskProperties) AsCustomPersistentDiskProperties() (*CustomPersistentDiskProperties, bool) { - return &cpdp, true -} - -// AsBasicCustomPersistentDiskProperties is the BasicCustomPersistentDiskProperties implementation for CustomPersistentDiskProperties. -func (cpdp CustomPersistentDiskProperties) AsBasicCustomPersistentDiskProperties() (BasicCustomPersistentDiskProperties, bool) { - return &cpdp, true -} - -// CustomPersistentDiskResource custom persistent disk resource payload. -type CustomPersistentDiskResource struct { - // CustomPersistentDiskProperties - Properties of the custom persistent disk resource payload. - CustomPersistentDiskProperties BasicCustomPersistentDiskProperties `json:"customPersistentDiskProperties,omitempty"` - // StorageID - The resource id of Azure Spring Cloud Storage resource. - StorageID *string `json:"storageId,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for CustomPersistentDiskResource struct. -func (cpdr *CustomPersistentDiskResource) 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 "customPersistentDiskProperties": - if v != nil { - customPersistentDiskProperties, err := unmarshalBasicCustomPersistentDiskProperties(*v) - if err != nil { - return err - } - cpdr.CustomPersistentDiskProperties = customPersistentDiskProperties - } - case "storageId": - if v != nil { - var storageID string - err = json.Unmarshal(*v, &storageID) - if err != nil { - return err - } - cpdr.StorageID = &storageID - } - } - } - - return nil -} - -// DeploymentInstance deployment instance payload -type DeploymentInstance struct { - // Name - READ-ONLY; Name of the deployment instance - Name *string `json:"name,omitempty"` - // Status - READ-ONLY; Status of the deployment instance - Status *string `json:"status,omitempty"` - // Reason - READ-ONLY; Failed reason of the deployment instance - Reason *string `json:"reason,omitempty"` - // DiscoveryStatus - READ-ONLY; Discovery status of the deployment instance - DiscoveryStatus *string `json:"discoveryStatus,omitempty"` - // StartTime - READ-ONLY; Start time of the deployment instance - StartTime *string `json:"startTime,omitempty"` - // Zone - READ-ONLY; Availability zone information of the deployment instance - Zone *string `json:"zone,omitempty"` -} - -// MarshalJSON is the custom marshaler for DeploymentInstance. -func (di DeploymentInstance) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// DeploymentResource deployment resource payload -type DeploymentResource struct { - autorest.Response `json:"-"` - // Properties - Properties of the Deployment resource - Properties *DeploymentResourceProperties `json:"properties,omitempty"` - // Sku - Sku of the Deployment resource - Sku *Sku `json:"sku,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for DeploymentResource. -func (dr DeploymentResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dr.Properties != nil { - objectMap["properties"] = dr.Properties - } - if dr.Sku != nil { - objectMap["sku"] = dr.Sku - } - if dr.SystemData != nil { - objectMap["systemData"] = dr.SystemData - } - return json.Marshal(objectMap) -} - -// DeploymentResourceCollection object that includes an array of App resources and a possible link for next -// set -type DeploymentResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of Deployment resources - Value *[]DeploymentResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// DeploymentResourceCollectionIterator provides access to a complete listing of DeploymentResource values. -type DeploymentResourceCollectionIterator struct { - i int - page DeploymentResourceCollectionPage -} - -// NextWithContext 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 *DeploymentResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *DeploymentResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter DeploymentResourceCollectionIterator) 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 DeploymentResourceCollectionIterator) Response() DeploymentResourceCollection { - 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 DeploymentResourceCollectionIterator) Value() DeploymentResource { - if !iter.page.NotDone() { - return DeploymentResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the DeploymentResourceCollectionIterator type. -func NewDeploymentResourceCollectionIterator(page DeploymentResourceCollectionPage) DeploymentResourceCollectionIterator { - return DeploymentResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (drc DeploymentResourceCollection) IsEmpty() bool { - return drc.Value == nil || len(*drc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (drc DeploymentResourceCollection) hasNextLink() bool { - return drc.NextLink != nil && len(*drc.NextLink) != 0 -} - -// deploymentResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (drc DeploymentResourceCollection) deploymentResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !drc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(drc.NextLink))) -} - -// DeploymentResourceCollectionPage contains a page of DeploymentResource values. -type DeploymentResourceCollectionPage struct { - fn func(context.Context, DeploymentResourceCollection) (DeploymentResourceCollection, error) - drc DeploymentResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DeploymentResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.drc) - if err != nil { - return err - } - page.drc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DeploymentResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DeploymentResourceCollectionPage) NotDone() bool { - return !page.drc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DeploymentResourceCollectionPage) Response() DeploymentResourceCollection { - return page.drc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DeploymentResourceCollectionPage) Values() []DeploymentResource { - if page.drc.IsEmpty() { - return nil - } - return *page.drc.Value -} - -// Creates a new instance of the DeploymentResourceCollectionPage type. -func NewDeploymentResourceCollectionPage(cur DeploymentResourceCollection, getNextPage func(context.Context, DeploymentResourceCollection) (DeploymentResourceCollection, error)) DeploymentResourceCollectionPage { - return DeploymentResourceCollectionPage{ - fn: getNextPage, - drc: cur, - } -} - -// DeploymentResourceProperties deployment resource properties payload -type DeploymentResourceProperties struct { - // Source - Uploaded source information of the deployment. - Source BasicUserSourceInfo `json:"source,omitempty"` - // DeploymentSettings - Deployment settings of the Deployment - DeploymentSettings *DeploymentSettings `json:"deploymentSettings,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the Deployment. Possible values include: 'DeploymentResourceProvisioningStateCreating', 'DeploymentResourceProvisioningStateUpdating', 'DeploymentResourceProvisioningStateSucceeded', 'DeploymentResourceProvisioningStateFailed' - ProvisioningState DeploymentResourceProvisioningState `json:"provisioningState,omitempty"` - // Status - READ-ONLY; Status of the Deployment. Possible values include: 'DeploymentResourceStatusStopped', 'DeploymentResourceStatusRunning' - Status DeploymentResourceStatus `json:"status,omitempty"` - // Active - Indicates whether the Deployment is active - Active *bool `json:"active,omitempty"` - // Instances - READ-ONLY; Collection of instances belong to the Deployment - Instances *[]DeploymentInstance `json:"instances,omitempty"` -} - -// MarshalJSON is the custom marshaler for DeploymentResourceProperties. -func (drp DeploymentResourceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - objectMap["source"] = drp.Source - if drp.DeploymentSettings != nil { - objectMap["deploymentSettings"] = drp.DeploymentSettings - } - if drp.Active != nil { - objectMap["active"] = drp.Active - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for DeploymentResourceProperties struct. -func (drp *DeploymentResourceProperties) 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 "source": - if v != nil { - source, err := unmarshalBasicUserSourceInfo(*v) - if err != nil { - return err - } - drp.Source = source - } - case "deploymentSettings": - if v != nil { - var deploymentSettings DeploymentSettings - err = json.Unmarshal(*v, &deploymentSettings) - if err != nil { - return err - } - drp.DeploymentSettings = &deploymentSettings - } - case "provisioningState": - if v != nil { - var provisioningState DeploymentResourceProvisioningState - err = json.Unmarshal(*v, &provisioningState) - if err != nil { - return err - } - drp.ProvisioningState = provisioningState - } - case "status": - if v != nil { - var status DeploymentResourceStatus - err = json.Unmarshal(*v, &status) - if err != nil { - return err - } - drp.Status = status - } - case "active": - if v != nil { - var active bool - err = json.Unmarshal(*v, &active) - if err != nil { - return err - } - drp.Active = &active - } - case "instances": - if v != nil { - var instances []DeploymentInstance - err = json.Unmarshal(*v, &instances) - if err != nil { - return err - } - drp.Instances = &instances - } - } - } - - return nil -} - -// DeploymentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DeploymentsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DeploymentsClient) (DeploymentResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeploymentsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeploymentsCreateOrUpdateFuture.Result. -func (future *DeploymentsCreateOrUpdateFuture) result(client DeploymentsClient) (dr DeploymentResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dr.Response.Response, err = future.GetResult(sender); err == nil && dr.Response.Response.StatusCode != http.StatusNoContent { - dr, err = client.CreateOrUpdateResponder(dr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsCreateOrUpdateFuture", "Result", dr.Response.Response, "Failure responding to request") - } - } - return -} - -// DeploymentsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DeploymentsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DeploymentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeploymentsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeploymentsDeleteFuture.Result. -func (future *DeploymentsDeleteFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// DeploymentSettings deployment settings payload -type DeploymentSettings struct { - // ResourceRequests - The requested resource quantity for required CPU and Memory. It is recommended that using this field to represent the required CPU and Memory, the old field cpu and memoryInGB will be deprecated later. - ResourceRequests *ResourceRequests `json:"resourceRequests,omitempty"` - // EnvironmentVariables - Collection of environment variables - EnvironmentVariables map[string]*string `json:"environmentVariables"` - // AddonConfigs - Collection of addons - AddonConfigs map[string]map[string]interface{} `json:"addonConfigs"` - ContainerProbeSettings *ContainerProbeSettings `json:"containerProbeSettings,omitempty"` -} - -// MarshalJSON is the custom marshaler for DeploymentSettings. -func (ds DeploymentSettings) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ds.ResourceRequests != nil { - objectMap["resourceRequests"] = ds.ResourceRequests - } - if ds.EnvironmentVariables != nil { - objectMap["environmentVariables"] = ds.EnvironmentVariables - } - if ds.AddonConfigs != nil { - objectMap["addonConfigs"] = ds.AddonConfigs - } - if ds.ContainerProbeSettings != nil { - objectMap["containerProbeSettings"] = ds.ContainerProbeSettings - } - return json.Marshal(objectMap) -} - -// DeploymentsGenerateHeapDumpFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DeploymentsGenerateHeapDumpFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DeploymentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeploymentsGenerateHeapDumpFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeploymentsGenerateHeapDumpFuture.Result. -func (future *DeploymentsGenerateHeapDumpFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsGenerateHeapDumpFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsGenerateHeapDumpFuture") - return - } - ar.Response = future.Response() - return -} - -// DeploymentsGenerateThreadDumpFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DeploymentsGenerateThreadDumpFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DeploymentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeploymentsGenerateThreadDumpFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeploymentsGenerateThreadDumpFuture.Result. -func (future *DeploymentsGenerateThreadDumpFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsGenerateThreadDumpFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsGenerateThreadDumpFuture") - return - } - ar.Response = future.Response() - return -} - -// DeploymentsRestartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DeploymentsRestartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DeploymentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeploymentsRestartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeploymentsRestartFuture.Result. -func (future *DeploymentsRestartFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsRestartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsRestartFuture") - return - } - ar.Response = future.Response() - return -} - -// DeploymentsStartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DeploymentsStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DeploymentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeploymentsStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeploymentsStartFuture.Result. -func (future *DeploymentsStartFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsStartFuture") - return - } - ar.Response = future.Response() - return -} - -// DeploymentsStartJFRFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DeploymentsStartJFRFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DeploymentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeploymentsStartJFRFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeploymentsStartJFRFuture.Result. -func (future *DeploymentsStartJFRFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsStartJFRFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsStartJFRFuture") - return - } - ar.Response = future.Response() - return -} - -// DeploymentsStopFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DeploymentsStopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DeploymentsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeploymentsStopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeploymentsStopFuture.Result. -func (future *DeploymentsStopFuture) result(client DeploymentsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsStopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsStopFuture") - return - } - ar.Response = future.Response() - return -} - -// DeploymentsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DeploymentsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DeploymentsClient) (DeploymentResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeploymentsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeploymentsUpdateFuture.Result. -func (future *DeploymentsUpdateFuture) result(client DeploymentsClient) (dr DeploymentResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.DeploymentsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dr.Response.Response, err = future.GetResult(sender); err == nil && dr.Response.Response.StatusCode != http.StatusNoContent { - dr, err = client.UpdateResponder(dr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.DeploymentsUpdateFuture", "Result", dr.Response.Response, "Failure responding to request") - } - } - return -} - -// DiagnosticParameters diagnostic parameters of diagnostic operations -type DiagnosticParameters struct { - // AppInstance - App instance name - AppInstance *string `json:"appInstance,omitempty"` - // FilePath - Your target file path in your own BYOS - FilePath *string `json:"filePath,omitempty"` - // Duration - Duration of your JFR. 1 min can be represented by 1m or 60s. - Duration *string `json:"duration,omitempty"` -} - -// Error the error code compose of code and message. -type Error struct { - // Code - The code of error. - Code *string `json:"code,omitempty"` - // Message - The message of error. - Message *string `json:"message,omitempty"` -} - -// GatewayAPIMetadataProperties API metadata property for Spring Cloud Gateway -type GatewayAPIMetadataProperties struct { - // Title - Title describing the context of the APIs available on the Gateway instance (default: `Spring Cloud Gateway for K8S`) - Title *string `json:"title,omitempty"` - // Description - Detailed description of the APIs available on the Gateway instance (default: `Generated OpenAPI 3 document that describes the API routes configured.`) - Description *string `json:"description,omitempty"` - // Documentation - Location of additional documentation for the APIs available on the Gateway instance - Documentation *string `json:"documentation,omitempty"` - // Version - Version of APIs available on this Gateway instance (default: `unspecified`). - Version *string `json:"version,omitempty"` - // ServerURL - Base URL that API consumers will use to access APIs on the Gateway instance. - ServerURL *string `json:"serverUrl,omitempty"` -} - -// GatewayAPIRoute API route config of the Spring Cloud Gateway -type GatewayAPIRoute struct { - // Title - A title, will be applied to methods in the generated OpenAPI documentation. - Title *string `json:"title,omitempty"` - // Description - A description, will be applied to methods in the generated OpenAPI documentation. - Description *string `json:"description,omitempty"` - // URI - Full uri, will override `appName`. - URI *string `json:"uri,omitempty"` - // SsoEnabled - Enable sso validation. - SsoEnabled *bool `json:"ssoEnabled,omitempty"` - // TokenRelay - Pass currently-authenticated user's identity token to application service, default is 'false' - TokenRelay *bool `json:"tokenRelay,omitempty"` - // Predicates - A number of conditions to evaluate a route for each request. Each predicate may be evaluated against request headers and parameter values. All of the predicates associated with a route must evaluate to true for the route to be matched to the request. - Predicates *[]string `json:"predicates,omitempty"` - // Filters - To modify the request before sending it to the target endpoint, or the received response. - Filters *[]string `json:"filters,omitempty"` - // Order - Route processing order. - Order *int32 `json:"order,omitempty"` - // Tags - Classification tags, will be applied to methods in the generated OpenAPI documentation. - Tags *[]string `json:"tags,omitempty"` -} - -// GatewayCorsProperties cross-Origin Resource Sharing property -type GatewayCorsProperties struct { - // AllowedOrigins - Allowed origins to make cross-site requests. The special value `*` allows all domains. - AllowedOrigins *[]string `json:"allowedOrigins,omitempty"` - // AllowedMethods - Allowed HTTP methods on cross-site requests. The special value `*` allows all methods. If not set, `GET` and `HEAD` are allowed by default. - AllowedMethods *[]string `json:"allowedMethods,omitempty"` - // AllowedHeaders - Allowed headers in cross-site requests. The special value `*` allows actual requests to send any header. - AllowedHeaders *[]string `json:"allowedHeaders,omitempty"` - // MaxAge - How long, in seconds, the response from a pre-flight request can be cached by clients. - MaxAge *int32 `json:"maxAge,omitempty"` - // AllowCredentials - Whether user credentials are supported on cross-site requests. Valid values: `true`, `false`. - AllowCredentials *bool `json:"allowCredentials,omitempty"` - // ExposedHeaders - HTTP response headers to expose for cross-site requests. - ExposedHeaders *[]string `json:"exposedHeaders,omitempty"` -} - -// GatewayCustomDomainProperties the properties of custom domain for Spring Cloud Gateway -type GatewayCustomDomainProperties struct { - // Thumbprint - The thumbprint of bound certificate. - Thumbprint *string `json:"thumbprint,omitempty"` -} - -// GatewayCustomDomainResource custom domain of the Spring Cloud Gateway -type GatewayCustomDomainResource struct { - autorest.Response `json:"-"` - Properties *GatewayCustomDomainProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayCustomDomainResource. -func (gcdr GatewayCustomDomainResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if gcdr.Properties != nil { - objectMap["properties"] = gcdr.Properties - } - if gcdr.SystemData != nil { - objectMap["systemData"] = gcdr.SystemData - } - return json.Marshal(objectMap) -} - -// GatewayCustomDomainResourceCollection object that includes an array of Spring Cloud Gateway custom -// domain resources and a possible link for next set -type GatewayCustomDomainResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of Spring Cloud Gateway custom domain resources - Value *[]GatewayCustomDomainResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// GatewayCustomDomainResourceCollectionIterator provides access to a complete listing of -// GatewayCustomDomainResource values. -type GatewayCustomDomainResourceCollectionIterator struct { - i int - page GatewayCustomDomainResourceCollectionPage -} - -// NextWithContext 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 *GatewayCustomDomainResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *GatewayCustomDomainResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter GatewayCustomDomainResourceCollectionIterator) 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 GatewayCustomDomainResourceCollectionIterator) Response() GatewayCustomDomainResourceCollection { - 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 GatewayCustomDomainResourceCollectionIterator) Value() GatewayCustomDomainResource { - if !iter.page.NotDone() { - return GatewayCustomDomainResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the GatewayCustomDomainResourceCollectionIterator type. -func NewGatewayCustomDomainResourceCollectionIterator(page GatewayCustomDomainResourceCollectionPage) GatewayCustomDomainResourceCollectionIterator { - return GatewayCustomDomainResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (gcdrc GatewayCustomDomainResourceCollection) IsEmpty() bool { - return gcdrc.Value == nil || len(*gcdrc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (gcdrc GatewayCustomDomainResourceCollection) hasNextLink() bool { - return gcdrc.NextLink != nil && len(*gcdrc.NextLink) != 0 -} - -// gatewayCustomDomainResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (gcdrc GatewayCustomDomainResourceCollection) gatewayCustomDomainResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !gcdrc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(gcdrc.NextLink))) -} - -// GatewayCustomDomainResourceCollectionPage contains a page of GatewayCustomDomainResource values. -type GatewayCustomDomainResourceCollectionPage struct { - fn func(context.Context, GatewayCustomDomainResourceCollection) (GatewayCustomDomainResourceCollection, error) - gcdrc GatewayCustomDomainResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *GatewayCustomDomainResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayCustomDomainResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.gcdrc) - if err != nil { - return err - } - page.gcdrc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *GatewayCustomDomainResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page GatewayCustomDomainResourceCollectionPage) NotDone() bool { - return !page.gcdrc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page GatewayCustomDomainResourceCollectionPage) Response() GatewayCustomDomainResourceCollection { - return page.gcdrc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page GatewayCustomDomainResourceCollectionPage) Values() []GatewayCustomDomainResource { - if page.gcdrc.IsEmpty() { - return nil - } - return *page.gcdrc.Value -} - -// Creates a new instance of the GatewayCustomDomainResourceCollectionPage type. -func NewGatewayCustomDomainResourceCollectionPage(cur GatewayCustomDomainResourceCollection, getNextPage func(context.Context, GatewayCustomDomainResourceCollection) (GatewayCustomDomainResourceCollection, error)) GatewayCustomDomainResourceCollectionPage { - return GatewayCustomDomainResourceCollectionPage{ - fn: getNextPage, - gcdrc: cur, - } -} - -// GatewayCustomDomainsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type GatewayCustomDomainsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GatewayCustomDomainsClient) (GatewayCustomDomainResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GatewayCustomDomainsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GatewayCustomDomainsCreateOrUpdateFuture.Result. -func (future *GatewayCustomDomainsCreateOrUpdateFuture) result(client GatewayCustomDomainsClient) (gcdr GatewayCustomDomainResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - gcdr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.GatewayCustomDomainsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if gcdr.Response.Response, err = future.GetResult(sender); err == nil && gcdr.Response.Response.StatusCode != http.StatusNoContent { - gcdr, err = client.CreateOrUpdateResponder(gcdr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsCreateOrUpdateFuture", "Result", gcdr.Response.Response, "Failure responding to request") - } - } - return -} - -// GatewayCustomDomainsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type GatewayCustomDomainsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GatewayCustomDomainsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GatewayCustomDomainsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GatewayCustomDomainsDeleteFuture.Result. -func (future *GatewayCustomDomainsDeleteFuture) result(client GatewayCustomDomainsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayCustomDomainsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.GatewayCustomDomainsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// GatewayInstance collection of instances belong to the Spring Cloud Gateway -type GatewayInstance struct { - // Name - READ-ONLY; Name of the Spring Cloud Gateway instance - Name *string `json:"name,omitempty"` - // Status - READ-ONLY; Status of the Spring Cloud Gateway instance - Status *string `json:"status,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayInstance. -func (gi GatewayInstance) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GatewayOperatorProperties properties of the Spring Cloud Gateway Operator. -type GatewayOperatorProperties struct { - // ResourceRequests - The requested resource quantity for required CPU and Memory. - ResourceRequests *GatewayOperatorResourceRequests `json:"resourceRequests,omitempty"` - // Instances - READ-ONLY; Collection of instances belong to Spring Cloud Gateway operator. - Instances *[]GatewayInstance `json:"instances,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayOperatorProperties. -func (gop GatewayOperatorProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if gop.ResourceRequests != nil { - objectMap["resourceRequests"] = gop.ResourceRequests - } - return json.Marshal(objectMap) -} - -// GatewayOperatorResourceRequests properties of the Spring Cloud Gateway Operator. -type GatewayOperatorResourceRequests struct { - // CPU - READ-ONLY; Cpu allocated to each Spring Cloud Gateway Operator instance. - CPU *string `json:"cpu,omitempty"` - // Memory - READ-ONLY; Memory allocated to each Spring Cloud Gateway Operator instance. - Memory *string `json:"memory,omitempty"` - // InstanceCount - READ-ONLY; Instance count of the Spring Cloud Gateway Operator. - InstanceCount *int32 `json:"instanceCount,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayOperatorResourceRequests. -func (gorr GatewayOperatorResourceRequests) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GatewayProperties spring Cloud Gateway properties payload -type GatewayProperties struct { - // ProvisioningState - READ-ONLY; State of the Spring Cloud Gateway. Possible values include: 'GatewayProvisioningStateCreating', 'GatewayProvisioningStateUpdating', 'GatewayProvisioningStateSucceeded', 'GatewayProvisioningStateFailed', 'GatewayProvisioningStateDeleting' - ProvisioningState GatewayProvisioningState `json:"provisioningState,omitempty"` - // Public - Indicates whether the Spring Cloud Gateway exposes endpoint. - Public *bool `json:"public,omitempty"` - // URL - READ-ONLY; URL of the Spring Cloud Gateway, exposed when 'public' is true. - URL *string `json:"url,omitempty"` - // HTTPSOnly - Indicate if only https is allowed. - HTTPSOnly *bool `json:"httpsOnly,omitempty"` - SsoProperties *SsoProperties `json:"ssoProperties,omitempty"` - APIMetadataProperties *GatewayAPIMetadataProperties `json:"apiMetadataProperties,omitempty"` - CorsProperties *GatewayCorsProperties `json:"corsProperties,omitempty"` - // ResourceRequests - The requested resource quantity for required CPU and Memory. - ResourceRequests *GatewayResourceRequests `json:"resourceRequests,omitempty"` - // Instances - READ-ONLY; Collection of instances belong to Spring Cloud Gateway. - Instances *[]GatewayInstance `json:"instances,omitempty"` - // OperatorProperties - READ-ONLY - OperatorProperties *GatewayOperatorProperties `json:"operatorProperties,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayProperties. -func (gp GatewayProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if gp.Public != nil { - objectMap["public"] = gp.Public - } - if gp.HTTPSOnly != nil { - objectMap["httpsOnly"] = gp.HTTPSOnly - } - if gp.SsoProperties != nil { - objectMap["ssoProperties"] = gp.SsoProperties - } - if gp.APIMetadataProperties != nil { - objectMap["apiMetadataProperties"] = gp.APIMetadataProperties - } - if gp.CorsProperties != nil { - objectMap["corsProperties"] = gp.CorsProperties - } - if gp.ResourceRequests != nil { - objectMap["resourceRequests"] = gp.ResourceRequests - } - return json.Marshal(objectMap) -} - -// GatewayResource spring Cloud Gateway resource -type GatewayResource struct { - autorest.Response `json:"-"` - Properties *GatewayProperties `json:"properties,omitempty"` - // Sku - Sku of the Spring Cloud Gateway resource - Sku *Sku `json:"sku,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayResource. -func (gr GatewayResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if gr.Properties != nil { - objectMap["properties"] = gr.Properties - } - if gr.Sku != nil { - objectMap["sku"] = gr.Sku - } - if gr.SystemData != nil { - objectMap["systemData"] = gr.SystemData - } - return json.Marshal(objectMap) -} - -// GatewayResourceCollection object that includes an array of gateway resources and a possible link for -// next set -type GatewayResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of gateway resources - Value *[]GatewayResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// GatewayResourceCollectionIterator provides access to a complete listing of GatewayResource values. -type GatewayResourceCollectionIterator struct { - i int - page GatewayResourceCollectionPage -} - -// NextWithContext 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 *GatewayResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *GatewayResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter GatewayResourceCollectionIterator) 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 GatewayResourceCollectionIterator) Response() GatewayResourceCollection { - 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 GatewayResourceCollectionIterator) Value() GatewayResource { - if !iter.page.NotDone() { - return GatewayResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the GatewayResourceCollectionIterator type. -func NewGatewayResourceCollectionIterator(page GatewayResourceCollectionPage) GatewayResourceCollectionIterator { - return GatewayResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (grc GatewayResourceCollection) IsEmpty() bool { - return grc.Value == nil || len(*grc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (grc GatewayResourceCollection) hasNextLink() bool { - return grc.NextLink != nil && len(*grc.NextLink) != 0 -} - -// gatewayResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (grc GatewayResourceCollection) gatewayResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !grc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(grc.NextLink))) -} - -// GatewayResourceCollectionPage contains a page of GatewayResource values. -type GatewayResourceCollectionPage struct { - fn func(context.Context, GatewayResourceCollection) (GatewayResourceCollection, error) - grc GatewayResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *GatewayResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.grc) - if err != nil { - return err - } - page.grc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *GatewayResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page GatewayResourceCollectionPage) NotDone() bool { - return !page.grc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page GatewayResourceCollectionPage) Response() GatewayResourceCollection { - return page.grc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page GatewayResourceCollectionPage) Values() []GatewayResource { - if page.grc.IsEmpty() { - return nil - } - return *page.grc.Value -} - -// Creates a new instance of the GatewayResourceCollectionPage type. -func NewGatewayResourceCollectionPage(cur GatewayResourceCollection, getNextPage func(context.Context, GatewayResourceCollection) (GatewayResourceCollection, error)) GatewayResourceCollectionPage { - return GatewayResourceCollectionPage{ - fn: getNextPage, - grc: cur, - } -} - -// GatewayResourceRequests resource request payload of Spring Cloud Gateway. -type GatewayResourceRequests struct { - // CPU - Cpu allocated to each Spring Cloud Gateway instance. - CPU *string `json:"cpu,omitempty"` - // Memory - Memory allocated to each Spring Cloud Gateway instance. - Memory *string `json:"memory,omitempty"` -} - -// GatewayRouteConfigProperties API route config of the Spring Cloud Gateway -type GatewayRouteConfigProperties struct { - // ProvisioningState - READ-ONLY; State of the Spring Cloud Gateway route config. Possible values include: 'GatewayProvisioningStateCreating', 'GatewayProvisioningStateUpdating', 'GatewayProvisioningStateSucceeded', 'GatewayProvisioningStateFailed', 'GatewayProvisioningStateDeleting' - ProvisioningState GatewayProvisioningState `json:"provisioningState,omitempty"` - // AppResourceID - The resource Id of the Azure Spring Cloud app, required unless route defines `uri`. - AppResourceID *string `json:"appResourceId,omitempty"` - // Routes - Array of API routes, each route contains properties such as `title`, `uri`, `ssoEnabled`, `predicates`, `filters`. - Routes *[]GatewayAPIRoute `json:"routes,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayRouteConfigProperties. -func (grcp GatewayRouteConfigProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if grcp.AppResourceID != nil { - objectMap["appResourceId"] = grcp.AppResourceID - } - if grcp.Routes != nil { - objectMap["routes"] = grcp.Routes - } - return json.Marshal(objectMap) -} - -// GatewayRouteConfigResource spring Cloud Gateway route config resource -type GatewayRouteConfigResource struct { - autorest.Response `json:"-"` - Properties *GatewayRouteConfigProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayRouteConfigResource. -func (grcr GatewayRouteConfigResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if grcr.Properties != nil { - objectMap["properties"] = grcr.Properties - } - if grcr.SystemData != nil { - objectMap["systemData"] = grcr.SystemData - } - return json.Marshal(objectMap) -} - -// GatewayRouteConfigResourceCollection object that includes an array of Spring Cloud Gateway route config -// resources and a possible link for next set -type GatewayRouteConfigResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of Spring Cloud Gateway route config resources - Value *[]GatewayRouteConfigResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// GatewayRouteConfigResourceCollectionIterator provides access to a complete listing of -// GatewayRouteConfigResource values. -type GatewayRouteConfigResourceCollectionIterator struct { - i int - page GatewayRouteConfigResourceCollectionPage -} - -// NextWithContext 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 *GatewayRouteConfigResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *GatewayRouteConfigResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter GatewayRouteConfigResourceCollectionIterator) 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 GatewayRouteConfigResourceCollectionIterator) Response() GatewayRouteConfigResourceCollection { - 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 GatewayRouteConfigResourceCollectionIterator) Value() GatewayRouteConfigResource { - if !iter.page.NotDone() { - return GatewayRouteConfigResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the GatewayRouteConfigResourceCollectionIterator type. -func NewGatewayRouteConfigResourceCollectionIterator(page GatewayRouteConfigResourceCollectionPage) GatewayRouteConfigResourceCollectionIterator { - return GatewayRouteConfigResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (grcrc GatewayRouteConfigResourceCollection) IsEmpty() bool { - return grcrc.Value == nil || len(*grcrc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (grcrc GatewayRouteConfigResourceCollection) hasNextLink() bool { - return grcrc.NextLink != nil && len(*grcrc.NextLink) != 0 -} - -// gatewayRouteConfigResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (grcrc GatewayRouteConfigResourceCollection) gatewayRouteConfigResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !grcrc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(grcrc.NextLink))) -} - -// GatewayRouteConfigResourceCollectionPage contains a page of GatewayRouteConfigResource values. -type GatewayRouteConfigResourceCollectionPage struct { - fn func(context.Context, GatewayRouteConfigResourceCollection) (GatewayRouteConfigResourceCollection, error) - grcrc GatewayRouteConfigResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *GatewayRouteConfigResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GatewayRouteConfigResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.grcrc) - if err != nil { - return err - } - page.grcrc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *GatewayRouteConfigResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page GatewayRouteConfigResourceCollectionPage) NotDone() bool { - return !page.grcrc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page GatewayRouteConfigResourceCollectionPage) Response() GatewayRouteConfigResourceCollection { - return page.grcrc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page GatewayRouteConfigResourceCollectionPage) Values() []GatewayRouteConfigResource { - if page.grcrc.IsEmpty() { - return nil - } - return *page.grcrc.Value -} - -// Creates a new instance of the GatewayRouteConfigResourceCollectionPage type. -func NewGatewayRouteConfigResourceCollectionPage(cur GatewayRouteConfigResourceCollection, getNextPage func(context.Context, GatewayRouteConfigResourceCollection) (GatewayRouteConfigResourceCollection, error)) GatewayRouteConfigResourceCollectionPage { - return GatewayRouteConfigResourceCollectionPage{ - fn: getNextPage, - grcrc: cur, - } -} - -// GatewayRouteConfigsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type GatewayRouteConfigsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GatewayRouteConfigsClient) (GatewayRouteConfigResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GatewayRouteConfigsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GatewayRouteConfigsCreateOrUpdateFuture.Result. -func (future *GatewayRouteConfigsCreateOrUpdateFuture) result(client GatewayRouteConfigsClient) (grcr GatewayRouteConfigResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - grcr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.GatewayRouteConfigsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if grcr.Response.Response, err = future.GetResult(sender); err == nil && grcr.Response.Response.StatusCode != http.StatusNoContent { - grcr, err = client.CreateOrUpdateResponder(grcr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsCreateOrUpdateFuture", "Result", grcr.Response.Response, "Failure responding to request") - } - } - return -} - -// GatewayRouteConfigsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type GatewayRouteConfigsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GatewayRouteConfigsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GatewayRouteConfigsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GatewayRouteConfigsDeleteFuture.Result. -func (future *GatewayRouteConfigsDeleteFuture) result(client GatewayRouteConfigsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewayRouteConfigsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.GatewayRouteConfigsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// GatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type GatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GatewaysClient) (GatewayResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GatewaysCreateOrUpdateFuture.Result. -func (future *GatewaysCreateOrUpdateFuture) result(client GatewaysClient) (gr GatewayResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - gr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.GatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if gr.Response.Response, err = future.GetResult(sender); err == nil && gr.Response.Response.StatusCode != http.StatusNoContent { - gr, err = client.CreateOrUpdateResponder(gr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysCreateOrUpdateFuture", "Result", gr.Response.Response, "Failure responding to request") - } - } - return -} - -// GatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type GatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GatewaysDeleteFuture.Result. -func (future *GatewaysDeleteFuture) result(client GatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.GatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.GatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// GitPatternRepository git repository property payload for config server -type GitPatternRepository struct { - // Name - Name of the repository - Name *string `json:"name,omitempty"` - // Pattern - Collection of pattern of the repository - Pattern *[]string `json:"pattern,omitempty"` - // URI - URI of the repository - URI *string `json:"uri,omitempty"` - // Label - Label of the repository - Label *string `json:"label,omitempty"` - // SearchPaths - Searching path of the repository - SearchPaths *[]string `json:"searchPaths,omitempty"` - // Username - Username of git repository basic auth. - Username *string `json:"username,omitempty"` - // Password - Password of git repository basic auth. - Password *string `json:"password,omitempty"` - // HostKey - Public sshKey of git repository. - HostKey *string `json:"hostKey,omitempty"` - // HostKeyAlgorithm - SshKey algorithm of git repository. - HostKeyAlgorithm *string `json:"hostKeyAlgorithm,omitempty"` - // PrivateKey - Private sshKey algorithm of git repository. - PrivateKey *string `json:"privateKey,omitempty"` - // StrictHostKeyChecking - Strict host key checking or not. - StrictHostKeyChecking *bool `json:"strictHostKeyChecking,omitempty"` -} - -// ImageRegistryCredential credential of the image registry -type ImageRegistryCredential struct { - // Username - The username of the image registry credential - Username *string `json:"username,omitempty"` - // Password - The password of the image registry credential - Password *string `json:"password,omitempty"` -} - -// JarUploadedUserSourceInfo uploaded Jar binary for a deployment -type JarUploadedUserSourceInfo struct { - // RuntimeVersion - Runtime version of the Jar file - RuntimeVersion *string `json:"runtimeVersion,omitempty"` - // JvmOptions - JVM parameter - JvmOptions *string `json:"jvmOptions,omitempty"` - // RelativePath - Relative path of the storage which stores the source - RelativePath *string `json:"relativePath,omitempty"` - // Version - Version of the source - Version *string `json:"version,omitempty"` - // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' - Type TypeBasicUserSourceInfo `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) MarshalJSON() ([]byte, error) { - juusi.Type = TypeBasicUserSourceInfoTypeJar - objectMap := make(map[string]interface{}) - if juusi.RuntimeVersion != nil { - objectMap["runtimeVersion"] = juusi.RuntimeVersion - } - if juusi.JvmOptions != nil { - objectMap["jvmOptions"] = juusi.JvmOptions - } - if juusi.RelativePath != nil { - objectMap["relativePath"] = juusi.RelativePath - } - if juusi.Version != nil { - objectMap["version"] = juusi.Version - } - if juusi.Type != "" { - objectMap["type"] = juusi.Type - } - return json.Marshal(objectMap) -} - -// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { - return &juusi, true -} - -// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { - return &juusi, true -} - -// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { - return nil, false -} - -// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { - return nil, false -} - -// AsUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { - return nil, false -} - -// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for JarUploadedUserSourceInfo. -func (juusi JarUploadedUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { - return &juusi, true -} - -// KeyVaultCertificateProperties properties of certificate imported from key vault. -type KeyVaultCertificateProperties struct { - // VaultURI - The vault uri of user key vault. - VaultURI *string `json:"vaultUri,omitempty"` - // KeyVaultCertName - The certificate name of key vault. - KeyVaultCertName *string `json:"keyVaultCertName,omitempty"` - // CertVersion - The certificate version of key vault. - CertVersion *string `json:"certVersion,omitempty"` - // ExcludePrivateKey - Optional. If set to true, it will not import private key from key vault. - ExcludePrivateKey *bool `json:"excludePrivateKey,omitempty"` - // Thumbprint - READ-ONLY; The thumbprint of certificate. - Thumbprint *string `json:"thumbprint,omitempty"` - // Issuer - READ-ONLY; The issuer of certificate. - Issuer *string `json:"issuer,omitempty"` - // IssuedDate - READ-ONLY; The issue date of certificate. - IssuedDate *string `json:"issuedDate,omitempty"` - // ExpirationDate - READ-ONLY; The expiration date of certificate. - ExpirationDate *string `json:"expirationDate,omitempty"` - // ActivateDate - READ-ONLY; The activate date of certificate. - ActivateDate *string `json:"activateDate,omitempty"` - // SubjectName - READ-ONLY; The subject name of certificate. - SubjectName *string `json:"subjectName,omitempty"` - // DNSNames - READ-ONLY; The domain list of certificate. - DNSNames *[]string `json:"dnsNames,omitempty"` - // Type - Possible values include: 'TypeBasicCertificatePropertiesTypeCertificateProperties', 'TypeBasicCertificatePropertiesTypeKeyVaultCertificate', 'TypeBasicCertificatePropertiesTypeContentCertificate' - Type TypeBasicCertificateProperties `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for KeyVaultCertificateProperties. -func (kvcp KeyVaultCertificateProperties) MarshalJSON() ([]byte, error) { - kvcp.Type = TypeBasicCertificatePropertiesTypeKeyVaultCertificate - objectMap := make(map[string]interface{}) - if kvcp.VaultURI != nil { - objectMap["vaultUri"] = kvcp.VaultURI - } - if kvcp.KeyVaultCertName != nil { - objectMap["keyVaultCertName"] = kvcp.KeyVaultCertName - } - if kvcp.CertVersion != nil { - objectMap["certVersion"] = kvcp.CertVersion - } - if kvcp.ExcludePrivateKey != nil { - objectMap["excludePrivateKey"] = kvcp.ExcludePrivateKey - } - if kvcp.Type != "" { - objectMap["type"] = kvcp.Type - } - return json.Marshal(objectMap) -} - -// AsKeyVaultCertificateProperties is the BasicCertificateProperties implementation for KeyVaultCertificateProperties. -func (kvcp KeyVaultCertificateProperties) AsKeyVaultCertificateProperties() (*KeyVaultCertificateProperties, bool) { - return &kvcp, true -} - -// AsContentCertificateProperties is the BasicCertificateProperties implementation for KeyVaultCertificateProperties. -func (kvcp KeyVaultCertificateProperties) AsContentCertificateProperties() (*ContentCertificateProperties, bool) { - return nil, false -} - -// AsCertificateProperties is the BasicCertificateProperties implementation for KeyVaultCertificateProperties. -func (kvcp KeyVaultCertificateProperties) AsCertificateProperties() (*CertificateProperties, bool) { - return nil, false -} - -// AsBasicCertificateProperties is the BasicCertificateProperties implementation for KeyVaultCertificateProperties. -func (kvcp KeyVaultCertificateProperties) AsBasicCertificateProperties() (BasicCertificateProperties, bool) { - return &kvcp, true -} - -// LoadedCertificate loaded certificate payload -type LoadedCertificate struct { - // ResourceID - Resource Id of loaded certificate - ResourceID *string `json:"resourceId,omitempty"` - // LoadTrustStore - Indicate whether the certificate will be loaded into default trust store, only work for Java runtime. - LoadTrustStore *bool `json:"loadTrustStore,omitempty"` -} - -// LogFileURLResponse log file URL payload -type LogFileURLResponse struct { - autorest.Response `json:"-"` - // URL - URL of the log file - URL *string `json:"url,omitempty"` -} - -// LogSpecification specifications of the Log for Azure Monitoring -type LogSpecification struct { - // Name - Name of the log - Name *string `json:"name,omitempty"` - // DisplayName - Localized friendly display name of the log - DisplayName *string `json:"displayName,omitempty"` - // BlobDuration - Blob duration of the log - BlobDuration *string `json:"blobDuration,omitempty"` -} - -// ManagedIdentityProperties managed identity properties retrieved from ARM request headers. -type ManagedIdentityProperties struct { - // Type - Type of the managed identity. Possible values include: 'ManagedIdentityTypeNone', 'ManagedIdentityTypeSystemAssigned', 'ManagedIdentityTypeUserAssigned', 'ManagedIdentityTypeSystemAssignedUserAssigned' - Type ManagedIdentityType `json:"type,omitempty"` - // PrincipalID - Principal Id of system-assigned managed identity. - PrincipalID *string `json:"principalId,omitempty"` - // TenantID - Tenant Id of system-assigned managed identity. - TenantID *string `json:"tenantId,omitempty"` - // UserAssignedIdentities - Properties of user-assigned managed identities - UserAssignedIdentities map[string]*UserAssignedManagedIdentity `json:"userAssignedIdentities"` -} - -// MarshalJSON is the custom marshaler for ManagedIdentityProperties. -func (mip ManagedIdentityProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mip.Type != "" { - objectMap["type"] = mip.Type - } - if mip.PrincipalID != nil { - objectMap["principalId"] = mip.PrincipalID - } - if mip.TenantID != nil { - objectMap["tenantId"] = mip.TenantID - } - if mip.UserAssignedIdentities != nil { - objectMap["userAssignedIdentities"] = mip.UserAssignedIdentities - } - return json.Marshal(objectMap) -} - -// MetricDimension specifications of the Dimension of metrics -type MetricDimension struct { - // Name - Name of the dimension - Name *string `json:"name,omitempty"` - // DisplayName - Localized friendly display name of the dimension - DisplayName *string `json:"displayName,omitempty"` - // ToBeExportedForShoebox - Whether this dimension should be included for the Shoebox export scenario - ToBeExportedForShoebox *bool `json:"toBeExportedForShoebox,omitempty"` -} - -// MetricSpecification specifications of the Metrics for Azure Monitoring -type MetricSpecification struct { - // Name - Name of the metric - Name *string `json:"name,omitempty"` - // DisplayName - Localized friendly display name of the metric - DisplayName *string `json:"displayName,omitempty"` - // DisplayDescription - Localized friendly description of the metric - DisplayDescription *string `json:"displayDescription,omitempty"` - // Unit - Unit that makes sense for the metric - Unit *string `json:"unit,omitempty"` - // Category - Name of the metric category that the metric belongs to. A metric can only belong to a single category. - Category *string `json:"category,omitempty"` - // AggregationType - Only provide one value for this field. Valid values: Average, Minimum, Maximum, Total, Count. - AggregationType *string `json:"aggregationType,omitempty"` - // SupportedAggregationTypes - Supported aggregation types - SupportedAggregationTypes *[]string `json:"supportedAggregationTypes,omitempty"` - // SupportedTimeGrainTypes - Supported time grain types - SupportedTimeGrainTypes *[]string `json:"supportedTimeGrainTypes,omitempty"` - // FillGapWithZero - Optional. If set to true, then zero will be returned for time duration where no metric is emitted/published. - FillGapWithZero *bool `json:"fillGapWithZero,omitempty"` - // Dimensions - Dimensions of the metric - Dimensions *[]MetricDimension `json:"dimensions,omitempty"` - // SourceMdmNamespace - Name of the MDM namespace. Optional. - SourceMdmNamespace *string `json:"sourceMdmNamespace,omitempty"` -} - -// MonitoringSettingProperties monitoring Setting properties payload -type MonitoringSettingProperties struct { - // ProvisioningState - READ-ONLY; State of the Monitoring Setting. Possible values include: 'MonitoringSettingStateNotAvailable', 'MonitoringSettingStateFailed', 'MonitoringSettingStateSucceeded', 'MonitoringSettingStateUpdating' - ProvisioningState MonitoringSettingState `json:"provisioningState,omitempty"` - // Error - Error when apply Monitoring Setting changes. - Error *Error `json:"error,omitempty"` - // TraceEnabled - Indicates whether enable the trace functionality, which will be deprecated since api version 2020-11-01-preview. Please leverage appInsightsInstrumentationKey to indicate if monitoringSettings enabled or not - TraceEnabled *bool `json:"traceEnabled,omitempty"` - // AppInsightsInstrumentationKey - Target application insight instrumentation key, null or whitespace include empty will disable monitoringSettings - AppInsightsInstrumentationKey *string `json:"appInsightsInstrumentationKey,omitempty"` - // AppInsightsSamplingRate - Indicates the sampling rate of application insight agent, should be in range [0.0, 100.0] - AppInsightsSamplingRate *float64 `json:"appInsightsSamplingRate,omitempty"` - // AppInsightsAgentVersions - Indicates the versions of application insight agent - AppInsightsAgentVersions *ApplicationInsightsAgentVersions `json:"appInsightsAgentVersions,omitempty"` -} - -// MarshalJSON is the custom marshaler for MonitoringSettingProperties. -func (msp MonitoringSettingProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if msp.Error != nil { - objectMap["error"] = msp.Error - } - if msp.TraceEnabled != nil { - objectMap["traceEnabled"] = msp.TraceEnabled - } - if msp.AppInsightsInstrumentationKey != nil { - objectMap["appInsightsInstrumentationKey"] = msp.AppInsightsInstrumentationKey - } - if msp.AppInsightsSamplingRate != nil { - objectMap["appInsightsSamplingRate"] = msp.AppInsightsSamplingRate - } - if msp.AppInsightsAgentVersions != nil { - objectMap["appInsightsAgentVersions"] = msp.AppInsightsAgentVersions - } - return json.Marshal(objectMap) -} - -// MonitoringSettingResource monitoring Setting resource -type MonitoringSettingResource struct { - autorest.Response `json:"-"` - // Properties - Properties of the Monitoring Setting resource - Properties *MonitoringSettingProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for MonitoringSettingResource. -func (msr MonitoringSettingResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if msr.Properties != nil { - objectMap["properties"] = msr.Properties - } - if msr.SystemData != nil { - objectMap["systemData"] = msr.SystemData - } - return json.Marshal(objectMap) -} - -// MonitoringSettingsUpdatePatchFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type MonitoringSettingsUpdatePatchFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(MonitoringSettingsClient) (MonitoringSettingResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *MonitoringSettingsUpdatePatchFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for MonitoringSettingsUpdatePatchFuture.Result. -func (future *MonitoringSettingsUpdatePatchFuture) result(client MonitoringSettingsClient) (msr MonitoringSettingResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsUpdatePatchFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - msr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.MonitoringSettingsUpdatePatchFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if msr.Response.Response, err = future.GetResult(sender); err == nil && msr.Response.Response.StatusCode != http.StatusNoContent { - msr, err = client.UpdatePatchResponder(msr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsUpdatePatchFuture", "Result", msr.Response.Response, "Failure responding to request") - } - } - return -} - -// MonitoringSettingsUpdatePutFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type MonitoringSettingsUpdatePutFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(MonitoringSettingsClient) (MonitoringSettingResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *MonitoringSettingsUpdatePutFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for MonitoringSettingsUpdatePutFuture.Result. -func (future *MonitoringSettingsUpdatePutFuture) result(client MonitoringSettingsClient) (msr MonitoringSettingResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsUpdatePutFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - msr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.MonitoringSettingsUpdatePutFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if msr.Response.Response, err = future.GetResult(sender); err == nil && msr.Response.Response.StatusCode != http.StatusNoContent { - msr, err = client.UpdatePutResponder(msr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsUpdatePutFuture", "Result", msr.Response.Response, "Failure responding to request") - } - } - return -} - -// NameAvailability name availability result payload -type NameAvailability struct { - autorest.Response `json:"-"` - // NameAvailable - Indicates whether the name is available - NameAvailable *bool `json:"nameAvailable,omitempty"` - // Reason - Reason why the name is not available - Reason *string `json:"reason,omitempty"` - // Message - Message why the name is not available - Message *string `json:"message,omitempty"` -} - -// NameAvailabilityParameters name availability parameters payload -type NameAvailabilityParameters struct { - // Type - Type of the resource to check name availability - Type *string `json:"type,omitempty"` - // Name - Name to be checked - Name *string `json:"name,omitempty"` -} - -// NetCoreZipUploadedUserSourceInfo uploaded Jar binary for a deployment -type NetCoreZipUploadedUserSourceInfo struct { - // NetCoreMainEntryPath - The path to the .NET executable relative to zip root - NetCoreMainEntryPath *string `json:"netCoreMainEntryPath,omitempty"` - // RuntimeVersion - Runtime version of the .Net file - RuntimeVersion *string `json:"runtimeVersion,omitempty"` - // RelativePath - Relative path of the storage which stores the source - RelativePath *string `json:"relativePath,omitempty"` - // Version - Version of the source - Version *string `json:"version,omitempty"` - // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' - Type TypeBasicUserSourceInfo `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) MarshalJSON() ([]byte, error) { - nczuusi.Type = TypeBasicUserSourceInfoTypeNetCoreZip - objectMap := make(map[string]interface{}) - if nczuusi.NetCoreMainEntryPath != nil { - objectMap["netCoreMainEntryPath"] = nczuusi.NetCoreMainEntryPath - } - if nczuusi.RuntimeVersion != nil { - objectMap["runtimeVersion"] = nczuusi.RuntimeVersion - } - if nczuusi.RelativePath != nil { - objectMap["relativePath"] = nczuusi.RelativePath - } - if nczuusi.Version != nil { - objectMap["version"] = nczuusi.Version - } - if nczuusi.Type != "" { - objectMap["type"] = nczuusi.Type - } - return json.Marshal(objectMap) -} - -// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { - return &nczuusi, true -} - -// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { - return &nczuusi, true -} - -// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { - return nil, false -} - -// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { - return nil, false -} - -// AsUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { - return nil, false -} - -// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for NetCoreZipUploadedUserSourceInfo. -func (nczuusi NetCoreZipUploadedUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { - return &nczuusi, true -} - -// NetworkProfile service network profile payload -type NetworkProfile struct { - // ServiceRuntimeSubnetID - Fully qualified resource Id of the subnet to host Azure Spring Cloud Service Runtime - ServiceRuntimeSubnetID *string `json:"serviceRuntimeSubnetId,omitempty"` - // AppSubnetID - Fully qualified resource Id of the subnet to host Azure Spring Cloud Apps - AppSubnetID *string `json:"appSubnetId,omitempty"` - // ServiceCidr - Azure Spring Cloud service reserved CIDR - ServiceCidr *string `json:"serviceCidr,omitempty"` - // ServiceRuntimeNetworkResourceGroup - Name of the resource group containing network resources of Azure Spring Cloud Service Runtime - ServiceRuntimeNetworkResourceGroup *string `json:"serviceRuntimeNetworkResourceGroup,omitempty"` - // AppNetworkResourceGroup - Name of the resource group containing network resources of Azure Spring Cloud Apps - AppNetworkResourceGroup *string `json:"appNetworkResourceGroup,omitempty"` - // OutboundIPs - READ-ONLY; Desired outbound IP resources for Azure Spring Cloud instance. - OutboundIPs *NetworkProfileOutboundIPs `json:"outboundIPs,omitempty"` - // RequiredTraffics - READ-ONLY; Required inbound or outbound traffics for Azure Spring Cloud instance. - RequiredTraffics *[]RequiredTraffic `json:"requiredTraffics,omitempty"` -} - -// MarshalJSON is the custom marshaler for NetworkProfile. -func (np NetworkProfile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if np.ServiceRuntimeSubnetID != nil { - objectMap["serviceRuntimeSubnetId"] = np.ServiceRuntimeSubnetID - } - if np.AppSubnetID != nil { - objectMap["appSubnetId"] = np.AppSubnetID - } - if np.ServiceCidr != nil { - objectMap["serviceCidr"] = np.ServiceCidr - } - if np.ServiceRuntimeNetworkResourceGroup != nil { - objectMap["serviceRuntimeNetworkResourceGroup"] = np.ServiceRuntimeNetworkResourceGroup - } - if np.AppNetworkResourceGroup != nil { - objectMap["appNetworkResourceGroup"] = np.AppNetworkResourceGroup - } - return json.Marshal(objectMap) -} - -// NetworkProfileOutboundIPs desired outbound IP resources for Azure Spring Cloud instance. -type NetworkProfileOutboundIPs struct { - // PublicIPs - READ-ONLY; A list of public IP addresses. - PublicIPs *[]string `json:"publicIPs,omitempty"` -} - -// MarshalJSON is the custom marshaler for NetworkProfileOutboundIPs. -func (npP NetworkProfileOutboundIPs) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// OperationDetail operation detail payload -type OperationDetail struct { - // Name - Name of the operation - Name *string `json:"name,omitempty"` - // IsDataAction - Indicates whether the operation is a data action - IsDataAction *bool `json:"isDataAction,omitempty"` - // Display - Display of the operation - Display *OperationDisplay `json:"display,omitempty"` - // ActionType - READ-ONLY; Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. Possible values include: 'ActionTypeInternal' - ActionType ActionType `json:"actionType,omitempty"` - // Origin - Origin of the operation - Origin *string `json:"origin,omitempty"` - // Properties - Properties of the operation - Properties *OperationProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for OperationDetail. -func (od OperationDetail) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if od.Name != nil { - objectMap["name"] = od.Name - } - if od.IsDataAction != nil { - objectMap["isDataAction"] = od.IsDataAction - } - if od.Display != nil { - objectMap["display"] = od.Display - } - if od.Origin != nil { - objectMap["origin"] = od.Origin - } - if od.Properties != nil { - objectMap["properties"] = od.Properties - } - return json.Marshal(objectMap) -} - -// OperationDisplay operation display payload -type OperationDisplay struct { - // Provider - Resource provider of the operation - Provider *string `json:"provider,omitempty"` - // Resource - Resource of the operation - Resource *string `json:"resource,omitempty"` - // Operation - Localized friendly name for the operation - Operation *string `json:"operation,omitempty"` - // Description - Localized friendly description for the operation - Description *string `json:"description,omitempty"` -} - -// OperationProperties extra Operation properties -type OperationProperties struct { - // ServiceSpecification - Service specifications of the operation - ServiceSpecification *ServiceSpecification `json:"serviceSpecification,omitempty"` -} - -// PersistentDisk persistent disk payload -type PersistentDisk struct { - // SizeInGB - Size of the persistent disk in GB - SizeInGB *int32 `json:"sizeInGB,omitempty"` - // UsedInGB - READ-ONLY; Size of the used persistent disk in GB - UsedInGB *int32 `json:"usedInGB,omitempty"` - // MountPath - Mount path of the persistent disk - MountPath *string `json:"mountPath,omitempty"` -} - -// MarshalJSON is the custom marshaler for PersistentDisk. -func (pd PersistentDisk) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pd.SizeInGB != nil { - objectMap["sizeInGB"] = pd.SizeInGB - } - if pd.MountPath != nil { - objectMap["mountPath"] = pd.MountPath - } - return json.Marshal(objectMap) -} - -// ProxyResource the resource model definition for a ARM proxy resource. It will have everything other than -// required location and tags. -type ProxyResource struct { - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for ProxyResource. -func (pr ProxyResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pr.SystemData != nil { - objectMap["systemData"] = pr.SystemData - } - return json.Marshal(objectMap) -} - -// RegenerateTestKeyRequestPayload regenerate test key request payload -type RegenerateTestKeyRequestPayload struct { - // KeyType - Type of the test key. Possible values include: 'TestKeyTypePrimary', 'TestKeyTypeSecondary' - KeyType TestKeyType `json:"keyType,omitempty"` -} - -// RequiredTraffic required inbound or outbound traffic for Azure Spring Cloud instance. -type RequiredTraffic struct { - // Protocol - READ-ONLY; The protocol of required traffic - Protocol *string `json:"protocol,omitempty"` - // Port - READ-ONLY; The port of required traffic - Port *int32 `json:"port,omitempty"` - // Ips - READ-ONLY; The ip list of required traffic - Ips *[]string `json:"ips,omitempty"` - // Fqdns - READ-ONLY; The FQDN list of required traffic - Fqdns *[]string `json:"fqdns,omitempty"` - // Direction - READ-ONLY; The direction of required traffic. Possible values include: 'TrafficDirectionInbound', 'TrafficDirectionOutbound' - Direction TrafficDirection `json:"direction,omitempty"` -} - -// MarshalJSON is the custom marshaler for RequiredTraffic. -func (rt RequiredTraffic) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Resource the core properties of ARM resources. -type Resource struct { - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.SystemData != nil { - objectMap["systemData"] = r.SystemData - } - return json.Marshal(objectMap) -} - -// ResourceRequests deployment resource request payload -type ResourceRequests struct { - // CPU - Required CPU. 1 core can be represented by 1 or 1000m. This should be 500m or 1 for Basic tier, and {500m, 1, 2, 3, 4} for Standard tier. - CPU *string `json:"cpu,omitempty"` - // Memory - Required memory. 1 GB can be represented by 1Gi or 1024Mi. This should be {512Mi, 1Gi, 2Gi} for Basic tier, and {512Mi, 1Gi, 2Gi, ..., 8Gi} for Standard tier. - Memory *string `json:"memory,omitempty"` -} - -// ResourceSku describes an available Azure Spring Cloud SKU. -type ResourceSku struct { - // ResourceType - Gets the type of resource the SKU applies to. - ResourceType *string `json:"resourceType,omitempty"` - // Name - Gets the name of SKU. - Name *string `json:"name,omitempty"` - // Tier - Gets the tier of SKU. - Tier *string `json:"tier,omitempty"` - // Capacity - Gets the capacity of SKU. - Capacity *SkuCapacity `json:"capacity,omitempty"` - // Locations - Gets the set of locations that the SKU is available. - Locations *[]string `json:"locations,omitempty"` - // LocationInfo - Gets a list of locations and availability zones in those locations where the SKU is available. - LocationInfo *[]ResourceSkuLocationInfo `json:"locationInfo,omitempty"` - // Restrictions - Gets the restrictions because of which SKU cannot be used. This is - // empty if there are no restrictions. - Restrictions *[]ResourceSkuRestrictions `json:"restrictions,omitempty"` -} - -// ResourceSkuCapabilities ... -type ResourceSkuCapabilities struct { - // Name - Gets an invariant to describe the feature. - Name *string `json:"name,omitempty"` - // Value - Gets an invariant if the feature is measured by quantity. - Value *string `json:"value,omitempty"` -} - -// ResourceSkuCollection object that includes an array of Azure Spring Cloud SKU and a possible link for -// next set -type ResourceSkuCollection struct { - autorest.Response `json:"-"` - // Value - Collection of resource SKU - Value *[]ResourceSku `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// ResourceSkuCollectionIterator provides access to a complete listing of ResourceSku values. -type ResourceSkuCollectionIterator struct { - i int - page ResourceSkuCollectionPage -} - -// NextWithContext 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 *ResourceSkuCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkuCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ResourceSkuCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ResourceSkuCollectionIterator) 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 ResourceSkuCollectionIterator) Response() ResourceSkuCollection { - 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 ResourceSkuCollectionIterator) Value() ResourceSku { - if !iter.page.NotDone() { - return ResourceSku{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ResourceSkuCollectionIterator type. -func NewResourceSkuCollectionIterator(page ResourceSkuCollectionPage) ResourceSkuCollectionIterator { - return ResourceSkuCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rsc ResourceSkuCollection) IsEmpty() bool { - return rsc.Value == nil || len(*rsc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rsc ResourceSkuCollection) hasNextLink() bool { - return rsc.NextLink != nil && len(*rsc.NextLink) != 0 -} - -// resourceSkuCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rsc ResourceSkuCollection) resourceSkuCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !rsc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rsc.NextLink))) -} - -// ResourceSkuCollectionPage contains a page of ResourceSku values. -type ResourceSkuCollectionPage struct { - fn func(context.Context, ResourceSkuCollection) (ResourceSkuCollection, error) - rsc ResourceSkuCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ResourceSkuCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkuCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rsc) - if err != nil { - return err - } - page.rsc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ResourceSkuCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ResourceSkuCollectionPage) NotDone() bool { - return !page.rsc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ResourceSkuCollectionPage) Response() ResourceSkuCollection { - return page.rsc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ResourceSkuCollectionPage) Values() []ResourceSku { - if page.rsc.IsEmpty() { - return nil - } - return *page.rsc.Value -} - -// Creates a new instance of the ResourceSkuCollectionPage type. -func NewResourceSkuCollectionPage(cur ResourceSkuCollection, getNextPage func(context.Context, ResourceSkuCollection) (ResourceSkuCollection, error)) ResourceSkuCollectionPage { - return ResourceSkuCollectionPage{ - fn: getNextPage, - rsc: cur, - } -} - -// ResourceSkuLocationInfo locations and availability zones where the SKU is available -type ResourceSkuLocationInfo struct { - // Location - Gets location of the SKU - Location *string `json:"location,omitempty"` - // Zones - Gets list of availability zones where the SKU is supported. - Zones *[]string `json:"zones,omitempty"` - // ZoneDetails - Gets details of capabilities available to a SKU in specific zones. - ZoneDetails *[]ResourceSkuZoneDetails `json:"zoneDetails,omitempty"` -} - -// ResourceSkuRestrictionInfo information about the restriction where the SKU cannot be used -type ResourceSkuRestrictionInfo struct { - // Locations - Gets locations where the SKU is restricted - Locations *[]string `json:"locations,omitempty"` - // Zones - Gets list of availability zones where the SKU is restricted. - Zones *[]string `json:"zones,omitempty"` -} - -// ResourceSkuRestrictions restrictions where the SKU cannot be used -type ResourceSkuRestrictions struct { - // Type - Gets the type of restrictions. Possible values include: 'Location', 'Zone'. Possible values include: 'ResourceSkuRestrictionsTypeLocation', 'ResourceSkuRestrictionsTypeZone' - Type ResourceSkuRestrictionsType `json:"type,omitempty"` - // Values - Gets the value of restrictions. If the restriction type is set to - // location. This would be different locations where the SKU is restricted. - Values *[]string `json:"values,omitempty"` - // RestrictionInfo - Gets the information about the restriction where the SKU cannot be used. - RestrictionInfo *ResourceSkuRestrictionInfo `json:"restrictionInfo,omitempty"` - // ReasonCode - Gets the reason for restriction. Possible values include: 'QuotaId', 'NotAvailableForSubscription'. Possible values include: 'ResourceSkuRestrictionsReasonCodeQuotaID', 'ResourceSkuRestrictionsReasonCodeNotAvailableForSubscription' - ReasonCode ResourceSkuRestrictionsReasonCode `json:"reasonCode,omitempty"` -} - -// ResourceSkuZoneDetails details of capabilities available to a SKU in specific zones -type ResourceSkuZoneDetails struct { - // Name - Gets the set of zones that the SKU is available in with the - // specified capabilities. - Name *[]string `json:"name,omitempty"` - // Capabilities - Gets a list of capabilities that are available for the SKU in the - // specified list of zones. - Capabilities *[]ResourceSkuCapabilities `json:"capabilities,omitempty"` -} - -// ResourceUploadDefinition resource upload definition payload -type ResourceUploadDefinition struct { - autorest.Response `json:"-"` - // RelativePath - Source relative path - RelativePath *string `json:"relativePath,omitempty"` - // UploadURL - Upload URL - UploadURL *string `json:"uploadUrl,omitempty"` -} - -// ServiceRegistriesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ServiceRegistriesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceRegistriesClient) (ServiceRegistryResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceRegistriesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceRegistriesCreateOrUpdateFuture.Result. -func (future *ServiceRegistriesCreateOrUpdateFuture) result(client ServiceRegistriesClient) (srr ServiceRegistryResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - srr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ServiceRegistriesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if srr.Response.Response, err = future.GetResult(sender); err == nil && srr.Response.Response.StatusCode != http.StatusNoContent { - srr, err = client.CreateOrUpdateResponder(srr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesCreateOrUpdateFuture", "Result", srr.Response.Response, "Failure responding to request") - } - } - return -} - -// ServiceRegistriesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ServiceRegistriesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceRegistriesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceRegistriesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceRegistriesDeleteFuture.Result. -func (future *ServiceRegistriesDeleteFuture) result(client ServiceRegistriesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ServiceRegistriesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ServiceRegistryInstance collection of instances belong to the Service Registry -type ServiceRegistryInstance struct { - // Name - READ-ONLY; Name of the Service Registry instance - Name *string `json:"name,omitempty"` - // Status - READ-ONLY; Status of the Service Registry instance - Status *string `json:"status,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceRegistryInstance. -func (sri ServiceRegistryInstance) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ServiceRegistryProperties service Registry properties payload -type ServiceRegistryProperties struct { - // ProvisioningState - READ-ONLY; State of the Service Registry. Possible values include: 'ServiceRegistryProvisioningStateCreating', 'ServiceRegistryProvisioningStateUpdating', 'ServiceRegistryProvisioningStateSucceeded', 'ServiceRegistryProvisioningStateFailed', 'ServiceRegistryProvisioningStateDeleting' - ProvisioningState ServiceRegistryProvisioningState `json:"provisioningState,omitempty"` - // ResourceRequests - The requested resource quantity for required CPU and Memory. - ResourceRequests *ServiceRegistryResourceRequests `json:"resourceRequests,omitempty"` - // Instances - READ-ONLY; Collection of instances belong to Service Registry. - Instances *[]ServiceRegistryInstance `json:"instances,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceRegistryProperties. -func (srp ServiceRegistryProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if srp.ResourceRequests != nil { - objectMap["resourceRequests"] = srp.ResourceRequests - } - return json.Marshal(objectMap) -} - -// ServiceRegistryResource service Registry resource -type ServiceRegistryResource struct { - autorest.Response `json:"-"` - Properties *ServiceRegistryProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceRegistryResource. -func (srr ServiceRegistryResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if srr.Properties != nil { - objectMap["properties"] = srr.Properties - } - if srr.SystemData != nil { - objectMap["systemData"] = srr.SystemData - } - return json.Marshal(objectMap) -} - -// ServiceRegistryResourceCollection object that includes an array of Service Registry resources and a -// possible link for next set -type ServiceRegistryResourceCollection struct { - autorest.Response `json:"-"` - // Value - Collection of Service Registry resources - Value *[]ServiceRegistryResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// ServiceRegistryResourceCollectionIterator provides access to a complete listing of -// ServiceRegistryResource values. -type ServiceRegistryResourceCollectionIterator struct { - i int - page ServiceRegistryResourceCollectionPage -} - -// NextWithContext 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 *ServiceRegistryResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistryResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ServiceRegistryResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ServiceRegistryResourceCollectionIterator) 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 ServiceRegistryResourceCollectionIterator) Response() ServiceRegistryResourceCollection { - 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 ServiceRegistryResourceCollectionIterator) Value() ServiceRegistryResource { - if !iter.page.NotDone() { - return ServiceRegistryResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ServiceRegistryResourceCollectionIterator type. -func NewServiceRegistryResourceCollectionIterator(page ServiceRegistryResourceCollectionPage) ServiceRegistryResourceCollectionIterator { - return ServiceRegistryResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (srrc ServiceRegistryResourceCollection) IsEmpty() bool { - return srrc.Value == nil || len(*srrc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (srrc ServiceRegistryResourceCollection) hasNextLink() bool { - return srrc.NextLink != nil && len(*srrc.NextLink) != 0 -} - -// serviceRegistryResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (srrc ServiceRegistryResourceCollection) serviceRegistryResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !srrc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(srrc.NextLink))) -} - -// ServiceRegistryResourceCollectionPage contains a page of ServiceRegistryResource values. -type ServiceRegistryResourceCollectionPage struct { - fn func(context.Context, ServiceRegistryResourceCollection) (ServiceRegistryResourceCollection, error) - srrc ServiceRegistryResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ServiceRegistryResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistryResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.srrc) - if err != nil { - return err - } - page.srrc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ServiceRegistryResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ServiceRegistryResourceCollectionPage) NotDone() bool { - return !page.srrc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ServiceRegistryResourceCollectionPage) Response() ServiceRegistryResourceCollection { - return page.srrc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ServiceRegistryResourceCollectionPage) Values() []ServiceRegistryResource { - if page.srrc.IsEmpty() { - return nil - } - return *page.srrc.Value -} - -// Creates a new instance of the ServiceRegistryResourceCollectionPage type. -func NewServiceRegistryResourceCollectionPage(cur ServiceRegistryResourceCollection, getNextPage func(context.Context, ServiceRegistryResourceCollection) (ServiceRegistryResourceCollection, error)) ServiceRegistryResourceCollectionPage { - return ServiceRegistryResourceCollectionPage{ - fn: getNextPage, - srrc: cur, - } -} - -// ServiceRegistryResourceRequests resource request payload of Service Registry -type ServiceRegistryResourceRequests struct { - // CPU - READ-ONLY; Cpu allocated to each Service Registry instance - CPU *string `json:"cpu,omitempty"` - // Memory - READ-ONLY; Memory allocated to each Service Registry instance - Memory *string `json:"memory,omitempty"` - // InstanceCount - READ-ONLY; Instance count of the Service Registry - InstanceCount *int32 `json:"instanceCount,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceRegistryResourceRequests. -func (srrr ServiceRegistryResourceRequests) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ServiceResource service resource -type ServiceResource struct { - autorest.Response `json:"-"` - // Properties - Properties of the Service resource - Properties *ClusterResourceProperties `json:"properties,omitempty"` - // Sku - Sku of the Service resource - Sku *Sku `json:"sku,omitempty"` - // Location - The GEO location of the resource. - Location *string `json:"location,omitempty"` - // Tags - Tags of the service which is a list of key value pairs that describe the resource. - Tags map[string]*string `json:"tags"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceResource. -func (sr ServiceResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sr.Properties != nil { - objectMap["properties"] = sr.Properties - } - if sr.Sku != nil { - objectMap["sku"] = sr.Sku - } - if sr.Location != nil { - objectMap["location"] = sr.Location - } - if sr.Tags != nil { - objectMap["tags"] = sr.Tags - } - if sr.SystemData != nil { - objectMap["systemData"] = sr.SystemData - } - return json.Marshal(objectMap) -} - -// ServiceResourceList object that includes an array of Service resources and a possible link for next set -type ServiceResourceList struct { - autorest.Response `json:"-"` - // Value - Collection of Service resources - Value *[]ServiceResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// ServiceResourceListIterator provides access to a complete listing of ServiceResource values. -type ServiceResourceListIterator struct { - i int - page ServiceResourceListPage -} - -// NextWithContext 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 *ServiceResourceListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceResourceListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ServiceResourceListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ServiceResourceListIterator) 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 ServiceResourceListIterator) Response() ServiceResourceList { - 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 ServiceResourceListIterator) Value() ServiceResource { - if !iter.page.NotDone() { - return ServiceResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ServiceResourceListIterator type. -func NewServiceResourceListIterator(page ServiceResourceListPage) ServiceResourceListIterator { - return ServiceResourceListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (srl ServiceResourceList) IsEmpty() bool { - return srl.Value == nil || len(*srl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (srl ServiceResourceList) hasNextLink() bool { - return srl.NextLink != nil && len(*srl.NextLink) != 0 -} - -// serviceResourceListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (srl ServiceResourceList) serviceResourceListPreparer(ctx context.Context) (*http.Request, error) { - if !srl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(srl.NextLink))) -} - -// ServiceResourceListPage contains a page of ServiceResource values. -type ServiceResourceListPage struct { - fn func(context.Context, ServiceResourceList) (ServiceResourceList, error) - srl ServiceResourceList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ServiceResourceListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceResourceListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.srl) - if err != nil { - return err - } - page.srl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ServiceResourceListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ServiceResourceListPage) NotDone() bool { - return !page.srl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ServiceResourceListPage) Response() ServiceResourceList { - return page.srl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ServiceResourceListPage) Values() []ServiceResource { - if page.srl.IsEmpty() { - return nil - } - return *page.srl.Value -} - -// Creates a new instance of the ServiceResourceListPage type. -func NewServiceResourceListPage(cur ServiceResourceList, getNextPage func(context.Context, ServiceResourceList) (ServiceResourceList, error)) ServiceResourceListPage { - return ServiceResourceListPage{ - fn: getNextPage, - srl: cur, - } -} - -// ServicesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ServicesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServicesClient) (ServiceResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServicesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServicesCreateOrUpdateFuture.Result. -func (future *ServicesCreateOrUpdateFuture) result(client ServicesClient) (sr ServiceResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ServicesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sr.Response.Response, err = future.GetResult(sender); err == nil && sr.Response.Response.StatusCode != http.StatusNoContent { - sr, err = client.CreateOrUpdateResponder(sr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesCreateOrUpdateFuture", "Result", sr.Response.Response, "Failure responding to request") - } - } - return -} - -// ServicesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ServicesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServicesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServicesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServicesDeleteFuture.Result. -func (future *ServicesDeleteFuture) result(client ServicesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ServicesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ServiceSpecification service specification payload -type ServiceSpecification struct { - // LogSpecifications - Specifications of the Log for Azure Monitoring - LogSpecifications *[]LogSpecification `json:"logSpecifications,omitempty"` - // MetricSpecifications - Specifications of the Metrics for Azure Monitoring - MetricSpecifications *[]MetricSpecification `json:"metricSpecifications,omitempty"` -} - -// ServicesStartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ServicesStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServicesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServicesStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServicesStartFuture.Result. -func (future *ServicesStartFuture) result(client ServicesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ServicesStartFuture") - return - } - ar.Response = future.Response() - return -} - -// ServicesStopFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type ServicesStopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServicesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServicesStopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServicesStopFuture.Result. -func (future *ServicesStopFuture) result(client ServicesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesStopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ServicesStopFuture") - return - } - ar.Response = future.Response() - return -} - -// ServicesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ServicesUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServicesClient) (ServiceResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServicesUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServicesUpdateFuture.Result. -func (future *ServicesUpdateFuture) result(client ServicesClient) (sr ServiceResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.ServicesUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sr.Response.Response, err = future.GetResult(sender); err == nil && sr.Response.Response.StatusCode != http.StatusNoContent { - sr, err = client.UpdateResponder(sr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesUpdateFuture", "Result", sr.Response.Response, "Failure responding to request") - } - } - return -} - -// Sku sku of Azure Spring Cloud -type Sku struct { - // Name - Name of the Sku - Name *string `json:"name,omitempty"` - // Tier - Tier of the Sku - Tier *string `json:"tier,omitempty"` - // Capacity - Current capacity of the target resource - Capacity *int32 `json:"capacity,omitempty"` -} - -// SkuCapacity the SKU capacity -type SkuCapacity struct { - // Minimum - Gets or sets the minimum. - Minimum *int32 `json:"minimum,omitempty"` - // Maximum - Gets or sets the maximum. - Maximum *int32 `json:"maximum,omitempty"` - // Default - Gets or sets the default. - Default *int32 `json:"default,omitempty"` - // ScaleType - Gets or sets the type of the scale. Possible values include: 'SkuScaleTypeNone', 'SkuScaleTypeManual', 'SkuScaleTypeAutomatic' - ScaleType SkuScaleType `json:"scaleType,omitempty"` -} - -// SourceUploadedUserSourceInfo uploaded Java source code binary for a deployment -type SourceUploadedUserSourceInfo struct { - // ArtifactSelector - Selector for the artifact to be used for the deployment for multi-module projects. This should be - // the relative path to the target module/project. - ArtifactSelector *string `json:"artifactSelector,omitempty"` - // RuntimeVersion - Runtime version of the source file - RuntimeVersion *string `json:"runtimeVersion,omitempty"` - // RelativePath - Relative path of the storage which stores the source - RelativePath *string `json:"relativePath,omitempty"` - // Version - Version of the source - Version *string `json:"version,omitempty"` - // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' - Type TypeBasicUserSourceInfo `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) MarshalJSON() ([]byte, error) { - suusi.Type = TypeBasicUserSourceInfoTypeSource - objectMap := make(map[string]interface{}) - if suusi.ArtifactSelector != nil { - objectMap["artifactSelector"] = suusi.ArtifactSelector - } - if suusi.RuntimeVersion != nil { - objectMap["runtimeVersion"] = suusi.RuntimeVersion - } - if suusi.RelativePath != nil { - objectMap["relativePath"] = suusi.RelativePath - } - if suusi.Version != nil { - objectMap["version"] = suusi.Version - } - if suusi.Type != "" { - objectMap["type"] = suusi.Type - } - return json.Marshal(objectMap) -} - -// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { - return &suusi, true -} - -// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { - return &suusi, true -} - -// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { - return nil, false -} - -// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { - return nil, false -} - -// AsUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { - return nil, false -} - -// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for SourceUploadedUserSourceInfo. -func (suusi SourceUploadedUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { - return &suusi, true -} - -// SsoProperties single sign-on related configuration -type SsoProperties struct { - // Scope - It defines the specific actions applications can be allowed to do on a user's behalf - Scope *[]string `json:"scope,omitempty"` - // ClientID - The public identifier for the application - ClientID *string `json:"clientId,omitempty"` - // ClientSecret - The secret known only to the application and the authorization server - ClientSecret *string `json:"clientSecret,omitempty"` - // IssuerURI - The URI of Issuer Identifier - IssuerURI *string `json:"issuerUri,omitempty"` -} - -// StackProperties kPack ClusterStack properties payload -type StackProperties struct { - // ID - Id of the ClusterStack. - ID *string `json:"id,omitempty"` - // Version - Version of the ClusterStack - Version *string `json:"version,omitempty"` -} - -// StorageAccount storage resource of type Azure Storage Account. -type StorageAccount struct { - // AccountName - The account name of the Azure Storage Account. - AccountName *string `json:"accountName,omitempty"` - // AccountKey - The account key of the Azure Storage Account. - AccountKey *string `json:"accountKey,omitempty"` - // StorageType - Possible values include: 'StorageTypeStorageProperties', 'StorageTypeStorageAccount' - StorageType StorageType `json:"storageType,omitempty"` -} - -// MarshalJSON is the custom marshaler for StorageAccount. -func (sa StorageAccount) MarshalJSON() ([]byte, error) { - sa.StorageType = StorageTypeStorageAccount - objectMap := make(map[string]interface{}) - if sa.AccountName != nil { - objectMap["accountName"] = sa.AccountName - } - if sa.AccountKey != nil { - objectMap["accountKey"] = sa.AccountKey - } - if sa.StorageType != "" { - objectMap["storageType"] = sa.StorageType - } - return json.Marshal(objectMap) -} - -// AsStorageAccount is the BasicStorageProperties implementation for StorageAccount. -func (sa StorageAccount) AsStorageAccount() (*StorageAccount, bool) { - return &sa, true -} - -// AsStorageProperties is the BasicStorageProperties implementation for StorageAccount. -func (sa StorageAccount) AsStorageProperties() (*StorageProperties, bool) { - return nil, false -} - -// AsBasicStorageProperties is the BasicStorageProperties implementation for StorageAccount. -func (sa StorageAccount) AsBasicStorageProperties() (BasicStorageProperties, bool) { - return &sa, true -} - -// BasicStorageProperties storage resource payload. -type BasicStorageProperties interface { - AsStorageAccount() (*StorageAccount, bool) - AsStorageProperties() (*StorageProperties, bool) -} - -// StorageProperties storage resource payload. -type StorageProperties struct { - // StorageType - Possible values include: 'StorageTypeStorageProperties', 'StorageTypeStorageAccount' - StorageType StorageType `json:"storageType,omitempty"` -} - -func unmarshalBasicStorageProperties(body []byte) (BasicStorageProperties, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["storageType"] { - case string(StorageTypeStorageAccount): - var sa StorageAccount - err := json.Unmarshal(body, &sa) - return sa, err - default: - var sp StorageProperties - err := json.Unmarshal(body, &sp) - return sp, err - } -} -func unmarshalBasicStoragePropertiesArray(body []byte) ([]BasicStorageProperties, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - spArray := make([]BasicStorageProperties, len(rawMessages)) - - for index, rawMessage := range rawMessages { - sp, err := unmarshalBasicStorageProperties(*rawMessage) - if err != nil { - return nil, err - } - spArray[index] = sp - } - return spArray, nil -} - -// MarshalJSON is the custom marshaler for StorageProperties. -func (sp StorageProperties) MarshalJSON() ([]byte, error) { - sp.StorageType = StorageTypeStorageProperties - objectMap := make(map[string]interface{}) - if sp.StorageType != "" { - objectMap["storageType"] = sp.StorageType - } - return json.Marshal(objectMap) -} - -// AsStorageAccount is the BasicStorageProperties implementation for StorageProperties. -func (sp StorageProperties) AsStorageAccount() (*StorageAccount, bool) { - return nil, false -} - -// AsStorageProperties is the BasicStorageProperties implementation for StorageProperties. -func (sp StorageProperties) AsStorageProperties() (*StorageProperties, bool) { - return &sp, true -} - -// AsBasicStorageProperties is the BasicStorageProperties implementation for StorageProperties. -func (sp StorageProperties) AsBasicStorageProperties() (BasicStorageProperties, bool) { - return &sp, true -} - -// StorageResource storage resource payload. -type StorageResource struct { - autorest.Response `json:"-"` - // Properties - Properties of the storage resource payload. - Properties BasicStorageProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for StorageResource. -func (sr StorageResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - objectMap["properties"] = sr.Properties - if sr.SystemData != nil { - objectMap["systemData"] = sr.SystemData - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for StorageResource struct. -func (sr *StorageResource) 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 { - properties, err := unmarshalBasicStorageProperties(*v) - if err != nil { - return err - } - sr.Properties = properties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sr.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sr.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sr.Type = &typeVar - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - sr.SystemData = &systemData - } - } - } - - return nil -} - -// StorageResourceCollection collection compose of storage resources list and a possible link for next -// page. -type StorageResourceCollection struct { - autorest.Response `json:"-"` - // Value - The storage resources list. - Value *[]StorageResource `json:"value,omitempty"` - // NextLink - The link to next page of storage list. - NextLink *string `json:"nextLink,omitempty"` -} - -// StorageResourceCollectionIterator provides access to a complete listing of StorageResource values. -type StorageResourceCollectionIterator struct { - i int - page StorageResourceCollectionPage -} - -// NextWithContext 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 *StorageResourceCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StorageResourceCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *StorageResourceCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter StorageResourceCollectionIterator) 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 StorageResourceCollectionIterator) Response() StorageResourceCollection { - 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 StorageResourceCollectionIterator) Value() StorageResource { - if !iter.page.NotDone() { - return StorageResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the StorageResourceCollectionIterator type. -func NewStorageResourceCollectionIterator(page StorageResourceCollectionPage) StorageResourceCollectionIterator { - return StorageResourceCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (src StorageResourceCollection) IsEmpty() bool { - return src.Value == nil || len(*src.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (src StorageResourceCollection) hasNextLink() bool { - return src.NextLink != nil && len(*src.NextLink) != 0 -} - -// storageResourceCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (src StorageResourceCollection) storageResourceCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !src.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(src.NextLink))) -} - -// StorageResourceCollectionPage contains a page of StorageResource values. -type StorageResourceCollectionPage struct { - fn func(context.Context, StorageResourceCollection) (StorageResourceCollection, error) - src StorageResourceCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *StorageResourceCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StorageResourceCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.src) - if err != nil { - return err - } - page.src = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *StorageResourceCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page StorageResourceCollectionPage) NotDone() bool { - return !page.src.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page StorageResourceCollectionPage) Response() StorageResourceCollection { - return page.src -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page StorageResourceCollectionPage) Values() []StorageResource { - if page.src.IsEmpty() { - return nil - } - return *page.src.Value -} - -// Creates a new instance of the StorageResourceCollectionPage type. -func NewStorageResourceCollectionPage(cur StorageResourceCollection, getNextPage func(context.Context, StorageResourceCollection) (StorageResourceCollection, error)) StorageResourceCollectionPage { - return StorageResourceCollectionPage{ - fn: getNextPage, - src: cur, - } -} - -// StoragesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type StoragesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(StoragesClient) (StorageResource, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *StoragesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for StoragesCreateOrUpdateFuture.Result. -func (future *StoragesCreateOrUpdateFuture) result(client StoragesClient) (sr StorageResource, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.StoragesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sr.Response.Response, err = future.GetResult(sender); err == nil && sr.Response.Response.StatusCode != http.StatusNoContent { - sr, err = client.CreateOrUpdateResponder(sr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesCreateOrUpdateFuture", "Result", sr.Response.Response, "Failure responding to request") - } - } - return -} - -// StoragesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type StoragesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(StoragesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *StoragesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for StoragesDeleteFuture.Result. -func (future *StoragesDeleteFuture) result(client StoragesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("appplatform.StoragesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SupportedBuildpackResource supported buildpack resource payload -type SupportedBuildpackResource struct { - autorest.Response `json:"-"` - Properties *SupportedBuildpackResourceProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for SupportedBuildpackResource. -func (sbr SupportedBuildpackResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sbr.Properties != nil { - objectMap["properties"] = sbr.Properties - } - if sbr.SystemData != nil { - objectMap["systemData"] = sbr.SystemData - } - return json.Marshal(objectMap) -} - -// SupportedBuildpackResourceProperties supported buildpack resource properties -type SupportedBuildpackResourceProperties struct { - // BuildpackID - The id of supported buildpack - BuildpackID *string `json:"buildpackId,omitempty"` -} - -// SupportedBuildpacksCollection object that includes an array of supported buildpacks resources and a -// possible link for next set -type SupportedBuildpacksCollection struct { - autorest.Response `json:"-"` - // Value - Collection of supported buildpacks resources - Value *[]SupportedBuildpackResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// SupportedRuntimeVersion supported deployment runtime version descriptor. -type SupportedRuntimeVersion struct { - // Value - The raw value which could be passed to deployment CRUD operations. Possible values include: 'SupportedRuntimeValueJava8', 'SupportedRuntimeValueJava11', 'SupportedRuntimeValueJava17', 'SupportedRuntimeValueNetCore31' - Value SupportedRuntimeValue `json:"value,omitempty"` - // Platform - The platform of this runtime version (possible values: "Java" or ".NET"). Possible values include: 'SupportedRuntimePlatformJava', 'SupportedRuntimePlatformNETCore' - Platform SupportedRuntimePlatform `json:"platform,omitempty"` - // Version - The detailed version (major.minor) of the platform. - Version *string `json:"version,omitempty"` -} - -// SupportedStackResource supported stack resource payload -type SupportedStackResource struct { - autorest.Response `json:"-"` - Properties *SupportedStackResourceProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,omitempty"` -} - -// MarshalJSON is the custom marshaler for SupportedStackResource. -func (ssr SupportedStackResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ssr.Properties != nil { - objectMap["properties"] = ssr.Properties - } - if ssr.SystemData != nil { - objectMap["systemData"] = ssr.SystemData - } - return json.Marshal(objectMap) -} - -// SupportedStackResourceProperties supported stack resource properties -type SupportedStackResourceProperties struct { - // StackID - The id of supported stack - StackID *string `json:"stackId,omitempty"` - // Version - The version of supported stack - Version *string `json:"version,omitempty"` -} - -// SupportedStacksCollection object that includes an array of supported stacks resources and a possible -// link for next set -type SupportedStacksCollection struct { - autorest.Response `json:"-"` - // Value - Collection of supported stacks resources - Value *[]SupportedStackResource `json:"value,omitempty"` - // NextLink - URL client should use to fetch the next page (per server side paging). - // It's null for now, added for future use. - NextLink *string `json:"nextLink,omitempty"` -} - -// SystemData metadata pertaining to creation and last modification of the resource. -type SystemData struct { - // CreatedBy - The identity that created the resource. - CreatedBy *string `json:"createdBy,omitempty"` - // CreatedByType - The type of identity that created the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' - CreatedByType CreatedByType `json:"createdByType,omitempty"` - // CreatedAt - The timestamp of resource creation (UTC). - CreatedAt *date.Time `json:"createdAt,omitempty"` - // LastModifiedBy - The identity that last modified the resource. - LastModifiedBy *string `json:"lastModifiedBy,omitempty"` - // LastModifiedByType - The type of identity that last modified the resource. Possible values include: 'LastModifiedByTypeUser', 'LastModifiedByTypeApplication', 'LastModifiedByTypeManagedIdentity', 'LastModifiedByTypeKey' - LastModifiedByType LastModifiedByType `json:"lastModifiedByType,omitempty"` - // LastModifiedAt - The timestamp of resource modification (UTC). - LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` -} - -// TemporaryDisk temporary disk payload -type TemporaryDisk struct { - // SizeInGB - Size of the temporary disk in GB - SizeInGB *int32 `json:"sizeInGB,omitempty"` - // MountPath - Mount path of the temporary disk - MountPath *string `json:"mountPath,omitempty"` -} - -// TestKeys test keys payload -type TestKeys struct { - autorest.Response `json:"-"` - // PrimaryKey - Primary key - PrimaryKey *string `json:"primaryKey,omitempty"` - // SecondaryKey - Secondary key - SecondaryKey *string `json:"secondaryKey,omitempty"` - // PrimaryTestEndpoint - Primary test endpoint - PrimaryTestEndpoint *string `json:"primaryTestEndpoint,omitempty"` - // SecondaryTestEndpoint - Secondary test endpoint - SecondaryTestEndpoint *string `json:"secondaryTestEndpoint,omitempty"` - // Enabled - Indicates whether the test endpoint feature enabled or not - Enabled *bool `json:"enabled,omitempty"` -} - -// TrackedResource the resource model definition for a ARM tracked top level resource. -type TrackedResource struct { - // Location - The GEO location of the resource. - Location *string `json:"location,omitempty"` - // Tags - Tags of the service which is a list of key value pairs that describe the resource. - Tags map[string]*string `json:"tags"` - // ID - READ-ONLY; Fully qualified resource Id for the resource. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. - Type *string `json:"type,omitempty"` - SystemData *SystemData `json:"systemData,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.SystemData != nil { - objectMap["systemData"] = tr.SystemData - } - return json.Marshal(objectMap) -} - -// TriggeredBuildResult the build result triggered by a build -type TriggeredBuildResult struct { - // ID - The unique build id of this build result - ID *string `json:"id,omitempty"` -} - -// BasicUploadedUserSourceInfo source with uploaded location -type BasicUploadedUserSourceInfo interface { - AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) - AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) - AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) - AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) -} - -// UploadedUserSourceInfo source with uploaded location -type UploadedUserSourceInfo struct { - // RelativePath - Relative path of the storage which stores the source - RelativePath *string `json:"relativePath,omitempty"` - // Version - Version of the source - Version *string `json:"version,omitempty"` - // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' - Type TypeBasicUserSourceInfo `json:"type,omitempty"` -} - -func unmarshalBasicUploadedUserSourceInfo(body []byte) (BasicUploadedUserSourceInfo, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["type"] { - case string(TypeBasicUserSourceInfoTypeJar): - var juusi JarUploadedUserSourceInfo - err := json.Unmarshal(body, &juusi) - return juusi, err - case string(TypeBasicUserSourceInfoTypeSource): - var suusi SourceUploadedUserSourceInfo - err := json.Unmarshal(body, &suusi) - return suusi, err - case string(TypeBasicUserSourceInfoTypeNetCoreZip): - var nczuusi NetCoreZipUploadedUserSourceInfo - err := json.Unmarshal(body, &nczuusi) - return nczuusi, err - default: - var uusi UploadedUserSourceInfo - err := json.Unmarshal(body, &uusi) - return uusi, err - } -} -func unmarshalBasicUploadedUserSourceInfoArray(body []byte) ([]BasicUploadedUserSourceInfo, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - uusiArray := make([]BasicUploadedUserSourceInfo, len(rawMessages)) - - for index, rawMessage := range rawMessages { - uusi, err := unmarshalBasicUploadedUserSourceInfo(*rawMessage) - if err != nil { - return nil, err - } - uusiArray[index] = uusi - } - return uusiArray, nil -} - -// MarshalJSON is the custom marshaler for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) MarshalJSON() ([]byte, error) { - uusi.Type = TypeBasicUserSourceInfoTypeUploadedUserSourceInfo - objectMap := make(map[string]interface{}) - if uusi.RelativePath != nil { - objectMap["relativePath"] = uusi.RelativePath - } - if uusi.Version != nil { - objectMap["version"] = uusi.Version - } - if uusi.Type != "" { - objectMap["type"] = uusi.Type - } - return json.Marshal(objectMap) -} - -// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { - return &uusi, true -} - -// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { - return &uusi, true -} - -// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { - return nil, false -} - -// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { - return nil, false -} - -// AsUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { - return nil, false -} - -// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for UploadedUserSourceInfo. -func (uusi UploadedUserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { - return &uusi, true -} - -// UserAssignedManagedIdentity the details of the user-assigned managed identity assigned to an App. -type UserAssignedManagedIdentity struct { - // PrincipalID - READ-ONLY; Principal Id of user-assigned managed identity. - PrincipalID *string `json:"principalId,omitempty"` - // ClientID - READ-ONLY; Client Id of user-assigned managed identity. - ClientID *string `json:"clientId,omitempty"` -} - -// MarshalJSON is the custom marshaler for UserAssignedManagedIdentity. -func (uami UserAssignedManagedIdentity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// BasicUserSourceInfo source information for a deployment -type BasicUserSourceInfo interface { - AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) - AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) - AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) - AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) - AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) - AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) - AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) - AsUserSourceInfo() (*UserSourceInfo, bool) -} - -// UserSourceInfo source information for a deployment -type UserSourceInfo struct { - // Version - Version of the source - Version *string `json:"version,omitempty"` - // Type - Possible values include: 'TypeBasicUserSourceInfoTypeUserSourceInfo', 'TypeBasicUserSourceInfoTypeUploadedUserSourceInfo', 'TypeBasicUserSourceInfoTypeJar', 'TypeBasicUserSourceInfoTypeSource', 'TypeBasicUserSourceInfoTypeNetCoreZip', 'TypeBasicUserSourceInfoTypeBuildResult', 'TypeBasicUserSourceInfoTypeContainer' - Type TypeBasicUserSourceInfo `json:"type,omitempty"` -} - -func unmarshalBasicUserSourceInfo(body []byte) (BasicUserSourceInfo, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["type"] { - case string(TypeBasicUserSourceInfoTypeUploadedUserSourceInfo): - var uusi UploadedUserSourceInfo - err := json.Unmarshal(body, &uusi) - return uusi, err - case string(TypeBasicUserSourceInfoTypeJar): - var juusi JarUploadedUserSourceInfo - err := json.Unmarshal(body, &juusi) - return juusi, err - case string(TypeBasicUserSourceInfoTypeSource): - var suusi SourceUploadedUserSourceInfo - err := json.Unmarshal(body, &suusi) - return suusi, err - case string(TypeBasicUserSourceInfoTypeNetCoreZip): - var nczuusi NetCoreZipUploadedUserSourceInfo - err := json.Unmarshal(body, &nczuusi) - return nczuusi, err - case string(TypeBasicUserSourceInfoTypeBuildResult): - var brusi BuildResultUserSourceInfo - err := json.Unmarshal(body, &brusi) - return brusi, err - case string(TypeBasicUserSourceInfoTypeContainer): - var ccusi CustomContainerUserSourceInfo - err := json.Unmarshal(body, &ccusi) - return ccusi, err - default: - var usi UserSourceInfo - err := json.Unmarshal(body, &usi) - return usi, err - } -} -func unmarshalBasicUserSourceInfoArray(body []byte) ([]BasicUserSourceInfo, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - usiArray := make([]BasicUserSourceInfo, len(rawMessages)) - - for index, rawMessage := range rawMessages { - usi, err := unmarshalBasicUserSourceInfo(*rawMessage) - if err != nil { - return nil, err - } - usiArray[index] = usi - } - return usiArray, nil -} - -// MarshalJSON is the custom marshaler for UserSourceInfo. -func (usi UserSourceInfo) MarshalJSON() ([]byte, error) { - usi.Type = TypeBasicUserSourceInfoTypeUserSourceInfo - objectMap := make(map[string]interface{}) - if usi.Version != nil { - objectMap["version"] = usi.Version - } - if usi.Type != "" { - objectMap["type"] = usi.Type - } - return json.Marshal(objectMap) -} - -// AsUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. -func (usi UserSourceInfo) AsUploadedUserSourceInfo() (*UploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBasicUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. -func (usi UserSourceInfo) AsBasicUploadedUserSourceInfo() (BasicUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsJarUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. -func (usi UserSourceInfo) AsJarUploadedUserSourceInfo() (*JarUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsSourceUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. -func (usi UserSourceInfo) AsSourceUploadedUserSourceInfo() (*SourceUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsNetCoreZipUploadedUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. -func (usi UserSourceInfo) AsNetCoreZipUploadedUserSourceInfo() (*NetCoreZipUploadedUserSourceInfo, bool) { - return nil, false -} - -// AsBuildResultUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. -func (usi UserSourceInfo) AsBuildResultUserSourceInfo() (*BuildResultUserSourceInfo, bool) { - return nil, false -} - -// AsCustomContainerUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. -func (usi UserSourceInfo) AsCustomContainerUserSourceInfo() (*CustomContainerUserSourceInfo, bool) { - return nil, false -} - -// AsUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. -func (usi UserSourceInfo) AsUserSourceInfo() (*UserSourceInfo, bool) { - return &usi, true -} - -// AsBasicUserSourceInfo is the BasicUserSourceInfo implementation for UserSourceInfo. -func (usi UserSourceInfo) AsBasicUserSourceInfo() (BasicUserSourceInfo, bool) { - return &usi, true -} - -// ValidationMessages validate messages of the configuration service git repositories -type ValidationMessages struct { - // Name - The name of the configuration service git repository. - Name *string `json:"name,omitempty"` - // Messages - Detailed validation messages. - Messages *[]string `json:"messages,omitempty"` -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/monitoringsettings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/monitoringsettings.go deleted file mode 100644 index 6feea311ea0c..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/monitoringsettings.go +++ /dev/null @@ -1,287 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// MonitoringSettingsClient is the REST API for Azure Spring Cloud -type MonitoringSettingsClient struct { - BaseClient -} - -// NewMonitoringSettingsClient creates an instance of the MonitoringSettingsClient client. -func NewMonitoringSettingsClient(subscriptionID string) MonitoringSettingsClient { - return NewMonitoringSettingsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewMonitoringSettingsClientWithBaseURI creates an instance of the MonitoringSettingsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewMonitoringSettingsClientWithBaseURI(baseURI string, subscriptionID string) MonitoringSettingsClient { - return MonitoringSettingsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get get the Monitoring Setting and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client MonitoringSettingsClient) Get(ctx context.Context, resourceGroupName string, serviceName string) (result MonitoringSettingResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MonitoringSettingsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client MonitoringSettingsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/monitoringSettings/default", 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 MonitoringSettingsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client MonitoringSettingsClient) GetResponder(resp *http.Response) (result MonitoringSettingResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdatePatch update the Monitoring Setting. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// monitoringSettingResource - parameters for the update operation -func (client MonitoringSettingsClient) UpdatePatch(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource) (result MonitoringSettingsUpdatePatchFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MonitoringSettingsClient.UpdatePatch") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePatchPreparer(ctx, resourceGroupName, serviceName, monitoringSettingResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "UpdatePatch", nil, "Failure preparing request") - return - } - - result, err = client.UpdatePatchSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "UpdatePatch", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePatchPreparer prepares the UpdatePatch request. -func (client MonitoringSettingsClient) UpdatePatchPreparer(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/monitoringSettings/default", pathParameters), - autorest.WithJSON(monitoringSettingResource), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdatePatchSender sends the UpdatePatch request. The method will close the -// http.Response Body if it receives an error. -func (client MonitoringSettingsClient) UpdatePatchSender(req *http.Request) (future MonitoringSettingsUpdatePatchFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdatePatchResponder handles the response to the UpdatePatch request. The method always -// closes the http.Response Body. -func (client MonitoringSettingsClient) UpdatePatchResponder(resp *http.Response) (result MonitoringSettingResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdatePut update the Monitoring Setting. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// monitoringSettingResource - parameters for the update operation -func (client MonitoringSettingsClient) UpdatePut(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource) (result MonitoringSettingsUpdatePutFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MonitoringSettingsClient.UpdatePut") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: monitoringSettingResource, - Constraints: []validation.Constraint{{Target: "monitoringSettingResource.Properties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "monitoringSettingResource.Properties.AppInsightsSamplingRate", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "monitoringSettingResource.Properties.AppInsightsSamplingRate", Name: validation.InclusiveMaximum, Rule: float64(100), Chain: nil}, - {Target: "monitoringSettingResource.Properties.AppInsightsSamplingRate", Name: validation.InclusiveMinimum, Rule: float64(0), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("appplatform.MonitoringSettingsClient", "UpdatePut", err.Error()) - } - - req, err := client.UpdatePutPreparer(ctx, resourceGroupName, serviceName, monitoringSettingResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "UpdatePut", nil, "Failure preparing request") - return - } - - result, err = client.UpdatePutSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.MonitoringSettingsClient", "UpdatePut", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePutPreparer prepares the UpdatePut request. -func (client MonitoringSettingsClient) UpdatePutPreparer(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/monitoringSettings/default", pathParameters), - autorest.WithJSON(monitoringSettingResource), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdatePutSender sends the UpdatePut request. The method will close the -// http.Response Body if it receives an error. -func (client MonitoringSettingsClient) UpdatePutSender(req *http.Request) (future MonitoringSettingsUpdatePutFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdatePutResponder handles the response to the UpdatePut request. The method always -// closes the http.Response Body. -func (client MonitoringSettingsClient) UpdatePutResponder(resp *http.Response) (result MonitoringSettingResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/operations.go deleted file mode 100644 index 58e54b8446cd..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/operations.go +++ /dev/null @@ -1,140 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// OperationsClient is the REST API for Azure Spring Cloud -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 using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List lists all of the available REST API operations of the Microsoft.AppPlatform provider. -func (client OperationsClient) List(ctx context.Context) (result AvailableOperationsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.ao.Response.Response != nil { - sc = result.ao.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.OperationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ao.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.OperationsClient", "List", resp, "Failure sending request") - return - } - - result.ao, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.OperationsClient", "List", resp, "Failure responding to request") - return - } - if result.ao.hasNextLink() && result.ao.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.AppPlatform/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 client.Send(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 AvailableOperations, err error) { - err = autorest.Respond( - resp, - 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(ctx context.Context, lastResults AvailableOperations) (result AvailableOperations, err error) { - req, err := lastResults.availableOperationsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.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, "appplatform.OperationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.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 AvailableOperationsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/runtimeversions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/runtimeversions.go deleted file mode 100644 index 896cc97cbe2f..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/runtimeversions.go +++ /dev/null @@ -1,98 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// RuntimeVersionsClient is the REST API for Azure Spring Cloud -type RuntimeVersionsClient struct { - BaseClient -} - -// NewRuntimeVersionsClient creates an instance of the RuntimeVersionsClient client. -func NewRuntimeVersionsClient(subscriptionID string) RuntimeVersionsClient { - return NewRuntimeVersionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRuntimeVersionsClientWithBaseURI creates an instance of the RuntimeVersionsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRuntimeVersionsClientWithBaseURI(baseURI string, subscriptionID string) RuntimeVersionsClient { - return RuntimeVersionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// ListRuntimeVersions lists all of the available runtime versions supported by Microsoft.AppPlatform provider. -func (client RuntimeVersionsClient) ListRuntimeVersions(ctx context.Context) (result AvailableRuntimeVersions, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RuntimeVersionsClient.ListRuntimeVersions") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListRuntimeVersionsPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.RuntimeVersionsClient", "ListRuntimeVersions", nil, "Failure preparing request") - return - } - - resp, err := client.ListRuntimeVersionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.RuntimeVersionsClient", "ListRuntimeVersions", resp, "Failure sending request") - return - } - - result, err = client.ListRuntimeVersionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.RuntimeVersionsClient", "ListRuntimeVersions", resp, "Failure responding to request") - return - } - - return -} - -// ListRuntimeVersionsPreparer prepares the ListRuntimeVersions request. -func (client RuntimeVersionsClient) ListRuntimeVersionsPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.AppPlatform/runtimeVersions"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRuntimeVersionsSender sends the ListRuntimeVersions request. The method will close the -// http.Response Body if it receives an error. -func (client RuntimeVersionsClient) ListRuntimeVersionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListRuntimeVersionsResponder handles the response to the ListRuntimeVersions request. The method always -// closes the http.Response Body. -func (client RuntimeVersionsClient) ListRuntimeVersionsResponder(resp *http.Response) (result AvailableRuntimeVersions, err error) { - err = autorest.Respond( - resp, - 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/serviceregistries.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/serviceregistries.go deleted file mode 100644 index bc79902ddb29..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/serviceregistries.go +++ /dev/null @@ -1,393 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// ServiceRegistriesClient is the REST API for Azure Spring Cloud -type ServiceRegistriesClient struct { - BaseClient -} - -// NewServiceRegistriesClient creates an instance of the ServiceRegistriesClient client. -func NewServiceRegistriesClient(subscriptionID string) ServiceRegistriesClient { - return NewServiceRegistriesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewServiceRegistriesClientWithBaseURI creates an instance of the ServiceRegistriesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewServiceRegistriesClientWithBaseURI(baseURI string, subscriptionID string) ServiceRegistriesClient { - return ServiceRegistriesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create the default Service Registry or update the existing Service Registry. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// serviceRegistryName - the name of Service Registry. -func (client ServiceRegistriesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (result ServiceRegistriesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, serviceRegistryName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ServiceRegistriesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "serviceRegistryName": autorest.Encode("path", serviceRegistryName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/serviceRegistries/{serviceRegistryName}", pathParameters), - 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 ServiceRegistriesClient) CreateOrUpdateSender(req *http.Request) (future ServiceRegistriesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ServiceRegistriesClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceRegistryResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete disable the default Service Registry. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// serviceRegistryName - the name of Service Registry. -func (client ServiceRegistriesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (result ServiceRegistriesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, serviceRegistryName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ServiceRegistriesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "serviceRegistryName": autorest.Encode("path", serviceRegistryName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/serviceRegistries/{serviceRegistryName}", 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 ServiceRegistriesClient) DeleteSender(req *http.Request) (future ServiceRegistriesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ServiceRegistriesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the Service Registry and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// serviceRegistryName - the name of Service Registry. -func (client ServiceRegistriesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (result ServiceRegistryResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, serviceRegistryName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ServiceRegistriesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, serviceRegistryName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "serviceRegistryName": autorest.Encode("path", serviceRegistryName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/serviceRegistries/{serviceRegistryName}", 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 ServiceRegistriesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ServiceRegistriesClient) GetResponder(resp *http.Response) (result ServiceRegistryResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handles requests to list all resources in a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ServiceRegistriesClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result ServiceRegistryResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.List") - defer func() { - sc := -1 - if result.srrc.Response.Response != nil { - sc = result.srrc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.srrc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "List", resp, "Failure sending request") - return - } - - result.srrc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "List", resp, "Failure responding to request") - return - } - if result.srrc.hasNextLink() && result.srrc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ServiceRegistriesClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/serviceRegistries", 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 ServiceRegistriesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ServiceRegistriesClient) ListResponder(resp *http.Response) (result ServiceRegistryResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 ServiceRegistriesClient) listNextResults(ctx context.Context, lastResults ServiceRegistryResourceCollection) (result ServiceRegistryResourceCollection, err error) { - req, err := lastResults.serviceRegistryResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "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, "appplatform.ServiceRegistriesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServiceRegistriesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServiceRegistriesClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result ServiceRegistryResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRegistriesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/services.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/services.go deleted file mode 100644 index dd58f440bcdf..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/services.go +++ /dev/null @@ -1,1136 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ServicesClient is the REST API for Azure Spring Cloud -type ServicesClient struct { - BaseClient -} - -// NewServicesClient creates an instance of the ServicesClient client. -func NewServicesClient(subscriptionID string) ServicesClient { - return NewServicesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewServicesClientWithBaseURI creates an instance of the ServicesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewServicesClientWithBaseURI(baseURI string, subscriptionID string) ServicesClient { - return ServicesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckNameAvailability checks that the resource name is valid and is not already in use. -// Parameters: -// location - the region -// availabilityParameters - parameters supplied to the operation. -func (client ServicesClient) CheckNameAvailability(ctx context.Context, location string, availabilityParameters NameAvailabilityParameters) (result NameAvailability, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.CheckNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: availabilityParameters, - Constraints: []validation.Constraint{{Target: "availabilityParameters.Type", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "availabilityParameters.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("appplatform.ServicesClient", "CheckNameAvailability", err.Error()) - } - - req, err := client.CheckNameAvailabilityPreparer(ctx, location, availabilityParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CheckNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CheckNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CheckNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. -func (client ServicesClient) CheckNameAvailabilityPreparer(ctx context.Context, location string, availabilityParameters NameAvailabilityParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/locations/{location}/checkNameAvailability", pathParameters), - autorest.WithJSON(availabilityParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client ServicesClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always -// closes the http.Response Body. -func (client ServicesClient) CheckNameAvailabilityResponder(resp *http.Response) (result NameAvailability, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate create a new Service or update an exiting Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// resource - parameters for the create or update operation -func (client ServicesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (result ServicesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, resource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ServicesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}", pathParameters), - autorest.WithJSON(resource), - 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 ServicesClient) CreateOrUpdateSender(req *http.Request) (future ServicesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ServicesClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete operation to delete a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ServicesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string) (result ServicesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}", 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 ServicesClient) DeleteSender(req *http.Request) (future ServicesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ServicesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// DisableTestEndpoint disable test endpoint functionality for a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ServicesClient) DisableTestEndpoint(ctx context.Context, resourceGroupName string, serviceName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.DisableTestEndpoint") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DisableTestEndpointPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "DisableTestEndpoint", nil, "Failure preparing request") - return - } - - resp, err := client.DisableTestEndpointSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "DisableTestEndpoint", resp, "Failure sending request") - return - } - - result, err = client.DisableTestEndpointResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "DisableTestEndpoint", resp, "Failure responding to request") - return - } - - return -} - -// DisableTestEndpointPreparer prepares the DisableTestEndpoint request. -func (client ServicesClient) DisableTestEndpointPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/disableTestEndpoint", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DisableTestEndpointSender sends the DisableTestEndpoint request. The method will close the -// http.Response Body if it receives an error. -func (client ServicesClient) DisableTestEndpointSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DisableTestEndpointResponder handles the response to the DisableTestEndpoint request. The method always -// closes the http.Response Body. -func (client ServicesClient) DisableTestEndpointResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = resp - return -} - -// EnableTestEndpoint enable test endpoint functionality for a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ServicesClient) EnableTestEndpoint(ctx context.Context, resourceGroupName string, serviceName string) (result TestKeys, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.EnableTestEndpoint") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.EnableTestEndpointPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "EnableTestEndpoint", nil, "Failure preparing request") - return - } - - resp, err := client.EnableTestEndpointSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "EnableTestEndpoint", resp, "Failure sending request") - return - } - - result, err = client.EnableTestEndpointResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "EnableTestEndpoint", resp, "Failure responding to request") - return - } - - return -} - -// EnableTestEndpointPreparer prepares the EnableTestEndpoint request. -func (client ServicesClient) EnableTestEndpointPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/enableTestEndpoint", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// EnableTestEndpointSender sends the EnableTestEndpoint request. The method will close the -// http.Response Body if it receives an error. -func (client ServicesClient) EnableTestEndpointSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// EnableTestEndpointResponder handles the response to the EnableTestEndpoint request. The method always -// closes the http.Response Body. -func (client ServicesClient) EnableTestEndpointResponder(resp *http.Response) (result TestKeys, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get get a Service and its properties. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ServicesClient) Get(ctx context.Context, resourceGroupName string, serviceName string) (result ServiceResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ServicesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}", 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 ServicesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ServicesClient) GetResponder(resp *http.Response) (result ServiceResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List handles requests to list all resources in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -func (client ServicesClient) List(ctx context.Context, resourceGroupName string) (result ServiceResourceListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.List") - defer func() { - sc := -1 - if result.srl.Response.Response != nil { - sc = result.srl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.srl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "List", resp, "Failure sending request") - return - } - - result.srl, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "List", resp, "Failure responding to request") - return - } - if result.srl.hasNextLink() && result.srl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ServicesClient) ListPreparer(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 = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring", 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 ServicesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ServicesClient) ListResponder(resp *http.Response) (result ServiceResourceList, err error) { - err = autorest.Respond( - resp, - 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 ServicesClient) listNextResults(ctx context.Context, lastResults ServiceResourceList) (result ServiceResourceList, err error) { - req, err := lastResults.serviceResourceListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.ServicesClient", "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, "appplatform.ServicesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServicesClient) ListComplete(ctx context.Context, resourceGroupName string) (result ServiceResourceListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListBySubscription handles requests to list all resources in a subscription. -func (client ServicesClient) ListBySubscription(ctx context.Context) (result ServiceResourceListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.ListBySubscription") - defer func() { - sc := -1 - if result.srl.Response.Response != nil { - sc = result.srl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.srl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.srl, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.srl.hasNextLink() && result.srl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client ServicesClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AppPlatform/Spring", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client ServicesClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client ServicesClient) ListBySubscriptionResponder(resp *http.Response) (result ServiceResourceList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client ServicesClient) listBySubscriptionNextResults(ctx context.Context, lastResults ServiceResourceList) (result ServiceResourceList, err error) { - req, err := lastResults.serviceResourceListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.ServicesClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "appplatform.ServicesClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServicesClient) ListBySubscriptionComplete(ctx context.Context) (result ServiceResourceListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx) - return -} - -// ListTestKeys list test keys for a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ServicesClient) ListTestKeys(ctx context.Context, resourceGroupName string, serviceName string) (result TestKeys, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.ListTestKeys") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListTestKeysPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListTestKeys", nil, "Failure preparing request") - return - } - - resp, err := client.ListTestKeysSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListTestKeys", resp, "Failure sending request") - return - } - - result, err = client.ListTestKeysResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "ListTestKeys", resp, "Failure responding to request") - return - } - - return -} - -// ListTestKeysPreparer prepares the ListTestKeys request. -func (client ServicesClient) ListTestKeysPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/listTestKeys", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListTestKeysSender sends the ListTestKeys request. The method will close the -// http.Response Body if it receives an error. -func (client ServicesClient) ListTestKeysSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListTestKeysResponder handles the response to the ListTestKeys request. The method always -// closes the http.Response Body. -func (client ServicesClient) ListTestKeysResponder(resp *http.Response) (result TestKeys, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// RegenerateTestKey regenerate a test key for a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// regenerateTestKeyRequest - parameters for the operation -func (client ServicesClient) RegenerateTestKey(ctx context.Context, resourceGroupName string, serviceName string, regenerateTestKeyRequest RegenerateTestKeyRequestPayload) (result TestKeys, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.RegenerateTestKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RegenerateTestKeyPreparer(ctx, resourceGroupName, serviceName, regenerateTestKeyRequest) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "RegenerateTestKey", nil, "Failure preparing request") - return - } - - resp, err := client.RegenerateTestKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "RegenerateTestKey", resp, "Failure sending request") - return - } - - result, err = client.RegenerateTestKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "RegenerateTestKey", resp, "Failure responding to request") - return - } - - return -} - -// RegenerateTestKeyPreparer prepares the RegenerateTestKey request. -func (client ServicesClient) RegenerateTestKeyPreparer(ctx context.Context, resourceGroupName string, serviceName string, regenerateTestKeyRequest RegenerateTestKeyRequestPayload) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/regenerateTestKey", pathParameters), - autorest.WithJSON(regenerateTestKeyRequest), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RegenerateTestKeySender sends the RegenerateTestKey request. The method will close the -// http.Response Body if it receives an error. -func (client ServicesClient) RegenerateTestKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// RegenerateTestKeyResponder handles the response to the RegenerateTestKey request. The method always -// closes the http.Response Body. -func (client ServicesClient) RegenerateTestKeyResponder(resp *http.Response) (result TestKeys, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Start start a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ServicesClient) Start(ctx context.Context, resourceGroupName string, serviceName string) (result ServicesStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client ServicesClient) StartPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client ServicesClient) StartSender(req *http.Request) (future ServicesStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client ServicesClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Stop stop a Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client ServicesClient) Stop(ctx context.Context, resourceGroupName string, serviceName string) (result ServicesStopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Stop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Stop", nil, "Failure preparing request") - return - } - - result, err = client.StopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Stop", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client ServicesClient) StopPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/stop", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopSender sends the Stop request. The method will close the -// http.Response Body if it receives an error. -func (client ServicesClient) StopSender(req *http.Request) (future ServicesStopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopResponder handles the response to the Stop request. The method always -// closes the http.Response Body. -func (client ServicesClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Update operation to update an exiting Service. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// resource - parameters for the update operation -func (client ServicesClient) Update(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (result ServicesUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, resource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.ServicesClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ServicesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, resource ServiceResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}", pathParameters), - autorest.WithJSON(resource), - 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 ServicesClient) UpdateSender(req *http.Request) (future ServicesUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ServicesClient) UpdateResponder(resp *http.Response) (result ServiceResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, 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/preview/appplatform/mgmt/2022-03-01-preview/appplatform/skus.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/skus.go deleted file mode 100644 index 042d265e2a4b..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/skus.go +++ /dev/null @@ -1,144 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// SkusClient is the REST API for Azure Spring Cloud -type SkusClient struct { - BaseClient -} - -// NewSkusClient creates an instance of the SkusClient client. -func NewSkusClient(subscriptionID string) SkusClient { - return NewSkusClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSkusClientWithBaseURI creates an instance of the SkusClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSkusClientWithBaseURI(baseURI string, subscriptionID string) SkusClient { - return SkusClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List lists all of the available skus of the Microsoft.AppPlatform provider. -func (client SkusClient) List(ctx context.Context) (result ResourceSkuCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SkusClient.List") - defer func() { - sc := -1 - if result.rsc.Response.Response != nil { - sc = result.rsc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.SkusClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rsc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.SkusClient", "List", resp, "Failure sending request") - return - } - - result.rsc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.SkusClient", "List", resp, "Failure responding to request") - return - } - if result.rsc.hasNextLink() && result.rsc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SkusClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.AppPlatform/skus", 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 SkusClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SkusClient) ListResponder(resp *http.Response) (result ResourceSkuCollection, err error) { - err = autorest.Respond( - resp, - 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 SkusClient) listNextResults(ctx context.Context, lastResults ResourceSkuCollection) (result ResourceSkuCollection, err error) { - req, err := lastResults.resourceSkuCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.SkusClient", "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, "appplatform.SkusClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.SkusClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SkusClient) ListComplete(ctx context.Context) (result ResourceSkuCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SkusClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/storages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/storages.go deleted file mode 100644 index 2525c2f89a60..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/storages.go +++ /dev/null @@ -1,395 +0,0 @@ -package appplatform - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// StoragesClient is the REST API for Azure Spring Cloud -type StoragesClient struct { - BaseClient -} - -// NewStoragesClient creates an instance of the StoragesClient client. -func NewStoragesClient(subscriptionID string) StoragesClient { - return NewStoragesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewStoragesClientWithBaseURI creates an instance of the StoragesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewStoragesClientWithBaseURI(baseURI string, subscriptionID string) StoragesClient { - return StoragesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update storage resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// storageName - the name of the storage resource. -// storageResource - parameters for the create or update operation -func (client StoragesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, storageName string, storageResource StorageResource) (result StoragesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, storageName, storageResource) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client StoragesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, storageName string, storageResource StorageResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "storageName": autorest.Encode("path", storageName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - 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.AppPlatform/Spring/{serviceName}/storages/{storageName}", pathParameters), - autorest.WithJSON(storageResource), - 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 StoragesClient) CreateOrUpdateSender(req *http.Request) (future StoragesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client StoragesClient) CreateOrUpdateResponder(resp *http.Response) (result StorageResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the storage resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// storageName - the name of the storage resource. -func (client StoragesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, storageName string) (result StoragesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName, storageName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client StoragesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string, storageName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "storageName": autorest.Encode("path", storageName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/storages/{storageName}", 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 StoragesClient) DeleteSender(req *http.Request) (future StoragesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client StoragesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the storage resource. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -// storageName - the name of the storage resource. -func (client StoragesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, storageName string) (result StorageResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, storageName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client StoragesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, storageName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "storageName": autorest.Encode("path", storageName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/storages/{storageName}", 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 StoragesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client StoragesClient) GetResponder(resp *http.Response) (result StorageResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all the storages of one Azure Spring Cloud instance. -// Parameters: -// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value -// from the Azure Resource Manager API or the portal. -// serviceName - the name of the Service resource. -func (client StoragesClient) List(ctx context.Context, resourceGroupName string, serviceName string) (result StorageResourceCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.List") - defer func() { - sc := -1 - if result.src.Response.Response != nil { - sc = result.src.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.src.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "List", resp, "Failure sending request") - return - } - - result.src, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "List", resp, "Failure responding to request") - return - } - if result.src.hasNextLink() && result.src.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client StoragesClient) ListPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-03-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/storages", 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 StoragesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client StoragesClient) ListResponder(resp *http.Response) (result StorageResourceCollection, err error) { - err = autorest.Respond( - resp, - 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 StoragesClient) listNextResults(ctx context.Context, lastResults StorageResourceCollection) (result StorageResourceCollection, err error) { - req, err := lastResults.storageResourceCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "appplatform.StoragesClient", "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, "appplatform.StoragesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "appplatform.StoragesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client StoragesClient) ListComplete(ctx context.Context, resourceGroupName string, serviceName string) (result StorageResourceCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StoragesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, serviceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/version.go deleted file mode 100644 index deea37d5b5da..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2022-03-01-preview/appplatform/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package appplatform - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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() + " appplatform/2022-03-01-preview" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/CHANGELOG.md deleted file mode 100644 index 52911e4cc5e4..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/_meta.json deleted file mode 100644 index d8306d1abfe0..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "3c764635e7d442b3e74caf593029fcd440b3ef82", - "readme": "/_/azure-rest-api-specs/specification/policyinsights/resource-manager/readme.md", - "tag": "package-2019-10", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-2019-10 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION /_/azure-rest-api-specs/specification/policyinsights/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/client.go deleted file mode 100644 index e12b01c69756..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/client.go +++ /dev/null @@ -1,39 +0,0 @@ -// Package policyinsights implements the Azure ARM Policyinsights service API version . -// -// -package policyinsights - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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 Policyinsights - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Policyinsights. -type BaseClient struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the BaseClient client. -func New() BaseClient { - return NewWithBaseURI(DefaultBaseURI) -} - -// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewWithBaseURI(baseURI string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - } -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/enums.go deleted file mode 100644 index 2c21cb3b8aeb..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/enums.go +++ /dev/null @@ -1,38 +0,0 @@ -package policyinsights - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// PolicyStatesResource enumerates the values for policy states resource. -type PolicyStatesResource string - -const ( - // Default ... - Default PolicyStatesResource = "default" - // Latest ... - Latest PolicyStatesResource = "latest" -) - -// PossiblePolicyStatesResourceValues returns an array of possible values for the PolicyStatesResource const type. -func PossiblePolicyStatesResourceValues() []PolicyStatesResource { - return []PolicyStatesResource{Default, Latest} -} - -// ResourceDiscoveryMode enumerates the values for resource discovery mode. -type ResourceDiscoveryMode string - -const ( - // ExistingNonCompliant Remediate resources that are already known to be non-compliant. - ExistingNonCompliant ResourceDiscoveryMode = "ExistingNonCompliant" - // ReEvaluateCompliance Re-evaluate the compliance state of resources and then remediate the resources - // found to be non-compliant. - ReEvaluateCompliance ResourceDiscoveryMode = "ReEvaluateCompliance" -) - -// PossibleResourceDiscoveryModeValues returns an array of possible values for the ResourceDiscoveryMode const type. -func PossibleResourceDiscoveryModeValues() []ResourceDiscoveryMode { - return []ResourceDiscoveryMode{ExistingNonCompliant, ReEvaluateCompliance} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/models.go deleted file mode 100644 index 6a043e44d224..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/models.go +++ /dev/null @@ -1,2962 +0,0 @@ -package policyinsights - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights" - -// ComplianceDetail the compliance state rollup. -type ComplianceDetail struct { - // ComplianceState - The compliance state. - ComplianceState *string `json:"complianceState,omitempty"` - // Count - Summarized count value for this compliance state. - Count *int32 `json:"count,omitempty"` -} - -// ComponentEventDetails component event details. -type ComponentEventDetails struct { - // AdditionalProperties - Unmatched properties from the message are deserialized this collection - AdditionalProperties map[string]interface{} `json:""` - // ID - Component Id. - ID *string `json:"id,omitempty"` - // Type - Component type. - Type *string `json:"type,omitempty"` - // Name - Component name. - Name *string `json:"name,omitempty"` - // Timestamp - Timestamp for component policy event record. - Timestamp *date.Time `json:"timestamp,omitempty"` - // TenantID - Tenant ID for the policy event record. - TenantID *string `json:"tenantId,omitempty"` - // PrincipalOid - Principal object ID for the user who initiated the resource component operation that triggered the policy event. - PrincipalOid *string `json:"principalOid,omitempty"` - // PolicyDefinitionAction - Policy definition action, i.e. effect. - PolicyDefinitionAction *string `json:"policyDefinitionAction,omitempty"` -} - -// MarshalJSON is the custom marshaler for ComponentEventDetails. -func (ced ComponentEventDetails) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ced.ID != nil { - objectMap["id"] = ced.ID - } - if ced.Type != nil { - objectMap["type"] = ced.Type - } - if ced.Name != nil { - objectMap["name"] = ced.Name - } - if ced.Timestamp != nil { - objectMap["timestamp"] = ced.Timestamp - } - if ced.TenantID != nil { - objectMap["tenantId"] = ced.TenantID - } - if ced.PrincipalOid != nil { - objectMap["principalOid"] = ced.PrincipalOid - } - if ced.PolicyDefinitionAction != nil { - objectMap["policyDefinitionAction"] = ced.PolicyDefinitionAction - } - for k, v := range ced.AdditionalProperties { - objectMap[k] = v - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ComponentEventDetails struct. -func (ced *ComponentEventDetails) 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 { - default: - if v != nil { - var additionalProperties interface{} - err = json.Unmarshal(*v, &additionalProperties) - if err != nil { - return err - } - if ced.AdditionalProperties == nil { - ced.AdditionalProperties = make(map[string]interface{}) - } - ced.AdditionalProperties[k] = additionalProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ced.ID = &ID - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ced.Type = &typeVar - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ced.Name = &name - } - case "timestamp": - if v != nil { - var timestamp date.Time - err = json.Unmarshal(*v, ×tamp) - if err != nil { - return err - } - ced.Timestamp = ×tamp - } - case "tenantId": - if v != nil { - var tenantID string - err = json.Unmarshal(*v, &tenantID) - if err != nil { - return err - } - ced.TenantID = &tenantID - } - case "principalOid": - if v != nil { - var principalOid string - err = json.Unmarshal(*v, &principalOid) - if err != nil { - return err - } - ced.PrincipalOid = &principalOid - } - case "policyDefinitionAction": - if v != nil { - var policyDefinitionAction string - err = json.Unmarshal(*v, &policyDefinitionAction) - if err != nil { - return err - } - ced.PolicyDefinitionAction = &policyDefinitionAction - } - } - } - - return nil -} - -// ComponentStateDetails component state details. -type ComponentStateDetails struct { - // AdditionalProperties - Unmatched properties from the message are deserialized this collection - AdditionalProperties map[string]interface{} `json:""` - // ID - Component Id. - ID *string `json:"id,omitempty"` - // Type - Component type. - Type *string `json:"type,omitempty"` - // Name - Component name. - Name *string `json:"name,omitempty"` - // Timestamp - Component compliance evaluation timestamp. - Timestamp *date.Time `json:"timestamp,omitempty"` - // ComplianceState - Component compliance state. - ComplianceState *string `json:"complianceState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ComponentStateDetails. -func (csd ComponentStateDetails) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if csd.ID != nil { - objectMap["id"] = csd.ID - } - if csd.Type != nil { - objectMap["type"] = csd.Type - } - if csd.Name != nil { - objectMap["name"] = csd.Name - } - if csd.Timestamp != nil { - objectMap["timestamp"] = csd.Timestamp - } - if csd.ComplianceState != nil { - objectMap["complianceState"] = csd.ComplianceState - } - for k, v := range csd.AdditionalProperties { - objectMap[k] = v - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ComponentStateDetails struct. -func (csd *ComponentStateDetails) 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 { - default: - if v != nil { - var additionalProperties interface{} - err = json.Unmarshal(*v, &additionalProperties) - if err != nil { - return err - } - if csd.AdditionalProperties == nil { - csd.AdditionalProperties = make(map[string]interface{}) - } - csd.AdditionalProperties[k] = additionalProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - csd.ID = &ID - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - csd.Type = &typeVar - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - csd.Name = &name - } - case "timestamp": - if v != nil { - var timestamp date.Time - err = json.Unmarshal(*v, ×tamp) - if err != nil { - return err - } - csd.Timestamp = ×tamp - } - case "complianceState": - if v != nil { - var complianceState string - err = json.Unmarshal(*v, &complianceState) - if err != nil { - return err - } - csd.ComplianceState = &complianceState - } - } - } - - return nil -} - -// ErrorDefinition error definition. -type ErrorDefinition struct { - // Code - READ-ONLY; Service specific error code which serves as the substatus for the HTTP error code. - Code *string `json:"code,omitempty"` - // Message - READ-ONLY; Description of the error. - Message *string `json:"message,omitempty"` - // Target - READ-ONLY; The target of the error. - Target *string `json:"target,omitempty"` - // Details - READ-ONLY; Internal error details. - Details *[]ErrorDefinition `json:"details,omitempty"` - // AdditionalInfo - READ-ONLY; Additional scenario specific error details. - AdditionalInfo *[]TypedErrorInfo `json:"additionalInfo,omitempty"` -} - -// MarshalJSON is the custom marshaler for ErrorDefinition. -func (ed ErrorDefinition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ErrorResponse error response. -type ErrorResponse struct { - // Error - The error details. - Error *ErrorDefinition `json:"error,omitempty"` -} - -// ExpressionEvaluationDetails evaluation details of policy language expressions. -type ExpressionEvaluationDetails struct { - // Result - Evaluation result. - Result *string `json:"result,omitempty"` - // Expression - Expression evaluated. - Expression *string `json:"expression,omitempty"` - // ExpressionKind - READ-ONLY; The kind of expression that was evaluated. - ExpressionKind *string `json:"expressionKind,omitempty"` - // Path - Property path if the expression is a field or an alias. - Path *string `json:"path,omitempty"` - // ExpressionValue - Value of the expression. - ExpressionValue interface{} `json:"expressionValue,omitempty"` - // TargetValue - Target value to be compared with the expression value. - TargetValue interface{} `json:"targetValue,omitempty"` - // Operator - Operator to compare the expression value and the target value. - Operator *string `json:"operator,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressionEvaluationDetails. -func (eed ExpressionEvaluationDetails) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if eed.Result != nil { - objectMap["result"] = eed.Result - } - if eed.Expression != nil { - objectMap["expression"] = eed.Expression - } - if eed.Path != nil { - objectMap["path"] = eed.Path - } - if eed.ExpressionValue != nil { - objectMap["expressionValue"] = eed.ExpressionValue - } - if eed.TargetValue != nil { - objectMap["targetValue"] = eed.TargetValue - } - if eed.Operator != nil { - objectMap["operator"] = eed.Operator - } - return json.Marshal(objectMap) -} - -// IfNotExistsEvaluationDetails evaluation details of IfNotExists effect. -type IfNotExistsEvaluationDetails struct { - // ResourceID - ID of the last evaluated resource for IfNotExists effect. - ResourceID *string `json:"resourceId,omitempty"` - // TotalResources - Total number of resources to which the existence condition is applicable. - TotalResources *int32 `json:"totalResources,omitempty"` -} - -// Operation operation definition. -type Operation struct { - // Name - Operation name. - Name *string `json:"name,omitempty"` - // Display - Display metadata associated with the operation. - Display *OperationDisplay `json:"display,omitempty"` -} - -// OperationDisplay display metadata associated with the operation. -type OperationDisplay struct { - // Provider - Resource provider name. - Provider *string `json:"provider,omitempty"` - // Resource - Resource name on which the operation is performed. - Resource *string `json:"resource,omitempty"` - // Operation - Operation name. - Operation *string `json:"operation,omitempty"` - // Description - Operation description. - Description *string `json:"description,omitempty"` -} - -// OperationsListResults list of available operations. -type OperationsListResults struct { - autorest.Response `json:"-"` - // OdataCount - OData entity count; represents the number of operations returned. - OdataCount *int32 `json:"@odata.count,omitempty"` - // Value - List of available operations. - Value *[]Operation `json:"value,omitempty"` -} - -// PolicyAssignmentSummary policy assignment summary. -type PolicyAssignmentSummary struct { - // PolicyAssignmentID - Policy assignment ID. - PolicyAssignmentID *string `json:"policyAssignmentId,omitempty"` - // PolicySetDefinitionID - Policy set definition ID, if the policy assignment is for a policy set. - PolicySetDefinitionID *string `json:"policySetDefinitionId,omitempty"` - // Results - Compliance summary for the policy assignment. - Results *SummaryResults `json:"results,omitempty"` - // PolicyDefinitions - Policy definitions summary. - PolicyDefinitions *[]PolicyDefinitionSummary `json:"policyDefinitions,omitempty"` - // PolicyGroups - Policy definition group summary. - PolicyGroups *[]PolicyGroupSummary `json:"policyGroups,omitempty"` -} - -// PolicyDefinitionSummary policy definition summary. -type PolicyDefinitionSummary struct { - // PolicyDefinitionID - Policy definition ID. - PolicyDefinitionID *string `json:"policyDefinitionId,omitempty"` - // PolicyDefinitionReferenceID - Policy definition reference ID. - PolicyDefinitionReferenceID *string `json:"policyDefinitionReferenceId,omitempty"` - // PolicyDefinitionGroupNames - Policy definition group names. - PolicyDefinitionGroupNames *[]string `json:"policyDefinitionGroupNames,omitempty"` - // Effect - Policy effect, i.e. policy definition action. - Effect *string `json:"effect,omitempty"` - // Results - Compliance summary for the policy definition. - Results *SummaryResults `json:"results,omitempty"` -} - -// PolicyDetails the policy details. -type PolicyDetails struct { - // PolicyDefinitionID - READ-ONLY; The ID of the policy definition. - PolicyDefinitionID *string `json:"policyDefinitionId,omitempty"` - // PolicyAssignmentID - READ-ONLY; The ID of the policy assignment. - PolicyAssignmentID *string `json:"policyAssignmentId,omitempty"` - // PolicyAssignmentDisplayName - READ-ONLY; The display name of the policy assignment. - PolicyAssignmentDisplayName *string `json:"policyAssignmentDisplayName,omitempty"` - // PolicyAssignmentScope - READ-ONLY; The scope of the policy assignment. - PolicyAssignmentScope *string `json:"policyAssignmentScope,omitempty"` - // PolicySetDefinitionID - READ-ONLY; The ID of the policy set definition. - PolicySetDefinitionID *string `json:"policySetDefinitionId,omitempty"` - // PolicyDefinitionReferenceID - READ-ONLY; The policy definition reference ID within the policy set definition. - PolicyDefinitionReferenceID *string `json:"policyDefinitionReferenceId,omitempty"` -} - -// MarshalJSON is the custom marshaler for PolicyDetails. -func (pd PolicyDetails) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PolicyEvaluationDetails policy evaluation details. -type PolicyEvaluationDetails struct { - // EvaluatedExpressions - Details of the evaluated expressions. - EvaluatedExpressions *[]ExpressionEvaluationDetails `json:"evaluatedExpressions,omitempty"` - // IfNotExistsDetails - Evaluation details of IfNotExists effect. - IfNotExistsDetails *IfNotExistsEvaluationDetails `json:"ifNotExistsDetails,omitempty"` -} - -// PolicyEvent policy event record. -type PolicyEvent struct { - // AdditionalProperties - Unmatched properties from the message are deserialized this collection - AdditionalProperties map[string]interface{} `json:""` - // OdataID - OData entity ID; always set to null since policy event records do not have an entity ID. - OdataID *string `json:"@odata.id,omitempty"` - // OdataContext - OData context string; used by OData clients to resolve type information based on metadata. - OdataContext *string `json:"@odata.context,omitempty"` - // Timestamp - Timestamp for the policy event record. - Timestamp *date.Time `json:"timestamp,omitempty"` - // ResourceID - Resource ID. - ResourceID *string `json:"resourceId,omitempty"` - // PolicyAssignmentID - Policy assignment ID. - PolicyAssignmentID *string `json:"policyAssignmentId,omitempty"` - // PolicyDefinitionID - Policy definition ID. - PolicyDefinitionID *string `json:"policyDefinitionId,omitempty"` - // EffectiveParameters - Effective parameters for the policy assignment. - EffectiveParameters *string `json:"effectiveParameters,omitempty"` - // IsCompliant - Flag which states whether the resource is compliant against the policy assignment it was evaluated against. - IsCompliant *bool `json:"isCompliant,omitempty"` - // SubscriptionID - Subscription ID. - SubscriptionID *string `json:"subscriptionId,omitempty"` - // ResourceType - Resource type. - ResourceType *string `json:"resourceType,omitempty"` - // ResourceLocation - Resource location. - ResourceLocation *string `json:"resourceLocation,omitempty"` - // ResourceGroup - Resource group name. - ResourceGroup *string `json:"resourceGroup,omitempty"` - // ResourceTags - List of resource tags. - ResourceTags *string `json:"resourceTags,omitempty"` - // PolicyAssignmentName - Policy assignment name. - PolicyAssignmentName *string `json:"policyAssignmentName,omitempty"` - // PolicyAssignmentOwner - Policy assignment owner. - PolicyAssignmentOwner *string `json:"policyAssignmentOwner,omitempty"` - // PolicyAssignmentParameters - Policy assignment parameters. - PolicyAssignmentParameters *string `json:"policyAssignmentParameters,omitempty"` - // PolicyAssignmentScope - Policy assignment scope. - PolicyAssignmentScope *string `json:"policyAssignmentScope,omitempty"` - // PolicyDefinitionName - Policy definition name. - PolicyDefinitionName *string `json:"policyDefinitionName,omitempty"` - // PolicyDefinitionAction - Policy definition action, i.e. effect. - PolicyDefinitionAction *string `json:"policyDefinitionAction,omitempty"` - // PolicyDefinitionCategory - Policy definition category. - PolicyDefinitionCategory *string `json:"policyDefinitionCategory,omitempty"` - // PolicySetDefinitionID - Policy set definition ID, if the policy assignment is for a policy set. - PolicySetDefinitionID *string `json:"policySetDefinitionId,omitempty"` - // PolicySetDefinitionName - Policy set definition name, if the policy assignment is for a policy set. - PolicySetDefinitionName *string `json:"policySetDefinitionName,omitempty"` - // PolicySetDefinitionOwner - Policy set definition owner, if the policy assignment is for a policy set. - PolicySetDefinitionOwner *string `json:"policySetDefinitionOwner,omitempty"` - // PolicySetDefinitionCategory - Policy set definition category, if the policy assignment is for a policy set. - PolicySetDefinitionCategory *string `json:"policySetDefinitionCategory,omitempty"` - // PolicySetDefinitionParameters - Policy set definition parameters, if the policy assignment is for a policy set. - PolicySetDefinitionParameters *string `json:"policySetDefinitionParameters,omitempty"` - // ManagementGroupIds - Comma separated list of management group IDs, which represent the hierarchy of the management groups the resource is under. - ManagementGroupIds *string `json:"managementGroupIds,omitempty"` - // PolicyDefinitionReferenceID - Reference ID for the policy definition inside the policy set, if the policy assignment is for a policy set. - PolicyDefinitionReferenceID *string `json:"policyDefinitionReferenceId,omitempty"` - // ComplianceState - Compliance state of the resource. - ComplianceState *string `json:"complianceState,omitempty"` - // TenantID - Tenant ID for the policy event record. - TenantID *string `json:"tenantId,omitempty"` - // PrincipalOid - Principal object ID for the user who initiated the resource operation that triggered the policy event. - PrincipalOid *string `json:"principalOid,omitempty"` - // Components - Components events records populated only when URL contains $expand=components clause. - Components *[]ComponentEventDetails `json:"components,omitempty"` -} - -// MarshalJSON is the custom marshaler for PolicyEvent. -func (peVar PolicyEvent) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if peVar.OdataID != nil { - objectMap["@odata.id"] = peVar.OdataID - } - if peVar.OdataContext != nil { - objectMap["@odata.context"] = peVar.OdataContext - } - if peVar.Timestamp != nil { - objectMap["timestamp"] = peVar.Timestamp - } - if peVar.ResourceID != nil { - objectMap["resourceId"] = peVar.ResourceID - } - if peVar.PolicyAssignmentID != nil { - objectMap["policyAssignmentId"] = peVar.PolicyAssignmentID - } - if peVar.PolicyDefinitionID != nil { - objectMap["policyDefinitionId"] = peVar.PolicyDefinitionID - } - if peVar.EffectiveParameters != nil { - objectMap["effectiveParameters"] = peVar.EffectiveParameters - } - if peVar.IsCompliant != nil { - objectMap["isCompliant"] = peVar.IsCompliant - } - if peVar.SubscriptionID != nil { - objectMap["subscriptionId"] = peVar.SubscriptionID - } - if peVar.ResourceType != nil { - objectMap["resourceType"] = peVar.ResourceType - } - if peVar.ResourceLocation != nil { - objectMap["resourceLocation"] = peVar.ResourceLocation - } - if peVar.ResourceGroup != nil { - objectMap["resourceGroup"] = peVar.ResourceGroup - } - if peVar.ResourceTags != nil { - objectMap["resourceTags"] = peVar.ResourceTags - } - if peVar.PolicyAssignmentName != nil { - objectMap["policyAssignmentName"] = peVar.PolicyAssignmentName - } - if peVar.PolicyAssignmentOwner != nil { - objectMap["policyAssignmentOwner"] = peVar.PolicyAssignmentOwner - } - if peVar.PolicyAssignmentParameters != nil { - objectMap["policyAssignmentParameters"] = peVar.PolicyAssignmentParameters - } - if peVar.PolicyAssignmentScope != nil { - objectMap["policyAssignmentScope"] = peVar.PolicyAssignmentScope - } - if peVar.PolicyDefinitionName != nil { - objectMap["policyDefinitionName"] = peVar.PolicyDefinitionName - } - if peVar.PolicyDefinitionAction != nil { - objectMap["policyDefinitionAction"] = peVar.PolicyDefinitionAction - } - if peVar.PolicyDefinitionCategory != nil { - objectMap["policyDefinitionCategory"] = peVar.PolicyDefinitionCategory - } - if peVar.PolicySetDefinitionID != nil { - objectMap["policySetDefinitionId"] = peVar.PolicySetDefinitionID - } - if peVar.PolicySetDefinitionName != nil { - objectMap["policySetDefinitionName"] = peVar.PolicySetDefinitionName - } - if peVar.PolicySetDefinitionOwner != nil { - objectMap["policySetDefinitionOwner"] = peVar.PolicySetDefinitionOwner - } - if peVar.PolicySetDefinitionCategory != nil { - objectMap["policySetDefinitionCategory"] = peVar.PolicySetDefinitionCategory - } - if peVar.PolicySetDefinitionParameters != nil { - objectMap["policySetDefinitionParameters"] = peVar.PolicySetDefinitionParameters - } - if peVar.ManagementGroupIds != nil { - objectMap["managementGroupIds"] = peVar.ManagementGroupIds - } - if peVar.PolicyDefinitionReferenceID != nil { - objectMap["policyDefinitionReferenceId"] = peVar.PolicyDefinitionReferenceID - } - if peVar.ComplianceState != nil { - objectMap["complianceState"] = peVar.ComplianceState - } - if peVar.TenantID != nil { - objectMap["tenantId"] = peVar.TenantID - } - if peVar.PrincipalOid != nil { - objectMap["principalOid"] = peVar.PrincipalOid - } - if peVar.Components != nil { - objectMap["components"] = peVar.Components - } - for k, v := range peVar.AdditionalProperties { - objectMap[k] = v - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PolicyEvent struct. -func (peVar *PolicyEvent) 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 { - default: - if v != nil { - var additionalProperties interface{} - err = json.Unmarshal(*v, &additionalProperties) - if err != nil { - return err - } - if peVar.AdditionalProperties == nil { - peVar.AdditionalProperties = make(map[string]interface{}) - } - peVar.AdditionalProperties[k] = additionalProperties - } - case "@odata.id": - if v != nil { - var odataID string - err = json.Unmarshal(*v, &odataID) - if err != nil { - return err - } - peVar.OdataID = &odataID - } - case "@odata.context": - if v != nil { - var odataContext string - err = json.Unmarshal(*v, &odataContext) - if err != nil { - return err - } - peVar.OdataContext = &odataContext - } - case "timestamp": - if v != nil { - var timestamp date.Time - err = json.Unmarshal(*v, ×tamp) - if err != nil { - return err - } - peVar.Timestamp = ×tamp - } - case "resourceId": - if v != nil { - var resourceID string - err = json.Unmarshal(*v, &resourceID) - if err != nil { - return err - } - peVar.ResourceID = &resourceID - } - case "policyAssignmentId": - if v != nil { - var policyAssignmentID string - err = json.Unmarshal(*v, &policyAssignmentID) - if err != nil { - return err - } - peVar.PolicyAssignmentID = &policyAssignmentID - } - case "policyDefinitionId": - if v != nil { - var policyDefinitionID string - err = json.Unmarshal(*v, &policyDefinitionID) - if err != nil { - return err - } - peVar.PolicyDefinitionID = &policyDefinitionID - } - case "effectiveParameters": - if v != nil { - var effectiveParameters string - err = json.Unmarshal(*v, &effectiveParameters) - if err != nil { - return err - } - peVar.EffectiveParameters = &effectiveParameters - } - case "isCompliant": - if v != nil { - var isCompliant bool - err = json.Unmarshal(*v, &isCompliant) - if err != nil { - return err - } - peVar.IsCompliant = &isCompliant - } - case "subscriptionId": - if v != nil { - var subscriptionID string - err = json.Unmarshal(*v, &subscriptionID) - if err != nil { - return err - } - peVar.SubscriptionID = &subscriptionID - } - case "resourceType": - if v != nil { - var resourceType string - err = json.Unmarshal(*v, &resourceType) - if err != nil { - return err - } - peVar.ResourceType = &resourceType - } - case "resourceLocation": - if v != nil { - var resourceLocation string - err = json.Unmarshal(*v, &resourceLocation) - if err != nil { - return err - } - peVar.ResourceLocation = &resourceLocation - } - case "resourceGroup": - if v != nil { - var resourceGroup string - err = json.Unmarshal(*v, &resourceGroup) - if err != nil { - return err - } - peVar.ResourceGroup = &resourceGroup - } - case "resourceTags": - if v != nil { - var resourceTags string - err = json.Unmarshal(*v, &resourceTags) - if err != nil { - return err - } - peVar.ResourceTags = &resourceTags - } - case "policyAssignmentName": - if v != nil { - var policyAssignmentName string - err = json.Unmarshal(*v, &policyAssignmentName) - if err != nil { - return err - } - peVar.PolicyAssignmentName = &policyAssignmentName - } - case "policyAssignmentOwner": - if v != nil { - var policyAssignmentOwner string - err = json.Unmarshal(*v, &policyAssignmentOwner) - if err != nil { - return err - } - peVar.PolicyAssignmentOwner = &policyAssignmentOwner - } - case "policyAssignmentParameters": - if v != nil { - var policyAssignmentParameters string - err = json.Unmarshal(*v, &policyAssignmentParameters) - if err != nil { - return err - } - peVar.PolicyAssignmentParameters = &policyAssignmentParameters - } - case "policyAssignmentScope": - if v != nil { - var policyAssignmentScope string - err = json.Unmarshal(*v, &policyAssignmentScope) - if err != nil { - return err - } - peVar.PolicyAssignmentScope = &policyAssignmentScope - } - case "policyDefinitionName": - if v != nil { - var policyDefinitionName string - err = json.Unmarshal(*v, &policyDefinitionName) - if err != nil { - return err - } - peVar.PolicyDefinitionName = &policyDefinitionName - } - case "policyDefinitionAction": - if v != nil { - var policyDefinitionAction string - err = json.Unmarshal(*v, &policyDefinitionAction) - if err != nil { - return err - } - peVar.PolicyDefinitionAction = &policyDefinitionAction - } - case "policyDefinitionCategory": - if v != nil { - var policyDefinitionCategory string - err = json.Unmarshal(*v, &policyDefinitionCategory) - if err != nil { - return err - } - peVar.PolicyDefinitionCategory = &policyDefinitionCategory - } - case "policySetDefinitionId": - if v != nil { - var policySetDefinitionID string - err = json.Unmarshal(*v, &policySetDefinitionID) - if err != nil { - return err - } - peVar.PolicySetDefinitionID = &policySetDefinitionID - } - case "policySetDefinitionName": - if v != nil { - var policySetDefinitionName string - err = json.Unmarshal(*v, &policySetDefinitionName) - if err != nil { - return err - } - peVar.PolicySetDefinitionName = &policySetDefinitionName - } - case "policySetDefinitionOwner": - if v != nil { - var policySetDefinitionOwner string - err = json.Unmarshal(*v, &policySetDefinitionOwner) - if err != nil { - return err - } - peVar.PolicySetDefinitionOwner = &policySetDefinitionOwner - } - case "policySetDefinitionCategory": - if v != nil { - var policySetDefinitionCategory string - err = json.Unmarshal(*v, &policySetDefinitionCategory) - if err != nil { - return err - } - peVar.PolicySetDefinitionCategory = &policySetDefinitionCategory - } - case "policySetDefinitionParameters": - if v != nil { - var policySetDefinitionParameters string - err = json.Unmarshal(*v, &policySetDefinitionParameters) - if err != nil { - return err - } - peVar.PolicySetDefinitionParameters = &policySetDefinitionParameters - } - case "managementGroupIds": - if v != nil { - var managementGroupIds string - err = json.Unmarshal(*v, &managementGroupIds) - if err != nil { - return err - } - peVar.ManagementGroupIds = &managementGroupIds - } - case "policyDefinitionReferenceId": - if v != nil { - var policyDefinitionReferenceID string - err = json.Unmarshal(*v, &policyDefinitionReferenceID) - if err != nil { - return err - } - peVar.PolicyDefinitionReferenceID = &policyDefinitionReferenceID - } - case "complianceState": - if v != nil { - var complianceState string - err = json.Unmarshal(*v, &complianceState) - if err != nil { - return err - } - peVar.ComplianceState = &complianceState - } - case "tenantId": - if v != nil { - var tenantID string - err = json.Unmarshal(*v, &tenantID) - if err != nil { - return err - } - peVar.TenantID = &tenantID - } - case "principalOid": - if v != nil { - var principalOid string - err = json.Unmarshal(*v, &principalOid) - if err != nil { - return err - } - peVar.PrincipalOid = &principalOid - } - case "components": - if v != nil { - var components []ComponentEventDetails - err = json.Unmarshal(*v, &components) - if err != nil { - return err - } - peVar.Components = &components - } - } - } - - return nil -} - -// PolicyEventsQueryResults query results. -type PolicyEventsQueryResults struct { - autorest.Response `json:"-"` - // OdataContext - OData context string; used by OData clients to resolve type information based on metadata. - OdataContext *string `json:"@odata.context,omitempty"` - // OdataCount - OData entity count; represents the number of policy event records returned. - OdataCount *int32 `json:"@odata.count,omitempty"` - // OdataNextLink - Odata next link; URL to get the next set of results. - OdataNextLink *string `json:"@odata.nextLink,omitempty"` - // Value - Query results. - Value *[]PolicyEvent `json:"value,omitempty"` -} - -// PolicyEventsQueryResultsIterator provides access to a complete listing of PolicyEvent values. -type PolicyEventsQueryResultsIterator struct { - i int - page PolicyEventsQueryResultsPage -} - -// NextWithContext 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 *PolicyEventsQueryResultsIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsQueryResultsIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PolicyEventsQueryResultsIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PolicyEventsQueryResultsIterator) 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 PolicyEventsQueryResultsIterator) Response() PolicyEventsQueryResults { - 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 PolicyEventsQueryResultsIterator) Value() PolicyEvent { - if !iter.page.NotDone() { - return PolicyEvent{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PolicyEventsQueryResultsIterator type. -func NewPolicyEventsQueryResultsIterator(page PolicyEventsQueryResultsPage) PolicyEventsQueryResultsIterator { - return PolicyEventsQueryResultsIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (peqr PolicyEventsQueryResults) IsEmpty() bool { - return peqr.Value == nil || len(*peqr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (peqr PolicyEventsQueryResults) hasNextLink() bool { - return peqr.OdataNextLink != nil && len(*peqr.OdataNextLink) != 0 -} - -// policyEventsQueryResultsPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (peqr PolicyEventsQueryResults) policyEventsQueryResultsPreparer(ctx context.Context) (*http.Request, error) { - if !peqr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(peqr.OdataNextLink))) -} - -// PolicyEventsQueryResultsPage contains a page of PolicyEvent values. -type PolicyEventsQueryResultsPage struct { - fn func(context.Context, PolicyEventsQueryResults) (PolicyEventsQueryResults, error) - peqr PolicyEventsQueryResults -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PolicyEventsQueryResultsPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsQueryResultsPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.peqr) - if err != nil { - return err - } - page.peqr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PolicyEventsQueryResultsPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PolicyEventsQueryResultsPage) NotDone() bool { - return !page.peqr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PolicyEventsQueryResultsPage) Response() PolicyEventsQueryResults { - return page.peqr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PolicyEventsQueryResultsPage) Values() []PolicyEvent { - if page.peqr.IsEmpty() { - return nil - } - return *page.peqr.Value -} - -// Creates a new instance of the PolicyEventsQueryResultsPage type. -func NewPolicyEventsQueryResultsPage(cur PolicyEventsQueryResults, getNextPage func(context.Context, PolicyEventsQueryResults) (PolicyEventsQueryResults, error)) PolicyEventsQueryResultsPage { - return PolicyEventsQueryResultsPage{ - fn: getNextPage, - peqr: cur, - } -} - -// PolicyGroupSummary policy definition group summary. -type PolicyGroupSummary struct { - // PolicyGroupName - Policy group name. - PolicyGroupName *string `json:"policyGroupName,omitempty"` - // Results - Compliance summary for the policy definition group. - Results *SummaryResults `json:"results,omitempty"` -} - -// PolicyMetadata policy metadata resource definition. -type PolicyMetadata struct { - autorest.Response `json:"-"` - // PolicyMetadataProperties - Properties of the policy metadata. - *PolicyMetadataProperties `json:"properties,omitempty"` - // ID - READ-ONLY; The ID of the policy metadata. - ID *string `json:"id,omitempty"` - // Type - READ-ONLY; The type of the policy metadata. - Type *string `json:"type,omitempty"` - // Name - READ-ONLY; The name of the policy metadata. - Name *string `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for PolicyMetadata. -func (pm PolicyMetadata) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pm.PolicyMetadataProperties != nil { - objectMap["properties"] = pm.PolicyMetadataProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PolicyMetadata struct. -func (pm *PolicyMetadata) 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 policyMetadataProperties PolicyMetadataProperties - err = json.Unmarshal(*v, &policyMetadataProperties) - if err != nil { - return err - } - pm.PolicyMetadataProperties = &policyMetadataProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pm.ID = &ID - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pm.Type = &typeVar - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pm.Name = &name - } - } - } - - return nil -} - -// PolicyMetadataCollection collection of policy metadata resources. -type PolicyMetadataCollection struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; Array of policy metadata definitions. - Value *[]SlimPolicyMetadata `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for PolicyMetadataCollection. -func (pmc PolicyMetadataCollection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PolicyMetadataCollectionIterator provides access to a complete listing of SlimPolicyMetadata values. -type PolicyMetadataCollectionIterator struct { - i int - page PolicyMetadataCollectionPage -} - -// NextWithContext 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 *PolicyMetadataCollectionIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyMetadataCollectionIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PolicyMetadataCollectionIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PolicyMetadataCollectionIterator) 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 PolicyMetadataCollectionIterator) Response() PolicyMetadataCollection { - 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 PolicyMetadataCollectionIterator) Value() SlimPolicyMetadata { - if !iter.page.NotDone() { - return SlimPolicyMetadata{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PolicyMetadataCollectionIterator type. -func NewPolicyMetadataCollectionIterator(page PolicyMetadataCollectionPage) PolicyMetadataCollectionIterator { - return PolicyMetadataCollectionIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (pmc PolicyMetadataCollection) IsEmpty() bool { - return pmc.Value == nil || len(*pmc.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (pmc PolicyMetadataCollection) hasNextLink() bool { - return pmc.NextLink != nil && len(*pmc.NextLink) != 0 -} - -// policyMetadataCollectionPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (pmc PolicyMetadataCollection) policyMetadataCollectionPreparer(ctx context.Context) (*http.Request, error) { - if !pmc.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(pmc.NextLink))) -} - -// PolicyMetadataCollectionPage contains a page of SlimPolicyMetadata values. -type PolicyMetadataCollectionPage struct { - fn func(context.Context, PolicyMetadataCollection) (PolicyMetadataCollection, error) - pmc PolicyMetadataCollection -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PolicyMetadataCollectionPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyMetadataCollectionPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.pmc) - if err != nil { - return err - } - page.pmc = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PolicyMetadataCollectionPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PolicyMetadataCollectionPage) NotDone() bool { - return !page.pmc.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PolicyMetadataCollectionPage) Response() PolicyMetadataCollection { - return page.pmc -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PolicyMetadataCollectionPage) Values() []SlimPolicyMetadata { - if page.pmc.IsEmpty() { - return nil - } - return *page.pmc.Value -} - -// Creates a new instance of the PolicyMetadataCollectionPage type. -func NewPolicyMetadataCollectionPage(cur PolicyMetadataCollection, getNextPage func(context.Context, PolicyMetadataCollection) (PolicyMetadataCollection, error)) PolicyMetadataCollectionPage { - return PolicyMetadataCollectionPage{ - fn: getNextPage, - pmc: cur, - } -} - -// PolicyMetadataProperties the properties of the policy metadata. -type PolicyMetadataProperties struct { - // Description - READ-ONLY; The description of the policy metadata. - Description *string `json:"description,omitempty"` - // Requirements - READ-ONLY; The requirements of the policy metadata. - Requirements *string `json:"requirements,omitempty"` - // MetadataID - READ-ONLY; The policy metadata identifier. - MetadataID *string `json:"metadataId,omitempty"` - // Category - READ-ONLY; The category of the policy metadata. - Category *string `json:"category,omitempty"` - // Title - READ-ONLY; The title of the policy metadata. - Title *string `json:"title,omitempty"` - // Owner - READ-ONLY; The owner of the policy metadata. - Owner *string `json:"owner,omitempty"` - // AdditionalContentURL - READ-ONLY; Url for getting additional content about the resource metadata. - AdditionalContentURL *string `json:"additionalContentUrl,omitempty"` - // Metadata - READ-ONLY; Additional metadata. - Metadata interface{} `json:"metadata,omitempty"` -} - -// MarshalJSON is the custom marshaler for PolicyMetadataProperties. -func (pmp PolicyMetadataProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PolicyMetadataSlimProperties the properties of the policy metadata, excluding properties containing -// large strings -type PolicyMetadataSlimProperties struct { - // MetadataID - READ-ONLY; The policy metadata identifier. - MetadataID *string `json:"metadataId,omitempty"` - // Category - READ-ONLY; The category of the policy metadata. - Category *string `json:"category,omitempty"` - // Title - READ-ONLY; The title of the policy metadata. - Title *string `json:"title,omitempty"` - // Owner - READ-ONLY; The owner of the policy metadata. - Owner *string `json:"owner,omitempty"` - // AdditionalContentURL - READ-ONLY; Url for getting additional content about the resource metadata. - AdditionalContentURL *string `json:"additionalContentUrl,omitempty"` - // Metadata - READ-ONLY; Additional metadata. - Metadata interface{} `json:"metadata,omitempty"` -} - -// MarshalJSON is the custom marshaler for PolicyMetadataSlimProperties. -func (pmsp PolicyMetadataSlimProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PolicyState policy state record. -type PolicyState struct { - // AdditionalProperties - Unmatched properties from the message are deserialized this collection - AdditionalProperties map[string]interface{} `json:""` - // OdataID - OData entity ID; always set to null since policy state records do not have an entity ID. - OdataID *string `json:"@odata.id,omitempty"` - // OdataContext - OData context string; used by OData clients to resolve type information based on metadata. - OdataContext *string `json:"@odata.context,omitempty"` - // Timestamp - Timestamp for the policy state record. - Timestamp *date.Time `json:"timestamp,omitempty"` - // ResourceID - Resource ID. - ResourceID *string `json:"resourceId,omitempty"` - // PolicyAssignmentID - Policy assignment ID. - PolicyAssignmentID *string `json:"policyAssignmentId,omitempty"` - // PolicyDefinitionID - Policy definition ID. - PolicyDefinitionID *string `json:"policyDefinitionId,omitempty"` - // EffectiveParameters - Effective parameters for the policy assignment. - EffectiveParameters *string `json:"effectiveParameters,omitempty"` - // IsCompliant - Flag which states whether the resource is compliant against the policy assignment it was evaluated against. This property is deprecated; please use ComplianceState instead. - IsCompliant *bool `json:"isCompliant,omitempty"` - // SubscriptionID - Subscription ID. - SubscriptionID *string `json:"subscriptionId,omitempty"` - // ResourceType - Resource type. - ResourceType *string `json:"resourceType,omitempty"` - // ResourceLocation - Resource location. - ResourceLocation *string `json:"resourceLocation,omitempty"` - // ResourceGroup - Resource group name. - ResourceGroup *string `json:"resourceGroup,omitempty"` - // ResourceTags - List of resource tags. - ResourceTags *string `json:"resourceTags,omitempty"` - // PolicyAssignmentName - Policy assignment name. - PolicyAssignmentName *string `json:"policyAssignmentName,omitempty"` - // PolicyAssignmentOwner - Policy assignment owner. - PolicyAssignmentOwner *string `json:"policyAssignmentOwner,omitempty"` - // PolicyAssignmentParameters - Policy assignment parameters. - PolicyAssignmentParameters *string `json:"policyAssignmentParameters,omitempty"` - // PolicyAssignmentScope - Policy assignment scope. - PolicyAssignmentScope *string `json:"policyAssignmentScope,omitempty"` - // PolicyDefinitionName - Policy definition name. - PolicyDefinitionName *string `json:"policyDefinitionName,omitempty"` - // PolicyDefinitionAction - Policy definition action, i.e. effect. - PolicyDefinitionAction *string `json:"policyDefinitionAction,omitempty"` - // PolicyDefinitionCategory - Policy definition category. - PolicyDefinitionCategory *string `json:"policyDefinitionCategory,omitempty"` - // PolicySetDefinitionID - Policy set definition ID, if the policy assignment is for a policy set. - PolicySetDefinitionID *string `json:"policySetDefinitionId,omitempty"` - // PolicySetDefinitionName - Policy set definition name, if the policy assignment is for a policy set. - PolicySetDefinitionName *string `json:"policySetDefinitionName,omitempty"` - // PolicySetDefinitionOwner - Policy set definition owner, if the policy assignment is for a policy set. - PolicySetDefinitionOwner *string `json:"policySetDefinitionOwner,omitempty"` - // PolicySetDefinitionCategory - Policy set definition category, if the policy assignment is for a policy set. - PolicySetDefinitionCategory *string `json:"policySetDefinitionCategory,omitempty"` - // PolicySetDefinitionParameters - Policy set definition parameters, if the policy assignment is for a policy set. - PolicySetDefinitionParameters *string `json:"policySetDefinitionParameters,omitempty"` - // ManagementGroupIds - Comma separated list of management group IDs, which represent the hierarchy of the management groups the resource is under. - ManagementGroupIds *string `json:"managementGroupIds,omitempty"` - // PolicyDefinitionReferenceID - Reference ID for the policy definition inside the policy set, if the policy assignment is for a policy set. - PolicyDefinitionReferenceID *string `json:"policyDefinitionReferenceId,omitempty"` - // ComplianceState - Compliance state of the resource. - ComplianceState *string `json:"complianceState,omitempty"` - // PolicyEvaluationDetails - Policy evaluation details. - PolicyEvaluationDetails *PolicyEvaluationDetails `json:"policyEvaluationDetails,omitempty"` - // PolicyDefinitionGroupNames - Policy definition group names. - PolicyDefinitionGroupNames *[]string `json:"policyDefinitionGroupNames,omitempty"` - // Components - Components state compliance records populated only when URL contains $expand=components clause. - Components *[]ComponentStateDetails `json:"components,omitempty"` - // PolicyDefinitionVersion - READ-ONLY; Evaluated policy definition version. - PolicyDefinitionVersion *string `json:"policyDefinitionVersion,omitempty"` - // PolicySetDefinitionVersion - READ-ONLY; Evaluated policy set definition version. - PolicySetDefinitionVersion *string `json:"policySetDefinitionVersion,omitempty"` - // PolicyAssignmentVersion - READ-ONLY; Evaluated policy assignment version. - PolicyAssignmentVersion *string `json:"policyAssignmentVersion,omitempty"` -} - -// MarshalJSON is the custom marshaler for PolicyState. -func (ps PolicyState) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ps.OdataID != nil { - objectMap["@odata.id"] = ps.OdataID - } - if ps.OdataContext != nil { - objectMap["@odata.context"] = ps.OdataContext - } - if ps.Timestamp != nil { - objectMap["timestamp"] = ps.Timestamp - } - if ps.ResourceID != nil { - objectMap["resourceId"] = ps.ResourceID - } - if ps.PolicyAssignmentID != nil { - objectMap["policyAssignmentId"] = ps.PolicyAssignmentID - } - if ps.PolicyDefinitionID != nil { - objectMap["policyDefinitionId"] = ps.PolicyDefinitionID - } - if ps.EffectiveParameters != nil { - objectMap["effectiveParameters"] = ps.EffectiveParameters - } - if ps.IsCompliant != nil { - objectMap["isCompliant"] = ps.IsCompliant - } - if ps.SubscriptionID != nil { - objectMap["subscriptionId"] = ps.SubscriptionID - } - if ps.ResourceType != nil { - objectMap["resourceType"] = ps.ResourceType - } - if ps.ResourceLocation != nil { - objectMap["resourceLocation"] = ps.ResourceLocation - } - if ps.ResourceGroup != nil { - objectMap["resourceGroup"] = ps.ResourceGroup - } - if ps.ResourceTags != nil { - objectMap["resourceTags"] = ps.ResourceTags - } - if ps.PolicyAssignmentName != nil { - objectMap["policyAssignmentName"] = ps.PolicyAssignmentName - } - if ps.PolicyAssignmentOwner != nil { - objectMap["policyAssignmentOwner"] = ps.PolicyAssignmentOwner - } - if ps.PolicyAssignmentParameters != nil { - objectMap["policyAssignmentParameters"] = ps.PolicyAssignmentParameters - } - if ps.PolicyAssignmentScope != nil { - objectMap["policyAssignmentScope"] = ps.PolicyAssignmentScope - } - if ps.PolicyDefinitionName != nil { - objectMap["policyDefinitionName"] = ps.PolicyDefinitionName - } - if ps.PolicyDefinitionAction != nil { - objectMap["policyDefinitionAction"] = ps.PolicyDefinitionAction - } - if ps.PolicyDefinitionCategory != nil { - objectMap["policyDefinitionCategory"] = ps.PolicyDefinitionCategory - } - if ps.PolicySetDefinitionID != nil { - objectMap["policySetDefinitionId"] = ps.PolicySetDefinitionID - } - if ps.PolicySetDefinitionName != nil { - objectMap["policySetDefinitionName"] = ps.PolicySetDefinitionName - } - if ps.PolicySetDefinitionOwner != nil { - objectMap["policySetDefinitionOwner"] = ps.PolicySetDefinitionOwner - } - if ps.PolicySetDefinitionCategory != nil { - objectMap["policySetDefinitionCategory"] = ps.PolicySetDefinitionCategory - } - if ps.PolicySetDefinitionParameters != nil { - objectMap["policySetDefinitionParameters"] = ps.PolicySetDefinitionParameters - } - if ps.ManagementGroupIds != nil { - objectMap["managementGroupIds"] = ps.ManagementGroupIds - } - if ps.PolicyDefinitionReferenceID != nil { - objectMap["policyDefinitionReferenceId"] = ps.PolicyDefinitionReferenceID - } - if ps.ComplianceState != nil { - objectMap["complianceState"] = ps.ComplianceState - } - if ps.PolicyEvaluationDetails != nil { - objectMap["policyEvaluationDetails"] = ps.PolicyEvaluationDetails - } - if ps.PolicyDefinitionGroupNames != nil { - objectMap["policyDefinitionGroupNames"] = ps.PolicyDefinitionGroupNames - } - if ps.Components != nil { - objectMap["components"] = ps.Components - } - for k, v := range ps.AdditionalProperties { - objectMap[k] = v - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PolicyState struct. -func (ps *PolicyState) 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 { - default: - if v != nil { - var additionalProperties interface{} - err = json.Unmarshal(*v, &additionalProperties) - if err != nil { - return err - } - if ps.AdditionalProperties == nil { - ps.AdditionalProperties = make(map[string]interface{}) - } - ps.AdditionalProperties[k] = additionalProperties - } - case "@odata.id": - if v != nil { - var odataID string - err = json.Unmarshal(*v, &odataID) - if err != nil { - return err - } - ps.OdataID = &odataID - } - case "@odata.context": - if v != nil { - var odataContext string - err = json.Unmarshal(*v, &odataContext) - if err != nil { - return err - } - ps.OdataContext = &odataContext - } - case "timestamp": - if v != nil { - var timestamp date.Time - err = json.Unmarshal(*v, ×tamp) - if err != nil { - return err - } - ps.Timestamp = ×tamp - } - case "resourceId": - if v != nil { - var resourceID string - err = json.Unmarshal(*v, &resourceID) - if err != nil { - return err - } - ps.ResourceID = &resourceID - } - case "policyAssignmentId": - if v != nil { - var policyAssignmentID string - err = json.Unmarshal(*v, &policyAssignmentID) - if err != nil { - return err - } - ps.PolicyAssignmentID = &policyAssignmentID - } - case "policyDefinitionId": - if v != nil { - var policyDefinitionID string - err = json.Unmarshal(*v, &policyDefinitionID) - if err != nil { - return err - } - ps.PolicyDefinitionID = &policyDefinitionID - } - case "effectiveParameters": - if v != nil { - var effectiveParameters string - err = json.Unmarshal(*v, &effectiveParameters) - if err != nil { - return err - } - ps.EffectiveParameters = &effectiveParameters - } - case "isCompliant": - if v != nil { - var isCompliant bool - err = json.Unmarshal(*v, &isCompliant) - if err != nil { - return err - } - ps.IsCompliant = &isCompliant - } - case "subscriptionId": - if v != nil { - var subscriptionID string - err = json.Unmarshal(*v, &subscriptionID) - if err != nil { - return err - } - ps.SubscriptionID = &subscriptionID - } - case "resourceType": - if v != nil { - var resourceType string - err = json.Unmarshal(*v, &resourceType) - if err != nil { - return err - } - ps.ResourceType = &resourceType - } - case "resourceLocation": - if v != nil { - var resourceLocation string - err = json.Unmarshal(*v, &resourceLocation) - if err != nil { - return err - } - ps.ResourceLocation = &resourceLocation - } - case "resourceGroup": - if v != nil { - var resourceGroup string - err = json.Unmarshal(*v, &resourceGroup) - if err != nil { - return err - } - ps.ResourceGroup = &resourceGroup - } - case "resourceTags": - if v != nil { - var resourceTags string - err = json.Unmarshal(*v, &resourceTags) - if err != nil { - return err - } - ps.ResourceTags = &resourceTags - } - case "policyAssignmentName": - if v != nil { - var policyAssignmentName string - err = json.Unmarshal(*v, &policyAssignmentName) - if err != nil { - return err - } - ps.PolicyAssignmentName = &policyAssignmentName - } - case "policyAssignmentOwner": - if v != nil { - var policyAssignmentOwner string - err = json.Unmarshal(*v, &policyAssignmentOwner) - if err != nil { - return err - } - ps.PolicyAssignmentOwner = &policyAssignmentOwner - } - case "policyAssignmentParameters": - if v != nil { - var policyAssignmentParameters string - err = json.Unmarshal(*v, &policyAssignmentParameters) - if err != nil { - return err - } - ps.PolicyAssignmentParameters = &policyAssignmentParameters - } - case "policyAssignmentScope": - if v != nil { - var policyAssignmentScope string - err = json.Unmarshal(*v, &policyAssignmentScope) - if err != nil { - return err - } - ps.PolicyAssignmentScope = &policyAssignmentScope - } - case "policyDefinitionName": - if v != nil { - var policyDefinitionName string - err = json.Unmarshal(*v, &policyDefinitionName) - if err != nil { - return err - } - ps.PolicyDefinitionName = &policyDefinitionName - } - case "policyDefinitionAction": - if v != nil { - var policyDefinitionAction string - err = json.Unmarshal(*v, &policyDefinitionAction) - if err != nil { - return err - } - ps.PolicyDefinitionAction = &policyDefinitionAction - } - case "policyDefinitionCategory": - if v != nil { - var policyDefinitionCategory string - err = json.Unmarshal(*v, &policyDefinitionCategory) - if err != nil { - return err - } - ps.PolicyDefinitionCategory = &policyDefinitionCategory - } - case "policySetDefinitionId": - if v != nil { - var policySetDefinitionID string - err = json.Unmarshal(*v, &policySetDefinitionID) - if err != nil { - return err - } - ps.PolicySetDefinitionID = &policySetDefinitionID - } - case "policySetDefinitionName": - if v != nil { - var policySetDefinitionName string - err = json.Unmarshal(*v, &policySetDefinitionName) - if err != nil { - return err - } - ps.PolicySetDefinitionName = &policySetDefinitionName - } - case "policySetDefinitionOwner": - if v != nil { - var policySetDefinitionOwner string - err = json.Unmarshal(*v, &policySetDefinitionOwner) - if err != nil { - return err - } - ps.PolicySetDefinitionOwner = &policySetDefinitionOwner - } - case "policySetDefinitionCategory": - if v != nil { - var policySetDefinitionCategory string - err = json.Unmarshal(*v, &policySetDefinitionCategory) - if err != nil { - return err - } - ps.PolicySetDefinitionCategory = &policySetDefinitionCategory - } - case "policySetDefinitionParameters": - if v != nil { - var policySetDefinitionParameters string - err = json.Unmarshal(*v, &policySetDefinitionParameters) - if err != nil { - return err - } - ps.PolicySetDefinitionParameters = &policySetDefinitionParameters - } - case "managementGroupIds": - if v != nil { - var managementGroupIds string - err = json.Unmarshal(*v, &managementGroupIds) - if err != nil { - return err - } - ps.ManagementGroupIds = &managementGroupIds - } - case "policyDefinitionReferenceId": - if v != nil { - var policyDefinitionReferenceID string - err = json.Unmarshal(*v, &policyDefinitionReferenceID) - if err != nil { - return err - } - ps.PolicyDefinitionReferenceID = &policyDefinitionReferenceID - } - case "complianceState": - if v != nil { - var complianceState string - err = json.Unmarshal(*v, &complianceState) - if err != nil { - return err - } - ps.ComplianceState = &complianceState - } - case "policyEvaluationDetails": - if v != nil { - var policyEvaluationDetails PolicyEvaluationDetails - err = json.Unmarshal(*v, &policyEvaluationDetails) - if err != nil { - return err - } - ps.PolicyEvaluationDetails = &policyEvaluationDetails - } - case "policyDefinitionGroupNames": - if v != nil { - var policyDefinitionGroupNames []string - err = json.Unmarshal(*v, &policyDefinitionGroupNames) - if err != nil { - return err - } - ps.PolicyDefinitionGroupNames = &policyDefinitionGroupNames - } - case "components": - if v != nil { - var components []ComponentStateDetails - err = json.Unmarshal(*v, &components) - if err != nil { - return err - } - ps.Components = &components - } - case "policyDefinitionVersion": - if v != nil { - var policyDefinitionVersion string - err = json.Unmarshal(*v, &policyDefinitionVersion) - if err != nil { - return err - } - ps.PolicyDefinitionVersion = &policyDefinitionVersion - } - case "policySetDefinitionVersion": - if v != nil { - var policySetDefinitionVersion string - err = json.Unmarshal(*v, &policySetDefinitionVersion) - if err != nil { - return err - } - ps.PolicySetDefinitionVersion = &policySetDefinitionVersion - } - case "policyAssignmentVersion": - if v != nil { - var policyAssignmentVersion string - err = json.Unmarshal(*v, &policyAssignmentVersion) - if err != nil { - return err - } - ps.PolicyAssignmentVersion = &policyAssignmentVersion - } - } - } - - return nil -} - -// PolicyStatesQueryResults query results. -type PolicyStatesQueryResults struct { - autorest.Response `json:"-"` - // OdataContext - OData context string; used by OData clients to resolve type information based on metadata. - OdataContext *string `json:"@odata.context,omitempty"` - // OdataCount - OData entity count; represents the number of policy state records returned. - OdataCount *int32 `json:"@odata.count,omitempty"` - // OdataNextLink - Odata next link; URL to get the next set of results. - OdataNextLink *string `json:"@odata.nextLink,omitempty"` - // Value - Query results. - Value *[]PolicyState `json:"value,omitempty"` -} - -// PolicyStatesQueryResultsIterator provides access to a complete listing of PolicyState values. -type PolicyStatesQueryResultsIterator struct { - i int - page PolicyStatesQueryResultsPage -} - -// NextWithContext 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 *PolicyStatesQueryResultsIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesQueryResultsIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PolicyStatesQueryResultsIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PolicyStatesQueryResultsIterator) 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 PolicyStatesQueryResultsIterator) Response() PolicyStatesQueryResults { - 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 PolicyStatesQueryResultsIterator) Value() PolicyState { - if !iter.page.NotDone() { - return PolicyState{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PolicyStatesQueryResultsIterator type. -func NewPolicyStatesQueryResultsIterator(page PolicyStatesQueryResultsPage) PolicyStatesQueryResultsIterator { - return PolicyStatesQueryResultsIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (psqr PolicyStatesQueryResults) IsEmpty() bool { - return psqr.Value == nil || len(*psqr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (psqr PolicyStatesQueryResults) hasNextLink() bool { - return psqr.OdataNextLink != nil && len(*psqr.OdataNextLink) != 0 -} - -// policyStatesQueryResultsPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (psqr PolicyStatesQueryResults) policyStatesQueryResultsPreparer(ctx context.Context) (*http.Request, error) { - if !psqr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(psqr.OdataNextLink))) -} - -// PolicyStatesQueryResultsPage contains a page of PolicyState values. -type PolicyStatesQueryResultsPage struct { - fn func(context.Context, PolicyStatesQueryResults) (PolicyStatesQueryResults, error) - psqr PolicyStatesQueryResults -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PolicyStatesQueryResultsPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesQueryResultsPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.psqr) - if err != nil { - return err - } - page.psqr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PolicyStatesQueryResultsPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PolicyStatesQueryResultsPage) NotDone() bool { - return !page.psqr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PolicyStatesQueryResultsPage) Response() PolicyStatesQueryResults { - return page.psqr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PolicyStatesQueryResultsPage) Values() []PolicyState { - if page.psqr.IsEmpty() { - return nil - } - return *page.psqr.Value -} - -// Creates a new instance of the PolicyStatesQueryResultsPage type. -func NewPolicyStatesQueryResultsPage(cur PolicyStatesQueryResults, getNextPage func(context.Context, PolicyStatesQueryResults) (PolicyStatesQueryResults, error)) PolicyStatesQueryResultsPage { - return PolicyStatesQueryResultsPage{ - fn: getNextPage, - psqr: cur, - } -} - -// PolicyStatesTriggerResourceGroupEvaluationFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type PolicyStatesTriggerResourceGroupEvaluationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PolicyStatesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PolicyStatesTriggerResourceGroupEvaluationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PolicyStatesTriggerResourceGroupEvaluationFuture.Result. -func (future *PolicyStatesTriggerResourceGroupEvaluationFuture) result(client PolicyStatesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesTriggerResourceGroupEvaluationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("policyinsights.PolicyStatesTriggerResourceGroupEvaluationFuture") - return - } - ar.Response = future.Response() - return -} - -// PolicyStatesTriggerSubscriptionEvaluationFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type PolicyStatesTriggerSubscriptionEvaluationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PolicyStatesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PolicyStatesTriggerSubscriptionEvaluationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PolicyStatesTriggerSubscriptionEvaluationFuture.Result. -func (future *PolicyStatesTriggerSubscriptionEvaluationFuture) result(client PolicyStatesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesTriggerSubscriptionEvaluationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("policyinsights.PolicyStatesTriggerSubscriptionEvaluationFuture") - return - } - ar.Response = future.Response() - return -} - -// PolicyTrackedResource policy tracked resource record. -type PolicyTrackedResource struct { - // TrackedResourceID - READ-ONLY; The ID of the policy tracked resource. - TrackedResourceID *string `json:"trackedResourceId,omitempty"` - // PolicyDetails - READ-ONLY; The details of the policy that require the tracked resource. - PolicyDetails *PolicyDetails `json:"policyDetails,omitempty"` - // CreatedBy - READ-ONLY; The details of the policy triggered deployment that created the tracked resource. - CreatedBy *TrackedResourceModificationDetails `json:"createdBy,omitempty"` - // LastModifiedBy - READ-ONLY; The details of the policy triggered deployment that modified the tracked resource. - LastModifiedBy *TrackedResourceModificationDetails `json:"lastModifiedBy,omitempty"` - // LastUpdateUtc - READ-ONLY; Timestamp of the last update to the tracked resource. - LastUpdateUtc *date.Time `json:"lastUpdateUtc,omitempty"` -} - -// MarshalJSON is the custom marshaler for PolicyTrackedResource. -func (ptr PolicyTrackedResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PolicyTrackedResourcesQueryResults query results. -type PolicyTrackedResourcesQueryResults struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; Query results. - Value *[]PolicyTrackedResource `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for PolicyTrackedResourcesQueryResults. -func (ptrqr PolicyTrackedResourcesQueryResults) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PolicyTrackedResourcesQueryResultsIterator provides access to a complete listing of -// PolicyTrackedResource values. -type PolicyTrackedResourcesQueryResultsIterator struct { - i int - page PolicyTrackedResourcesQueryResultsPage -} - -// NextWithContext 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 *PolicyTrackedResourcesQueryResultsIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesQueryResultsIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PolicyTrackedResourcesQueryResultsIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PolicyTrackedResourcesQueryResultsIterator) 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 PolicyTrackedResourcesQueryResultsIterator) Response() PolicyTrackedResourcesQueryResults { - 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 PolicyTrackedResourcesQueryResultsIterator) Value() PolicyTrackedResource { - if !iter.page.NotDone() { - return PolicyTrackedResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PolicyTrackedResourcesQueryResultsIterator type. -func NewPolicyTrackedResourcesQueryResultsIterator(page PolicyTrackedResourcesQueryResultsPage) PolicyTrackedResourcesQueryResultsIterator { - return PolicyTrackedResourcesQueryResultsIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ptrqr PolicyTrackedResourcesQueryResults) IsEmpty() bool { - return ptrqr.Value == nil || len(*ptrqr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ptrqr PolicyTrackedResourcesQueryResults) hasNextLink() bool { - return ptrqr.NextLink != nil && len(*ptrqr.NextLink) != 0 -} - -// policyTrackedResourcesQueryResultsPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ptrqr PolicyTrackedResourcesQueryResults) policyTrackedResourcesQueryResultsPreparer(ctx context.Context) (*http.Request, error) { - if !ptrqr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ptrqr.NextLink))) -} - -// PolicyTrackedResourcesQueryResultsPage contains a page of PolicyTrackedResource values. -type PolicyTrackedResourcesQueryResultsPage struct { - fn func(context.Context, PolicyTrackedResourcesQueryResults) (PolicyTrackedResourcesQueryResults, error) - ptrqr PolicyTrackedResourcesQueryResults -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PolicyTrackedResourcesQueryResultsPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesQueryResultsPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ptrqr) - if err != nil { - return err - } - page.ptrqr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PolicyTrackedResourcesQueryResultsPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PolicyTrackedResourcesQueryResultsPage) NotDone() bool { - return !page.ptrqr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PolicyTrackedResourcesQueryResultsPage) Response() PolicyTrackedResourcesQueryResults { - return page.ptrqr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PolicyTrackedResourcesQueryResultsPage) Values() []PolicyTrackedResource { - if page.ptrqr.IsEmpty() { - return nil - } - return *page.ptrqr.Value -} - -// Creates a new instance of the PolicyTrackedResourcesQueryResultsPage type. -func NewPolicyTrackedResourcesQueryResultsPage(cur PolicyTrackedResourcesQueryResults, getNextPage func(context.Context, PolicyTrackedResourcesQueryResults) (PolicyTrackedResourcesQueryResults, error)) PolicyTrackedResourcesQueryResultsPage { - return PolicyTrackedResourcesQueryResultsPage{ - fn: getNextPage, - ptrqr: cur, - } -} - -// QueryFailure error response. -type QueryFailure struct { - // Error - Error definition. - Error *QueryFailureError `json:"error,omitempty"` -} - -// QueryFailureError error definition. -type QueryFailureError struct { - // Code - READ-ONLY; Service specific error code which serves as the substatus for the HTTP error code. - Code *string `json:"code,omitempty"` - // Message - READ-ONLY; Description of the error. - Message *string `json:"message,omitempty"` -} - -// MarshalJSON is the custom marshaler for QueryFailureError. -func (qf QueryFailureError) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Remediation the remediation definition. -type Remediation struct { - autorest.Response `json:"-"` - // RemediationProperties - Properties for the remediation. - *RemediationProperties `json:"properties,omitempty"` - // ID - READ-ONLY; The ID of the remediation. - ID *string `json:"id,omitempty"` - // Type - READ-ONLY; The type of the remediation. - Type *string `json:"type,omitempty"` - // Name - READ-ONLY; The name of the remediation. - Name *string `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for Remediation. -func (r Remediation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.RemediationProperties != nil { - objectMap["properties"] = r.RemediationProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Remediation struct. -func (r *Remediation) 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 remediationProperties RemediationProperties - err = json.Unmarshal(*v, &remediationProperties) - if err != nil { - return err - } - r.RemediationProperties = &remediationProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - r.ID = &ID - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - r.Type = &typeVar - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - r.Name = &name - } - } - } - - return nil -} - -// RemediationDeployment details of a single deployment created by the remediation. -type RemediationDeployment struct { - // RemediatedResourceID - READ-ONLY; Resource ID of the resource that is being remediated by the deployment. - RemediatedResourceID *string `json:"remediatedResourceId,omitempty"` - // DeploymentID - READ-ONLY; Resource ID of the template deployment that will remediate the resource. - DeploymentID *string `json:"deploymentId,omitempty"` - // Status - READ-ONLY; Status of the remediation deployment. - Status *string `json:"status,omitempty"` - // ResourceLocation - READ-ONLY; Location of the resource that is being remediated. - ResourceLocation *string `json:"resourceLocation,omitempty"` - // Error - READ-ONLY; Error encountered while remediated the resource. - Error *ErrorDefinition `json:"error,omitempty"` - // CreatedOn - READ-ONLY; The time at which the remediation was created. - CreatedOn *date.Time `json:"createdOn,omitempty"` - // LastUpdatedOn - READ-ONLY; The time at which the remediation deployment was last updated. - LastUpdatedOn *date.Time `json:"lastUpdatedOn,omitempty"` -} - -// MarshalJSON is the custom marshaler for RemediationDeployment. -func (rd RemediationDeployment) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RemediationDeploymentsListResult list of deployments for a remediation. -type RemediationDeploymentsListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; Array of deployments for the remediation. - Value *[]RemediationDeployment `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for RemediationDeploymentsListResult. -func (rdlr RemediationDeploymentsListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RemediationDeploymentsListResultIterator provides access to a complete listing of RemediationDeployment -// values. -type RemediationDeploymentsListResultIterator struct { - i int - page RemediationDeploymentsListResultPage -} - -// NextWithContext 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 *RemediationDeploymentsListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationDeploymentsListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RemediationDeploymentsListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RemediationDeploymentsListResultIterator) 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 RemediationDeploymentsListResultIterator) Response() RemediationDeploymentsListResult { - 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 RemediationDeploymentsListResultIterator) Value() RemediationDeployment { - if !iter.page.NotDone() { - return RemediationDeployment{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RemediationDeploymentsListResultIterator type. -func NewRemediationDeploymentsListResultIterator(page RemediationDeploymentsListResultPage) RemediationDeploymentsListResultIterator { - return RemediationDeploymentsListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rdlr RemediationDeploymentsListResult) IsEmpty() bool { - return rdlr.Value == nil || len(*rdlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rdlr RemediationDeploymentsListResult) hasNextLink() bool { - return rdlr.NextLink != nil && len(*rdlr.NextLink) != 0 -} - -// remediationDeploymentsListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rdlr RemediationDeploymentsListResult) remediationDeploymentsListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rdlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rdlr.NextLink))) -} - -// RemediationDeploymentsListResultPage contains a page of RemediationDeployment values. -type RemediationDeploymentsListResultPage struct { - fn func(context.Context, RemediationDeploymentsListResult) (RemediationDeploymentsListResult, error) - rdlr RemediationDeploymentsListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RemediationDeploymentsListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationDeploymentsListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rdlr) - if err != nil { - return err - } - page.rdlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RemediationDeploymentsListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RemediationDeploymentsListResultPage) NotDone() bool { - return !page.rdlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RemediationDeploymentsListResultPage) Response() RemediationDeploymentsListResult { - return page.rdlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RemediationDeploymentsListResultPage) Values() []RemediationDeployment { - if page.rdlr.IsEmpty() { - return nil - } - return *page.rdlr.Value -} - -// Creates a new instance of the RemediationDeploymentsListResultPage type. -func NewRemediationDeploymentsListResultPage(cur RemediationDeploymentsListResult, getNextPage func(context.Context, RemediationDeploymentsListResult) (RemediationDeploymentsListResult, error)) RemediationDeploymentsListResultPage { - return RemediationDeploymentsListResultPage{ - fn: getNextPage, - rdlr: cur, - } -} - -// RemediationDeploymentSummary the deployment status summary for all deployments created by the -// remediation. -type RemediationDeploymentSummary struct { - // TotalDeployments - READ-ONLY; The number of deployments required by the remediation. - TotalDeployments *int32 `json:"totalDeployments,omitempty"` - // SuccessfulDeployments - READ-ONLY; The number of deployments required by the remediation that have succeeded. - SuccessfulDeployments *int32 `json:"successfulDeployments,omitempty"` - // FailedDeployments - READ-ONLY; The number of deployments required by the remediation that have failed. - FailedDeployments *int32 `json:"failedDeployments,omitempty"` -} - -// MarshalJSON is the custom marshaler for RemediationDeploymentSummary. -func (rds RemediationDeploymentSummary) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RemediationFilters the filters that will be applied to determine which resources to remediate. -type RemediationFilters struct { - // Locations - The resource locations that will be remediated. - Locations *[]string `json:"locations,omitempty"` -} - -// RemediationListResult list of remediations. -type RemediationListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; Array of remediation definitions. - Value *[]Remediation `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for RemediationListResult. -func (rlr RemediationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// RemediationListResultIterator provides access to a complete listing of Remediation values. -type RemediationListResultIterator struct { - i int - page RemediationListResultPage -} - -// NextWithContext 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 *RemediationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RemediationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RemediationListResultIterator) 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 RemediationListResultIterator) Response() RemediationListResult { - 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 RemediationListResultIterator) Value() Remediation { - if !iter.page.NotDone() { - return Remediation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RemediationListResultIterator type. -func NewRemediationListResultIterator(page RemediationListResultPage) RemediationListResultIterator { - return RemediationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rlr RemediationListResult) IsEmpty() bool { - return rlr.Value == nil || len(*rlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rlr RemediationListResult) hasNextLink() bool { - return rlr.NextLink != nil && len(*rlr.NextLink) != 0 -} - -// remediationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rlr RemediationListResult) remediationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rlr.NextLink))) -} - -// RemediationListResultPage contains a page of Remediation values. -type RemediationListResultPage struct { - fn func(context.Context, RemediationListResult) (RemediationListResult, error) - rlr RemediationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RemediationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rlr) - if err != nil { - return err - } - page.rlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RemediationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RemediationListResultPage) NotDone() bool { - return !page.rlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RemediationListResultPage) Response() RemediationListResult { - return page.rlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RemediationListResultPage) Values() []Remediation { - if page.rlr.IsEmpty() { - return nil - } - return *page.rlr.Value -} - -// Creates a new instance of the RemediationListResultPage type. -func NewRemediationListResultPage(cur RemediationListResult, getNextPage func(context.Context, RemediationListResult) (RemediationListResult, error)) RemediationListResultPage { - return RemediationListResultPage{ - fn: getNextPage, - rlr: cur, - } -} - -// RemediationProperties the remediation properties. -type RemediationProperties struct { - // PolicyAssignmentID - The resource ID of the policy assignment that should be remediated. - PolicyAssignmentID *string `json:"policyAssignmentId,omitempty"` - // PolicyDefinitionReferenceID - The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. - PolicyDefinitionReferenceID *string `json:"policyDefinitionReferenceId,omitempty"` - // ResourceDiscoveryMode - The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. Possible values include: 'ExistingNonCompliant', 'ReEvaluateCompliance' - ResourceDiscoveryMode ResourceDiscoveryMode `json:"resourceDiscoveryMode,omitempty"` - // ProvisioningState - READ-ONLY; The status of the remediation. - ProvisioningState *string `json:"provisioningState,omitempty"` - // CreatedOn - READ-ONLY; The time at which the remediation was created. - CreatedOn *date.Time `json:"createdOn,omitempty"` - // LastUpdatedOn - READ-ONLY; The time at which the remediation was last updated. - LastUpdatedOn *date.Time `json:"lastUpdatedOn,omitempty"` - // Filters - The filters that will be applied to determine which resources to remediate. - Filters *RemediationFilters `json:"filters,omitempty"` - // DeploymentStatus - READ-ONLY; The deployment status summary for all deployments created by the remediation. - DeploymentStatus *RemediationDeploymentSummary `json:"deploymentStatus,omitempty"` -} - -// MarshalJSON is the custom marshaler for RemediationProperties. -func (rp RemediationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rp.PolicyAssignmentID != nil { - objectMap["policyAssignmentId"] = rp.PolicyAssignmentID - } - if rp.PolicyDefinitionReferenceID != nil { - objectMap["policyDefinitionReferenceId"] = rp.PolicyDefinitionReferenceID - } - if rp.ResourceDiscoveryMode != "" { - objectMap["resourceDiscoveryMode"] = rp.ResourceDiscoveryMode - } - if rp.Filters != nil { - objectMap["filters"] = rp.Filters - } - return json.Marshal(objectMap) -} - -// SlimPolicyMetadata slim version of policy metadata resource definition, excluding properties with large -// strings -type SlimPolicyMetadata struct { - // PolicyMetadataSlimProperties - Properties of the policy metadata. - *PolicyMetadataSlimProperties `json:"properties,omitempty"` - // ID - READ-ONLY; The ID of the policy metadata. - ID *string `json:"id,omitempty"` - // Type - READ-ONLY; The type of the policy metadata. - Type *string `json:"type,omitempty"` - // Name - READ-ONLY; The name of the policy metadata. - Name *string `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for SlimPolicyMetadata. -func (spm SlimPolicyMetadata) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if spm.PolicyMetadataSlimProperties != nil { - objectMap["properties"] = spm.PolicyMetadataSlimProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SlimPolicyMetadata struct. -func (spm *SlimPolicyMetadata) 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 policyMetadataSlimProperties PolicyMetadataSlimProperties - err = json.Unmarshal(*v, &policyMetadataSlimProperties) - if err != nil { - return err - } - spm.PolicyMetadataSlimProperties = &policyMetadataSlimProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - spm.ID = &ID - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - spm.Type = &typeVar - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - spm.Name = &name - } - } - } - - return nil -} - -// SummarizeResults summarize action results. -type SummarizeResults struct { - autorest.Response `json:"-"` - // OdataContext - OData context string; used by OData clients to resolve type information based on metadata. - OdataContext *string `json:"@odata.context,omitempty"` - // OdataCount - OData entity count; represents the number of summaries returned; always set to 1. - OdataCount *int32 `json:"@odata.count,omitempty"` - // Value - Summarize action results. - Value *[]Summary `json:"value,omitempty"` -} - -// Summary summary results. -type Summary struct { - // OdataID - OData entity ID; always set to null since summaries do not have an entity ID. - OdataID *string `json:"@odata.id,omitempty"` - // OdataContext - OData context string; used by OData clients to resolve type information based on metadata. - OdataContext *string `json:"@odata.context,omitempty"` - // Results - Compliance summary for all policy assignments. - Results *SummaryResults `json:"results,omitempty"` - // PolicyAssignments - Policy assignments summary. - PolicyAssignments *[]PolicyAssignmentSummary `json:"policyAssignments,omitempty"` -} - -// SummaryResults compliance summary on a particular summary level. -type SummaryResults struct { - // QueryResultsURI - HTTP POST URI for queryResults action on Microsoft.PolicyInsights to retrieve raw results for the compliance summary. This property will not be available by default in future API versions, but could be queried explicitly. - QueryResultsURI *string `json:"queryResultsUri,omitempty"` - // NonCompliantResources - Number of non-compliant resources. - NonCompliantResources *int32 `json:"nonCompliantResources,omitempty"` - // NonCompliantPolicies - Number of non-compliant policies. - NonCompliantPolicies *int32 `json:"nonCompliantPolicies,omitempty"` - // ResourceDetails - The resources summary at this level. - ResourceDetails *[]ComplianceDetail `json:"resourceDetails,omitempty"` - // PolicyDetails - The policy artifact summary at this level. For query scope level, it represents policy assignment summary. For policy assignment level, it represents policy definitions summary. - PolicyDetails *[]ComplianceDetail `json:"policyDetails,omitempty"` - // PolicyGroupDetails - The policy definition group summary at this level. - PolicyGroupDetails *[]ComplianceDetail `json:"policyGroupDetails,omitempty"` -} - -// TrackedResourceModificationDetails the details of the policy triggered deployment that created or -// modified the tracked resource. -type TrackedResourceModificationDetails struct { - // PolicyDetails - READ-ONLY; The details of the policy that created or modified the tracked resource. - PolicyDetails *PolicyDetails `json:"policyDetails,omitempty"` - // DeploymentID - READ-ONLY; The ID of the deployment that created or modified the tracked resource. - DeploymentID *string `json:"deploymentId,omitempty"` - // DeploymentTime - READ-ONLY; Timestamp of the deployment that created or modified the tracked resource. - DeploymentTime *date.Time `json:"deploymentTime,omitempty"` -} - -// MarshalJSON is the custom marshaler for TrackedResourceModificationDetails. -func (trmd TrackedResourceModificationDetails) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// TypedErrorInfo scenario specific error details. -type TypedErrorInfo struct { - // Type - READ-ONLY; The type of included error details. - Type *string `json:"type,omitempty"` - // Info - READ-ONLY; The scenario specific error details. - Info interface{} `json:"info,omitempty"` -} - -// MarshalJSON is the custom marshaler for TypedErrorInfo. -func (tei TypedErrorInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/operations.go deleted file mode 100644 index 304ceb16dcf6..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/operations.go +++ /dev/null @@ -1,98 +0,0 @@ -package policyinsights - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// OperationsClient is the client for the Operations methods of the Policyinsights service. -type OperationsClient struct { - BaseClient -} - -// NewOperationsClient creates an instance of the OperationsClient client. -func NewOperationsClient() OperationsClient { - return NewOperationsClientWithBaseURI(DefaultBaseURI) -} - -// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI)} -} - -// List lists available operations. -func (client OperationsClient) List(ctx context.Context) (result OperationsListResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.OperationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.OperationsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.OperationsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.PolicyInsights/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 client.Send(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 OperationsListResults, err error) { - err = autorest.Respond( - resp, - 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/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policyevents.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policyevents.go deleted file mode 100644 index e5939080c35a..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policyevents.go +++ /dev/null @@ -1,1336 +0,0 @@ -package policyinsights - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/date" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PolicyEventsClient is the client for the PolicyEvents methods of the Policyinsights service. -type PolicyEventsClient struct { - BaseClient -} - -// NewPolicyEventsClient creates an instance of the PolicyEventsClient client. -func NewPolicyEventsClient() PolicyEventsClient { - return NewPolicyEventsClientWithBaseURI(DefaultBaseURI) -} - -// NewPolicyEventsClientWithBaseURI creates an instance of the PolicyEventsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewPolicyEventsClientWithBaseURI(baseURI string) PolicyEventsClient { - return PolicyEventsClient{NewWithBaseURI(baseURI)} -} - -// ListQueryResultsForManagementGroup queries policy events for the resources under the management group. -// Parameters: -// managementGroupName - management group name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyEventsClient) ListQueryResultsForManagementGroup(ctx context.Context, managementGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForManagementGroup") - defer func() { - sc := -1 - if result.peqr.Response.Response != nil { - sc = result.peqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyEventsClient", "ListQueryResultsForManagementGroup", err.Error()) - } - - result.fn = client.listQueryResultsForManagementGroupNextResults - req, err := client.ListQueryResultsForManagementGroupPreparer(ctx, managementGroupName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForManagementGroupSender(req) - if err != nil { - result.peqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForManagementGroup", resp, "Failure sending request") - return - } - - result.peqr, err = client.ListQueryResultsForManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForManagementGroup", resp, "Failure responding to request") - return - } - if result.peqr.hasNextLink() && result.peqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForManagementGroupPreparer prepares the ListQueryResultsForManagementGroup request. -func (client PolicyEventsClient) ListQueryResultsForManagementGroupPreparer(ctx context.Context, managementGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupName": autorest.Encode("path", managementGroupName), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - "policyEventsResource": autorest.Encode("path", "default"), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForManagementGroupSender sends the ListQueryResultsForManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyEventsClient) ListQueryResultsForManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListQueryResultsForManagementGroupResponder handles the response to the ListQueryResultsForManagementGroup request. The method always -// closes the http.Response Body. -func (client PolicyEventsClient) ListQueryResultsForManagementGroupResponder(resp *http.Response) (result PolicyEventsQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForManagementGroupNextResults retrieves the next set of results, if any. -func (client PolicyEventsClient) listQueryResultsForManagementGroupNextResults(ctx context.Context, lastResults PolicyEventsQueryResults) (result PolicyEventsQueryResults, err error) { - req, err := lastResults.policyEventsQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForManagementGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForManagementGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForManagementGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForManagementGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyEventsClient) ListQueryResultsForManagementGroupComplete(ctx context.Context, managementGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForManagementGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForManagementGroup(ctx, managementGroupName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForPolicyDefinition queries policy events for the subscription level policy definition. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// policyDefinitionName - policy definition name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyEventsClient) ListQueryResultsForPolicyDefinition(ctx context.Context, subscriptionID string, policyDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForPolicyDefinition") - defer func() { - sc := -1 - if result.peqr.Response.Response != nil { - sc = result.peqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyEventsClient", "ListQueryResultsForPolicyDefinition", err.Error()) - } - - result.fn = client.listQueryResultsForPolicyDefinitionNextResults - req, err := client.ListQueryResultsForPolicyDefinitionPreparer(ctx, subscriptionID, policyDefinitionName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForPolicyDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForPolicyDefinitionSender(req) - if err != nil { - result.peqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForPolicyDefinition", resp, "Failure sending request") - return - } - - result.peqr, err = client.ListQueryResultsForPolicyDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForPolicyDefinition", resp, "Failure responding to request") - return - } - if result.peqr.hasNextLink() && result.peqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForPolicyDefinitionPreparer prepares the ListQueryResultsForPolicyDefinition request. -func (client PolicyEventsClient) ListQueryResultsForPolicyDefinitionPreparer(ctx context.Context, subscriptionID string, policyDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyDefinitionName": autorest.Encode("path", policyDefinitionName), - "policyEventsResource": autorest.Encode("path", "default"), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForPolicyDefinitionSender sends the ListQueryResultsForPolicyDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyEventsClient) ListQueryResultsForPolicyDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForPolicyDefinitionResponder handles the response to the ListQueryResultsForPolicyDefinition request. The method always -// closes the http.Response Body. -func (client PolicyEventsClient) ListQueryResultsForPolicyDefinitionResponder(resp *http.Response) (result PolicyEventsQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForPolicyDefinitionNextResults retrieves the next set of results, if any. -func (client PolicyEventsClient) listQueryResultsForPolicyDefinitionNextResults(ctx context.Context, lastResults PolicyEventsQueryResults) (result PolicyEventsQueryResults, err error) { - req, err := lastResults.policyEventsQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForPolicyDefinitionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForPolicyDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForPolicyDefinitionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForPolicyDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForPolicyDefinitionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForPolicyDefinitionComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyEventsClient) ListQueryResultsForPolicyDefinitionComplete(ctx context.Context, subscriptionID string, policyDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForPolicyDefinition") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForPolicyDefinition(ctx, subscriptionID, policyDefinitionName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForPolicySetDefinition queries policy events for the subscription level policy set definition. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// policySetDefinitionName - policy set definition name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyEventsClient) ListQueryResultsForPolicySetDefinition(ctx context.Context, subscriptionID string, policySetDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForPolicySetDefinition") - defer func() { - sc := -1 - if result.peqr.Response.Response != nil { - sc = result.peqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyEventsClient", "ListQueryResultsForPolicySetDefinition", err.Error()) - } - - result.fn = client.listQueryResultsForPolicySetDefinitionNextResults - req, err := client.ListQueryResultsForPolicySetDefinitionPreparer(ctx, subscriptionID, policySetDefinitionName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForPolicySetDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForPolicySetDefinitionSender(req) - if err != nil { - result.peqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForPolicySetDefinition", resp, "Failure sending request") - return - } - - result.peqr, err = client.ListQueryResultsForPolicySetDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForPolicySetDefinition", resp, "Failure responding to request") - return - } - if result.peqr.hasNextLink() && result.peqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForPolicySetDefinitionPreparer prepares the ListQueryResultsForPolicySetDefinition request. -func (client PolicyEventsClient) ListQueryResultsForPolicySetDefinitionPreparer(ctx context.Context, subscriptionID string, policySetDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyEventsResource": autorest.Encode("path", "default"), - "policySetDefinitionName": autorest.Encode("path", policySetDefinitionName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForPolicySetDefinitionSender sends the ListQueryResultsForPolicySetDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyEventsClient) ListQueryResultsForPolicySetDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForPolicySetDefinitionResponder handles the response to the ListQueryResultsForPolicySetDefinition request. The method always -// closes the http.Response Body. -func (client PolicyEventsClient) ListQueryResultsForPolicySetDefinitionResponder(resp *http.Response) (result PolicyEventsQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForPolicySetDefinitionNextResults retrieves the next set of results, if any. -func (client PolicyEventsClient) listQueryResultsForPolicySetDefinitionNextResults(ctx context.Context, lastResults PolicyEventsQueryResults) (result PolicyEventsQueryResults, err error) { - req, err := lastResults.policyEventsQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForPolicySetDefinitionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForPolicySetDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForPolicySetDefinitionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForPolicySetDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForPolicySetDefinitionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForPolicySetDefinitionComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyEventsClient) ListQueryResultsForPolicySetDefinitionComplete(ctx context.Context, subscriptionID string, policySetDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForPolicySetDefinition") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForPolicySetDefinition(ctx, subscriptionID, policySetDefinitionName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForResource queries policy events for the resource. -// Parameters: -// resourceID - resource ID. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// expand - the $expand query parameter. For example, to expand components use $expand=components -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyEventsClient) ListQueryResultsForResource(ctx context.Context, resourceID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, expand string, skipToken string) (result PolicyEventsQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForResource") - defer func() { - sc := -1 - if result.peqr.Response.Response != nil { - sc = result.peqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyEventsClient", "ListQueryResultsForResource", err.Error()) - } - - result.fn = client.listQueryResultsForResourceNextResults - req, err := client.ListQueryResultsForResourcePreparer(ctx, resourceID, top, orderBy, selectParameter, from, toParameter, filter, apply, expand, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForResource", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForResourceSender(req) - if err != nil { - result.peqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForResource", resp, "Failure sending request") - return - } - - result.peqr, err = client.ListQueryResultsForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForResource", resp, "Failure responding to request") - return - } - if result.peqr.hasNextLink() && result.peqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForResourcePreparer prepares the ListQueryResultsForResource request. -func (client PolicyEventsClient) ListQueryResultsForResourcePreparer(ctx context.Context, resourceID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, expand string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyEventsResource": autorest.Encode("path", "default"), - "resourceId": resourceID, - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForResourceSender sends the ListQueryResultsForResource request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyEventsClient) ListQueryResultsForResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListQueryResultsForResourceResponder handles the response to the ListQueryResultsForResource request. The method always -// closes the http.Response Body. -func (client PolicyEventsClient) ListQueryResultsForResourceResponder(resp *http.Response) (result PolicyEventsQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForResourceNextResults retrieves the next set of results, if any. -func (client PolicyEventsClient) listQueryResultsForResourceNextResults(ctx context.Context, lastResults PolicyEventsQueryResults) (result PolicyEventsQueryResults, err error) { - req, err := lastResults.policyEventsQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForResourceNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForResourceNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForResourceNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForResourceComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyEventsClient) ListQueryResultsForResourceComplete(ctx context.Context, resourceID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, expand string, skipToken string) (result PolicyEventsQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForResource") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForResource(ctx, resourceID, top, orderBy, selectParameter, from, toParameter, filter, apply, expand, skipToken) - return -} - -// ListQueryResultsForResourceGroup queries policy events for the resources under the resource group. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyEventsClient) ListQueryResultsForResourceGroup(ctx context.Context, subscriptionID string, resourceGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForResourceGroup") - defer func() { - sc := -1 - if result.peqr.Response.Response != nil { - sc = result.peqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyEventsClient", "ListQueryResultsForResourceGroup", err.Error()) - } - - result.fn = client.listQueryResultsForResourceGroupNextResults - req, err := client.ListQueryResultsForResourceGroupPreparer(ctx, subscriptionID, resourceGroupName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForResourceGroupSender(req) - if err != nil { - result.peqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForResourceGroup", resp, "Failure sending request") - return - } - - result.peqr, err = client.ListQueryResultsForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForResourceGroup", resp, "Failure responding to request") - return - } - if result.peqr.hasNextLink() && result.peqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForResourceGroupPreparer prepares the ListQueryResultsForResourceGroup request. -func (client PolicyEventsClient) ListQueryResultsForResourceGroupPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyEventsResource": autorest.Encode("path", "default"), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForResourceGroupSender sends the ListQueryResultsForResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyEventsClient) ListQueryResultsForResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForResourceGroupResponder handles the response to the ListQueryResultsForResourceGroup request. The method always -// closes the http.Response Body. -func (client PolicyEventsClient) ListQueryResultsForResourceGroupResponder(resp *http.Response) (result PolicyEventsQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForResourceGroupNextResults retrieves the next set of results, if any. -func (client PolicyEventsClient) listQueryResultsForResourceGroupNextResults(ctx context.Context, lastResults PolicyEventsQueryResults) (result PolicyEventsQueryResults, err error) { - req, err := lastResults.policyEventsQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyEventsClient) ListQueryResultsForResourceGroupComplete(ctx context.Context, subscriptionID string, resourceGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForResourceGroup(ctx, subscriptionID, resourceGroupName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignment queries policy events for the resource group level policy -// assignment. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// policyAssignmentName - policy assignment name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyEventsClient) ListQueryResultsForResourceGroupLevelPolicyAssignment(ctx context.Context, subscriptionID string, resourceGroupName string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForResourceGroupLevelPolicyAssignment") - defer func() { - sc := -1 - if result.peqr.Response.Response != nil { - sc = result.peqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyEventsClient", "ListQueryResultsForResourceGroupLevelPolicyAssignment", err.Error()) - } - - result.fn = client.listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults - req, err := client.ListQueryResultsForResourceGroupLevelPolicyAssignmentPreparer(ctx, subscriptionID, resourceGroupName, policyAssignmentName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForResourceGroupLevelPolicyAssignment", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForResourceGroupLevelPolicyAssignmentSender(req) - if err != nil { - result.peqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForResourceGroupLevelPolicyAssignment", resp, "Failure sending request") - return - } - - result.peqr, err = client.ListQueryResultsForResourceGroupLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForResourceGroupLevelPolicyAssignment", resp, "Failure responding to request") - return - } - if result.peqr.hasNextLink() && result.peqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignmentPreparer prepares the ListQueryResultsForResourceGroupLevelPolicyAssignment request. -func (client PolicyEventsClient) ListQueryResultsForResourceGroupLevelPolicyAssignmentPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyAssignmentName": autorest.Encode("path", policyAssignmentName), - "policyEventsResource": autorest.Encode("path", "default"), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignmentSender sends the ListQueryResultsForResourceGroupLevelPolicyAssignment request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyEventsClient) ListQueryResultsForResourceGroupLevelPolicyAssignmentSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignmentResponder handles the response to the ListQueryResultsForResourceGroupLevelPolicyAssignment request. The method always -// closes the http.Response Body. -func (client PolicyEventsClient) ListQueryResultsForResourceGroupLevelPolicyAssignmentResponder(resp *http.Response) (result PolicyEventsQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults retrieves the next set of results, if any. -func (client PolicyEventsClient) listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults(ctx context.Context, lastResults PolicyEventsQueryResults) (result PolicyEventsQueryResults, err error) { - req, err := lastResults.policyEventsQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForResourceGroupLevelPolicyAssignmentSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForResourceGroupLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignmentComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyEventsClient) ListQueryResultsForResourceGroupLevelPolicyAssignmentComplete(ctx context.Context, subscriptionID string, resourceGroupName string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForResourceGroupLevelPolicyAssignment") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForResourceGroupLevelPolicyAssignment(ctx, subscriptionID, resourceGroupName, policyAssignmentName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForSubscription queries policy events for the resources under the subscription. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyEventsClient) ListQueryResultsForSubscription(ctx context.Context, subscriptionID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForSubscription") - defer func() { - sc := -1 - if result.peqr.Response.Response != nil { - sc = result.peqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyEventsClient", "ListQueryResultsForSubscription", err.Error()) - } - - result.fn = client.listQueryResultsForSubscriptionNextResults - req, err := client.ListQueryResultsForSubscriptionPreparer(ctx, subscriptionID, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForSubscriptionSender(req) - if err != nil { - result.peqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForSubscription", resp, "Failure sending request") - return - } - - result.peqr, err = client.ListQueryResultsForSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForSubscription", resp, "Failure responding to request") - return - } - if result.peqr.hasNextLink() && result.peqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForSubscriptionPreparer prepares the ListQueryResultsForSubscription request. -func (client PolicyEventsClient) ListQueryResultsForSubscriptionPreparer(ctx context.Context, subscriptionID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyEventsResource": autorest.Encode("path", "default"), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForSubscriptionSender sends the ListQueryResultsForSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyEventsClient) ListQueryResultsForSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForSubscriptionResponder handles the response to the ListQueryResultsForSubscription request. The method always -// closes the http.Response Body. -func (client PolicyEventsClient) ListQueryResultsForSubscriptionResponder(resp *http.Response) (result PolicyEventsQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForSubscriptionNextResults retrieves the next set of results, if any. -func (client PolicyEventsClient) listQueryResultsForSubscriptionNextResults(ctx context.Context, lastResults PolicyEventsQueryResults) (result PolicyEventsQueryResults, err error) { - req, err := lastResults.policyEventsQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForSubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForSubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForSubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForSubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyEventsClient) ListQueryResultsForSubscriptionComplete(ctx context.Context, subscriptionID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForSubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForSubscription(ctx, subscriptionID, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignment queries policy events for the subscription level policy -// assignment. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// policyAssignmentName - policy assignment name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyEventsClient) ListQueryResultsForSubscriptionLevelPolicyAssignment(ctx context.Context, subscriptionID string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForSubscriptionLevelPolicyAssignment") - defer func() { - sc := -1 - if result.peqr.Response.Response != nil { - sc = result.peqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyEventsClient", "ListQueryResultsForSubscriptionLevelPolicyAssignment", err.Error()) - } - - result.fn = client.listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults - req, err := client.ListQueryResultsForSubscriptionLevelPolicyAssignmentPreparer(ctx, subscriptionID, policyAssignmentName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForSubscriptionLevelPolicyAssignment", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForSubscriptionLevelPolicyAssignmentSender(req) - if err != nil { - result.peqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForSubscriptionLevelPolicyAssignment", resp, "Failure sending request") - return - } - - result.peqr, err = client.ListQueryResultsForSubscriptionLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "ListQueryResultsForSubscriptionLevelPolicyAssignment", resp, "Failure responding to request") - return - } - if result.peqr.hasNextLink() && result.peqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignmentPreparer prepares the ListQueryResultsForSubscriptionLevelPolicyAssignment request. -func (client PolicyEventsClient) ListQueryResultsForSubscriptionLevelPolicyAssignmentPreparer(ctx context.Context, subscriptionID string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyAssignmentName": autorest.Encode("path", policyAssignmentName), - "policyEventsResource": autorest.Encode("path", "default"), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignmentSender sends the ListQueryResultsForSubscriptionLevelPolicyAssignment request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyEventsClient) ListQueryResultsForSubscriptionLevelPolicyAssignmentSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignmentResponder handles the response to the ListQueryResultsForSubscriptionLevelPolicyAssignment request. The method always -// closes the http.Response Body. -func (client PolicyEventsClient) ListQueryResultsForSubscriptionLevelPolicyAssignmentResponder(resp *http.Response) (result PolicyEventsQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults retrieves the next set of results, if any. -func (client PolicyEventsClient) listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults(ctx context.Context, lastResults PolicyEventsQueryResults) (result PolicyEventsQueryResults, err error) { - req, err := lastResults.policyEventsQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForSubscriptionLevelPolicyAssignmentSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForSubscriptionLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyEventsClient", "listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignmentComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyEventsClient) ListQueryResultsForSubscriptionLevelPolicyAssignmentComplete(ctx context.Context, subscriptionID string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyEventsQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyEventsClient.ListQueryResultsForSubscriptionLevelPolicyAssignment") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForSubscriptionLevelPolicyAssignment(ctx, subscriptionID, policyAssignmentName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policymetadata.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policymetadata.go deleted file mode 100644 index 911a138dd2d5..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policymetadata.go +++ /dev/null @@ -1,226 +0,0 @@ -package policyinsights - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PolicyMetadataClient is the client for the PolicyMetadata methods of the Policyinsights service. -type PolicyMetadataClient struct { - BaseClient -} - -// NewPolicyMetadataClient creates an instance of the PolicyMetadataClient client. -func NewPolicyMetadataClient() PolicyMetadataClient { - return NewPolicyMetadataClientWithBaseURI(DefaultBaseURI) -} - -// NewPolicyMetadataClientWithBaseURI creates an instance of the PolicyMetadataClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewPolicyMetadataClientWithBaseURI(baseURI string) PolicyMetadataClient { - return PolicyMetadataClient{NewWithBaseURI(baseURI)} -} - -// GetResource get policy metadata resource. -// Parameters: -// resourceName - the name of the policy metadata resource. -func (client PolicyMetadataClient) GetResource(ctx context.Context, resourceName string) (result PolicyMetadata, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyMetadataClient.GetResource") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetResourcePreparer(ctx, resourceName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyMetadataClient", "GetResource", nil, "Failure preparing request") - return - } - - resp, err := client.GetResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyMetadataClient", "GetResource", resp, "Failure sending request") - return - } - - result, err = client.GetResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyMetadataClient", "GetResource", resp, "Failure responding to request") - return - } - - return -} - -// GetResourcePreparer prepares the GetResource request. -func (client PolicyMetadataClient) GetResourcePreparer(ctx context.Context, resourceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceName": resourceName, - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/Microsoft.PolicyInsights/policyMetadata/{resourceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetResourceSender sends the GetResource request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyMetadataClient) GetResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResourceResponder handles the response to the GetResource request. The method always -// closes the http.Response Body. -func (client PolicyMetadataClient) GetResourceResponder(resp *http.Response) (result PolicyMetadata, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List get a list of the policy metadata resources. -// Parameters: -// top - maximum number of records to return. -func (client PolicyMetadataClient) List(ctx context.Context, top *int32) (result PolicyMetadataCollectionPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyMetadataClient.List") - defer func() { - sc := -1 - if result.pmc.Response.Response != nil { - sc = result.pmc.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyMetadataClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, top) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyMetadataClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.pmc.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyMetadataClient", "List", resp, "Failure sending request") - return - } - - result.pmc, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyMetadataClient", "List", resp, "Failure responding to request") - return - } - if result.pmc.hasNextLink() && result.pmc.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PolicyMetadataClient) ListPreparer(ctx context.Context, top *int32) (*http.Request, error) { - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.PolicyInsights/policyMetadata"), - 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 PolicyMetadataClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(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 PolicyMetadataClient) ListResponder(resp *http.Response) (result PolicyMetadataCollection, err error) { - err = autorest.Respond( - resp, - 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 PolicyMetadataClient) listNextResults(ctx context.Context, lastResults PolicyMetadataCollection) (result PolicyMetadataCollection, err error) { - req, err := lastResults.policyMetadataCollectionPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyMetadataClient", "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, "policyinsights.PolicyMetadataClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyMetadataClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyMetadataClient) ListComplete(ctx context.Context, top *int32) (result PolicyMetadataCollectionIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyMetadataClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, top) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policystates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policystates.go deleted file mode 100644 index 918dab07a558..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policystates.go +++ /dev/null @@ -1,2314 +0,0 @@ -package policyinsights - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/date" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PolicyStatesClient is the client for the PolicyStates methods of the Policyinsights service. -type PolicyStatesClient struct { - BaseClient -} - -// NewPolicyStatesClient creates an instance of the PolicyStatesClient client. -func NewPolicyStatesClient() PolicyStatesClient { - return NewPolicyStatesClientWithBaseURI(DefaultBaseURI) -} - -// NewPolicyStatesClientWithBaseURI creates an instance of the PolicyStatesClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewPolicyStatesClientWithBaseURI(baseURI string) PolicyStatesClient { - return PolicyStatesClient{NewWithBaseURI(baseURI)} -} - -// ListQueryResultsForManagementGroup queries policy states for the resources under the management group. -// Parameters: -// policyStatesResource - the virtual resource under PolicyStates resource type. In a given time range, -// 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). -// managementGroupName - management group name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyStatesClient) ListQueryResultsForManagementGroup(ctx context.Context, policyStatesResource PolicyStatesResource, managementGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForManagementGroup") - defer func() { - sc := -1 - if result.psqr.Response.Response != nil { - sc = result.psqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "ListQueryResultsForManagementGroup", err.Error()) - } - - result.fn = client.listQueryResultsForManagementGroupNextResults - req, err := client.ListQueryResultsForManagementGroupPreparer(ctx, policyStatesResource, managementGroupName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForManagementGroupSender(req) - if err != nil { - result.psqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForManagementGroup", resp, "Failure sending request") - return - } - - result.psqr, err = client.ListQueryResultsForManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForManagementGroup", resp, "Failure responding to request") - return - } - if result.psqr.hasNextLink() && result.psqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForManagementGroupPreparer prepares the ListQueryResultsForManagementGroup request. -func (client PolicyStatesClient) ListQueryResultsForManagementGroupPreparer(ctx context.Context, policyStatesResource PolicyStatesResource, managementGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupName": autorest.Encode("path", managementGroupName), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - "policyStatesResource": autorest.Encode("path", policyStatesResource), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForManagementGroupSender sends the ListQueryResultsForManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) ListQueryResultsForManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListQueryResultsForManagementGroupResponder handles the response to the ListQueryResultsForManagementGroup request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) ListQueryResultsForManagementGroupResponder(resp *http.Response) (result PolicyStatesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForManagementGroupNextResults retrieves the next set of results, if any. -func (client PolicyStatesClient) listQueryResultsForManagementGroupNextResults(ctx context.Context, lastResults PolicyStatesQueryResults) (result PolicyStatesQueryResults, err error) { - req, err := lastResults.policyStatesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForManagementGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForManagementGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForManagementGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForManagementGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyStatesClient) ListQueryResultsForManagementGroupComplete(ctx context.Context, policyStatesResource PolicyStatesResource, managementGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForManagementGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForManagementGroup(ctx, policyStatesResource, managementGroupName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForPolicyDefinition queries policy states for the subscription level policy definition. -// Parameters: -// policyStatesResource - the virtual resource under PolicyStates resource type. In a given time range, -// 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). -// subscriptionID - microsoft Azure subscription ID. -// policyDefinitionName - policy definition name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyStatesClient) ListQueryResultsForPolicyDefinition(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, policyDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForPolicyDefinition") - defer func() { - sc := -1 - if result.psqr.Response.Response != nil { - sc = result.psqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "ListQueryResultsForPolicyDefinition", err.Error()) - } - - result.fn = client.listQueryResultsForPolicyDefinitionNextResults - req, err := client.ListQueryResultsForPolicyDefinitionPreparer(ctx, policyStatesResource, subscriptionID, policyDefinitionName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForPolicyDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForPolicyDefinitionSender(req) - if err != nil { - result.psqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForPolicyDefinition", resp, "Failure sending request") - return - } - - result.psqr, err = client.ListQueryResultsForPolicyDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForPolicyDefinition", resp, "Failure responding to request") - return - } - if result.psqr.hasNextLink() && result.psqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForPolicyDefinitionPreparer prepares the ListQueryResultsForPolicyDefinition request. -func (client PolicyStatesClient) ListQueryResultsForPolicyDefinitionPreparer(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, policyDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyDefinitionName": autorest.Encode("path", policyDefinitionName), - "policyStatesResource": autorest.Encode("path", policyStatesResource), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForPolicyDefinitionSender sends the ListQueryResultsForPolicyDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) ListQueryResultsForPolicyDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForPolicyDefinitionResponder handles the response to the ListQueryResultsForPolicyDefinition request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) ListQueryResultsForPolicyDefinitionResponder(resp *http.Response) (result PolicyStatesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForPolicyDefinitionNextResults retrieves the next set of results, if any. -func (client PolicyStatesClient) listQueryResultsForPolicyDefinitionNextResults(ctx context.Context, lastResults PolicyStatesQueryResults) (result PolicyStatesQueryResults, err error) { - req, err := lastResults.policyStatesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForPolicyDefinitionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForPolicyDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForPolicyDefinitionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForPolicyDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForPolicyDefinitionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForPolicyDefinitionComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyStatesClient) ListQueryResultsForPolicyDefinitionComplete(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, policyDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForPolicyDefinition") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForPolicyDefinition(ctx, policyStatesResource, subscriptionID, policyDefinitionName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForPolicySetDefinition queries policy states for the subscription level policy set definition. -// Parameters: -// policyStatesResource - the virtual resource under PolicyStates resource type. In a given time range, -// 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). -// subscriptionID - microsoft Azure subscription ID. -// policySetDefinitionName - policy set definition name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyStatesClient) ListQueryResultsForPolicySetDefinition(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, policySetDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForPolicySetDefinition") - defer func() { - sc := -1 - if result.psqr.Response.Response != nil { - sc = result.psqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "ListQueryResultsForPolicySetDefinition", err.Error()) - } - - result.fn = client.listQueryResultsForPolicySetDefinitionNextResults - req, err := client.ListQueryResultsForPolicySetDefinitionPreparer(ctx, policyStatesResource, subscriptionID, policySetDefinitionName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForPolicySetDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForPolicySetDefinitionSender(req) - if err != nil { - result.psqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForPolicySetDefinition", resp, "Failure sending request") - return - } - - result.psqr, err = client.ListQueryResultsForPolicySetDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForPolicySetDefinition", resp, "Failure responding to request") - return - } - if result.psqr.hasNextLink() && result.psqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForPolicySetDefinitionPreparer prepares the ListQueryResultsForPolicySetDefinition request. -func (client PolicyStatesClient) ListQueryResultsForPolicySetDefinitionPreparer(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, policySetDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policySetDefinitionName": autorest.Encode("path", policySetDefinitionName), - "policyStatesResource": autorest.Encode("path", policyStatesResource), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForPolicySetDefinitionSender sends the ListQueryResultsForPolicySetDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) ListQueryResultsForPolicySetDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForPolicySetDefinitionResponder handles the response to the ListQueryResultsForPolicySetDefinition request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) ListQueryResultsForPolicySetDefinitionResponder(resp *http.Response) (result PolicyStatesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForPolicySetDefinitionNextResults retrieves the next set of results, if any. -func (client PolicyStatesClient) listQueryResultsForPolicySetDefinitionNextResults(ctx context.Context, lastResults PolicyStatesQueryResults) (result PolicyStatesQueryResults, err error) { - req, err := lastResults.policyStatesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForPolicySetDefinitionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForPolicySetDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForPolicySetDefinitionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForPolicySetDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForPolicySetDefinitionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForPolicySetDefinitionComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyStatesClient) ListQueryResultsForPolicySetDefinitionComplete(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, policySetDefinitionName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForPolicySetDefinition") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForPolicySetDefinition(ctx, policyStatesResource, subscriptionID, policySetDefinitionName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForResource queries policy states for the resource. -// Parameters: -// policyStatesResource - the virtual resource under PolicyStates resource type. In a given time range, -// 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). -// resourceID - resource ID. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// expand - the $expand query parameter. For example, to expand components use $expand=components -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyStatesClient) ListQueryResultsForResource(ctx context.Context, policyStatesResource PolicyStatesResource, resourceID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, expand string, skipToken string) (result PolicyStatesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForResource") - defer func() { - sc := -1 - if result.psqr.Response.Response != nil { - sc = result.psqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "ListQueryResultsForResource", err.Error()) - } - - result.fn = client.listQueryResultsForResourceNextResults - req, err := client.ListQueryResultsForResourcePreparer(ctx, policyStatesResource, resourceID, top, orderBy, selectParameter, from, toParameter, filter, apply, expand, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForResource", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForResourceSender(req) - if err != nil { - result.psqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForResource", resp, "Failure sending request") - return - } - - result.psqr, err = client.ListQueryResultsForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForResource", resp, "Failure responding to request") - return - } - if result.psqr.hasNextLink() && result.psqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForResourcePreparer prepares the ListQueryResultsForResource request. -func (client PolicyStatesClient) ListQueryResultsForResourcePreparer(ctx context.Context, policyStatesResource PolicyStatesResource, resourceID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, expand string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyStatesResource": autorest.Encode("path", policyStatesResource), - "resourceId": resourceID, - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForResourceSender sends the ListQueryResultsForResource request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) ListQueryResultsForResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListQueryResultsForResourceResponder handles the response to the ListQueryResultsForResource request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) ListQueryResultsForResourceResponder(resp *http.Response) (result PolicyStatesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForResourceNextResults retrieves the next set of results, if any. -func (client PolicyStatesClient) listQueryResultsForResourceNextResults(ctx context.Context, lastResults PolicyStatesQueryResults) (result PolicyStatesQueryResults, err error) { - req, err := lastResults.policyStatesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForResourceNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForResourceNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForResourceNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForResourceComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyStatesClient) ListQueryResultsForResourceComplete(ctx context.Context, policyStatesResource PolicyStatesResource, resourceID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, expand string, skipToken string) (result PolicyStatesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForResource") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForResource(ctx, policyStatesResource, resourceID, top, orderBy, selectParameter, from, toParameter, filter, apply, expand, skipToken) - return -} - -// ListQueryResultsForResourceGroup queries policy states for the resources under the resource group. -// Parameters: -// policyStatesResource - the virtual resource under PolicyStates resource type. In a given time range, -// 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyStatesClient) ListQueryResultsForResourceGroup(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, resourceGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForResourceGroup") - defer func() { - sc := -1 - if result.psqr.Response.Response != nil { - sc = result.psqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "ListQueryResultsForResourceGroup", err.Error()) - } - - result.fn = client.listQueryResultsForResourceGroupNextResults - req, err := client.ListQueryResultsForResourceGroupPreparer(ctx, policyStatesResource, subscriptionID, resourceGroupName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForResourceGroupSender(req) - if err != nil { - result.psqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForResourceGroup", resp, "Failure sending request") - return - } - - result.psqr, err = client.ListQueryResultsForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForResourceGroup", resp, "Failure responding to request") - return - } - if result.psqr.hasNextLink() && result.psqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForResourceGroupPreparer prepares the ListQueryResultsForResourceGroup request. -func (client PolicyStatesClient) ListQueryResultsForResourceGroupPreparer(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, resourceGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyStatesResource": autorest.Encode("path", policyStatesResource), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForResourceGroupSender sends the ListQueryResultsForResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) ListQueryResultsForResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForResourceGroupResponder handles the response to the ListQueryResultsForResourceGroup request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) ListQueryResultsForResourceGroupResponder(resp *http.Response) (result PolicyStatesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForResourceGroupNextResults retrieves the next set of results, if any. -func (client PolicyStatesClient) listQueryResultsForResourceGroupNextResults(ctx context.Context, lastResults PolicyStatesQueryResults) (result PolicyStatesQueryResults, err error) { - req, err := lastResults.policyStatesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyStatesClient) ListQueryResultsForResourceGroupComplete(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, resourceGroupName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForResourceGroup(ctx, policyStatesResource, subscriptionID, resourceGroupName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignment queries policy states for the resource group level policy -// assignment. -// Parameters: -// policyStatesResource - the virtual resource under PolicyStates resource type. In a given time range, -// 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// policyAssignmentName - policy assignment name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyStatesClient) ListQueryResultsForResourceGroupLevelPolicyAssignment(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, resourceGroupName string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForResourceGroupLevelPolicyAssignment") - defer func() { - sc := -1 - if result.psqr.Response.Response != nil { - sc = result.psqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "ListQueryResultsForResourceGroupLevelPolicyAssignment", err.Error()) - } - - result.fn = client.listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults - req, err := client.ListQueryResultsForResourceGroupLevelPolicyAssignmentPreparer(ctx, policyStatesResource, subscriptionID, resourceGroupName, policyAssignmentName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForResourceGroupLevelPolicyAssignment", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForResourceGroupLevelPolicyAssignmentSender(req) - if err != nil { - result.psqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForResourceGroupLevelPolicyAssignment", resp, "Failure sending request") - return - } - - result.psqr, err = client.ListQueryResultsForResourceGroupLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForResourceGroupLevelPolicyAssignment", resp, "Failure responding to request") - return - } - if result.psqr.hasNextLink() && result.psqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignmentPreparer prepares the ListQueryResultsForResourceGroupLevelPolicyAssignment request. -func (client PolicyStatesClient) ListQueryResultsForResourceGroupLevelPolicyAssignmentPreparer(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, resourceGroupName string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyAssignmentName": autorest.Encode("path", policyAssignmentName), - "policyStatesResource": autorest.Encode("path", policyStatesResource), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignmentSender sends the ListQueryResultsForResourceGroupLevelPolicyAssignment request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) ListQueryResultsForResourceGroupLevelPolicyAssignmentSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignmentResponder handles the response to the ListQueryResultsForResourceGroupLevelPolicyAssignment request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) ListQueryResultsForResourceGroupLevelPolicyAssignmentResponder(resp *http.Response) (result PolicyStatesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults retrieves the next set of results, if any. -func (client PolicyStatesClient) listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults(ctx context.Context, lastResults PolicyStatesQueryResults) (result PolicyStatesQueryResults, err error) { - req, err := lastResults.policyStatesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForResourceGroupLevelPolicyAssignmentSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForResourceGroupLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForResourceGroupLevelPolicyAssignmentNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForResourceGroupLevelPolicyAssignmentComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyStatesClient) ListQueryResultsForResourceGroupLevelPolicyAssignmentComplete(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, resourceGroupName string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForResourceGroupLevelPolicyAssignment") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForResourceGroupLevelPolicyAssignment(ctx, policyStatesResource, subscriptionID, resourceGroupName, policyAssignmentName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForSubscription queries policy states for the resources under the subscription. -// Parameters: -// policyStatesResource - the virtual resource under PolicyStates resource type. In a given time range, -// 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). -// subscriptionID - microsoft Azure subscription ID. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyStatesClient) ListQueryResultsForSubscription(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForSubscription") - defer func() { - sc := -1 - if result.psqr.Response.Response != nil { - sc = result.psqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "ListQueryResultsForSubscription", err.Error()) - } - - result.fn = client.listQueryResultsForSubscriptionNextResults - req, err := client.ListQueryResultsForSubscriptionPreparer(ctx, policyStatesResource, subscriptionID, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForSubscriptionSender(req) - if err != nil { - result.psqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForSubscription", resp, "Failure sending request") - return - } - - result.psqr, err = client.ListQueryResultsForSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForSubscription", resp, "Failure responding to request") - return - } - if result.psqr.hasNextLink() && result.psqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForSubscriptionPreparer prepares the ListQueryResultsForSubscription request. -func (client PolicyStatesClient) ListQueryResultsForSubscriptionPreparer(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyStatesResource": autorest.Encode("path", policyStatesResource), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForSubscriptionSender sends the ListQueryResultsForSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) ListQueryResultsForSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForSubscriptionResponder handles the response to the ListQueryResultsForSubscription request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) ListQueryResultsForSubscriptionResponder(resp *http.Response) (result PolicyStatesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForSubscriptionNextResults retrieves the next set of results, if any. -func (client PolicyStatesClient) listQueryResultsForSubscriptionNextResults(ctx context.Context, lastResults PolicyStatesQueryResults) (result PolicyStatesQueryResults, err error) { - req, err := lastResults.policyStatesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForSubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForSubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForSubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForSubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyStatesClient) ListQueryResultsForSubscriptionComplete(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForSubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForSubscription(ctx, policyStatesResource, subscriptionID, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignment queries policy states for the subscription level policy -// assignment. -// Parameters: -// policyStatesResource - the virtual resource under PolicyStates resource type. In a given time range, -// 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). -// subscriptionID - microsoft Azure subscription ID. -// policyAssignmentName - policy assignment name. -// top - maximum number of records to return. -// orderBy - ordering expression using OData notation. One or more comma-separated column names with an -// optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". -// selectParameter - select expression using OData notation. Limits the columns on each record to just those -// requested, e.g. "$select=PolicyAssignmentId, ResourceId". -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -// apply - oData apply expression for aggregations. -// skipToken - skiptoken is only provided if a previous response returned a partial result as a part of -// nextLink element. -func (client PolicyStatesClient) ListQueryResultsForSubscriptionLevelPolicyAssignment(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForSubscriptionLevelPolicyAssignment") - defer func() { - sc := -1 - if result.psqr.Response.Response != nil { - sc = result.psqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "ListQueryResultsForSubscriptionLevelPolicyAssignment", err.Error()) - } - - result.fn = client.listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults - req, err := client.ListQueryResultsForSubscriptionLevelPolicyAssignmentPreparer(ctx, policyStatesResource, subscriptionID, policyAssignmentName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForSubscriptionLevelPolicyAssignment", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForSubscriptionLevelPolicyAssignmentSender(req) - if err != nil { - result.psqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForSubscriptionLevelPolicyAssignment", resp, "Failure sending request") - return - } - - result.psqr, err = client.ListQueryResultsForSubscriptionLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "ListQueryResultsForSubscriptionLevelPolicyAssignment", resp, "Failure responding to request") - return - } - if result.psqr.hasNextLink() && result.psqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignmentPreparer prepares the ListQueryResultsForSubscriptionLevelPolicyAssignment request. -func (client PolicyStatesClient) ListQueryResultsForSubscriptionLevelPolicyAssignmentPreparer(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyAssignmentName": autorest.Encode("path", policyAssignmentName), - "policyStatesResource": autorest.Encode("path", policyStatesResource), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(orderBy) > 0 { - queryParameters["$orderby"] = autorest.Encode("query", orderBy) - } - if len(selectParameter) > 0 { - queryParameters["$select"] = autorest.Encode("query", selectParameter) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - if len(apply) > 0 { - queryParameters["$apply"] = autorest.Encode("query", apply) - } - if len(skipToken) > 0 { - queryParameters["$skiptoken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignmentSender sends the ListQueryResultsForSubscriptionLevelPolicyAssignment request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) ListQueryResultsForSubscriptionLevelPolicyAssignmentSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignmentResponder handles the response to the ListQueryResultsForSubscriptionLevelPolicyAssignment request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) ListQueryResultsForSubscriptionLevelPolicyAssignmentResponder(resp *http.Response) (result PolicyStatesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults retrieves the next set of results, if any. -func (client PolicyStatesClient) listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults(ctx context.Context, lastResults PolicyStatesQueryResults) (result PolicyStatesQueryResults, err error) { - req, err := lastResults.policyStatesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForSubscriptionLevelPolicyAssignmentSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForSubscriptionLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "listQueryResultsForSubscriptionLevelPolicyAssignmentNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForSubscriptionLevelPolicyAssignmentComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyStatesClient) ListQueryResultsForSubscriptionLevelPolicyAssignmentComplete(ctx context.Context, policyStatesResource PolicyStatesResource, subscriptionID string, policyAssignmentName string, top *int32, orderBy string, selectParameter string, from *date.Time, toParameter *date.Time, filter string, apply string, skipToken string) (result PolicyStatesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.ListQueryResultsForSubscriptionLevelPolicyAssignment") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForSubscriptionLevelPolicyAssignment(ctx, policyStatesResource, subscriptionID, policyAssignmentName, top, orderBy, selectParameter, from, toParameter, filter, apply, skipToken) - return -} - -// SummarizeForManagementGroup summarizes policy states for the resources under the management group. -// Parameters: -// managementGroupName - management group name. -// top - maximum number of records to return. -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -func (client PolicyStatesClient) SummarizeForManagementGroup(ctx context.Context, managementGroupName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (result SummarizeResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.SummarizeForManagementGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "SummarizeForManagementGroup", err.Error()) - } - - req, err := client.SummarizeForManagementGroupPreparer(ctx, managementGroupName, top, from, toParameter, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.SummarizeForManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForManagementGroup", resp, "Failure sending request") - return - } - - result, err = client.SummarizeForManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForManagementGroup", resp, "Failure responding to request") - return - } - - return -} - -// SummarizeForManagementGroupPreparer prepares the SummarizeForManagementGroup request. -func (client PolicyStatesClient) SummarizeForManagementGroupPreparer(ctx context.Context, managementGroupName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupName": autorest.Encode("path", managementGroupName), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - "policyStatesSummaryResource": autorest.Encode("path", "latest"), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SummarizeForManagementGroupSender sends the SummarizeForManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) SummarizeForManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// SummarizeForManagementGroupResponder handles the response to the SummarizeForManagementGroup request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) SummarizeForManagementGroupResponder(resp *http.Response) (result SummarizeResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SummarizeForPolicyDefinition summarizes policy states for the subscription level policy definition. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// policyDefinitionName - policy definition name. -// top - maximum number of records to return. -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -func (client PolicyStatesClient) SummarizeForPolicyDefinition(ctx context.Context, subscriptionID string, policyDefinitionName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (result SummarizeResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.SummarizeForPolicyDefinition") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "SummarizeForPolicyDefinition", err.Error()) - } - - req, err := client.SummarizeForPolicyDefinitionPreparer(ctx, subscriptionID, policyDefinitionName, top, from, toParameter, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForPolicyDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.SummarizeForPolicyDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForPolicyDefinition", resp, "Failure sending request") - return - } - - result, err = client.SummarizeForPolicyDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForPolicyDefinition", resp, "Failure responding to request") - return - } - - return -} - -// SummarizeForPolicyDefinitionPreparer prepares the SummarizeForPolicyDefinition request. -func (client PolicyStatesClient) SummarizeForPolicyDefinitionPreparer(ctx context.Context, subscriptionID string, policyDefinitionName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyDefinitionName": autorest.Encode("path", policyDefinitionName), - "policyStatesSummaryResource": autorest.Encode("path", "latest"), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SummarizeForPolicyDefinitionSender sends the SummarizeForPolicyDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) SummarizeForPolicyDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SummarizeForPolicyDefinitionResponder handles the response to the SummarizeForPolicyDefinition request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) SummarizeForPolicyDefinitionResponder(resp *http.Response) (result SummarizeResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SummarizeForPolicySetDefinition summarizes policy states for the subscription level policy set definition. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// policySetDefinitionName - policy set definition name. -// top - maximum number of records to return. -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -func (client PolicyStatesClient) SummarizeForPolicySetDefinition(ctx context.Context, subscriptionID string, policySetDefinitionName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (result SummarizeResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.SummarizeForPolicySetDefinition") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "SummarizeForPolicySetDefinition", err.Error()) - } - - req, err := client.SummarizeForPolicySetDefinitionPreparer(ctx, subscriptionID, policySetDefinitionName, top, from, toParameter, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForPolicySetDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.SummarizeForPolicySetDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForPolicySetDefinition", resp, "Failure sending request") - return - } - - result, err = client.SummarizeForPolicySetDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForPolicySetDefinition", resp, "Failure responding to request") - return - } - - return -} - -// SummarizeForPolicySetDefinitionPreparer prepares the SummarizeForPolicySetDefinition request. -func (client PolicyStatesClient) SummarizeForPolicySetDefinitionPreparer(ctx context.Context, subscriptionID string, policySetDefinitionName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policySetDefinitionName": autorest.Encode("path", policySetDefinitionName), - "policyStatesSummaryResource": autorest.Encode("path", "latest"), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SummarizeForPolicySetDefinitionSender sends the SummarizeForPolicySetDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) SummarizeForPolicySetDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SummarizeForPolicySetDefinitionResponder handles the response to the SummarizeForPolicySetDefinition request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) SummarizeForPolicySetDefinitionResponder(resp *http.Response) (result SummarizeResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SummarizeForResource summarizes policy states for the resource. -// Parameters: -// resourceID - resource ID. -// top - maximum number of records to return. -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -func (client PolicyStatesClient) SummarizeForResource(ctx context.Context, resourceID string, top *int32, from *date.Time, toParameter *date.Time, filter string) (result SummarizeResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.SummarizeForResource") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "SummarizeForResource", err.Error()) - } - - req, err := client.SummarizeForResourcePreparer(ctx, resourceID, top, from, toParameter, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForResource", nil, "Failure preparing request") - return - } - - resp, err := client.SummarizeForResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForResource", resp, "Failure sending request") - return - } - - result, err = client.SummarizeForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForResource", resp, "Failure responding to request") - return - } - - return -} - -// SummarizeForResourcePreparer prepares the SummarizeForResource request. -func (client PolicyStatesClient) SummarizeForResourcePreparer(ctx context.Context, resourceID string, top *int32, from *date.Time, toParameter *date.Time, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyStatesSummaryResource": autorest.Encode("path", "latest"), - "resourceId": resourceID, - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SummarizeForResourceSender sends the SummarizeForResource request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) SummarizeForResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// SummarizeForResourceResponder handles the response to the SummarizeForResource request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) SummarizeForResourceResponder(resp *http.Response) (result SummarizeResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SummarizeForResourceGroup summarizes policy states for the resources under the resource group. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// top - maximum number of records to return. -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -func (client PolicyStatesClient) SummarizeForResourceGroup(ctx context.Context, subscriptionID string, resourceGroupName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (result SummarizeResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.SummarizeForResourceGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "SummarizeForResourceGroup", err.Error()) - } - - req, err := client.SummarizeForResourceGroupPreparer(ctx, subscriptionID, resourceGroupName, top, from, toParameter, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.SummarizeForResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForResourceGroup", resp, "Failure sending request") - return - } - - result, err = client.SummarizeForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForResourceGroup", resp, "Failure responding to request") - return - } - - return -} - -// SummarizeForResourceGroupPreparer prepares the SummarizeForResourceGroup request. -func (client PolicyStatesClient) SummarizeForResourceGroupPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyStatesSummaryResource": autorest.Encode("path", "latest"), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SummarizeForResourceGroupSender sends the SummarizeForResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) SummarizeForResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SummarizeForResourceGroupResponder handles the response to the SummarizeForResourceGroup request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) SummarizeForResourceGroupResponder(resp *http.Response) (result SummarizeResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SummarizeForResourceGroupLevelPolicyAssignment summarizes policy states for the resource group level policy -// assignment. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// policyAssignmentName - policy assignment name. -// top - maximum number of records to return. -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -func (client PolicyStatesClient) SummarizeForResourceGroupLevelPolicyAssignment(ctx context.Context, subscriptionID string, resourceGroupName string, policyAssignmentName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (result SummarizeResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.SummarizeForResourceGroupLevelPolicyAssignment") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "SummarizeForResourceGroupLevelPolicyAssignment", err.Error()) - } - - req, err := client.SummarizeForResourceGroupLevelPolicyAssignmentPreparer(ctx, subscriptionID, resourceGroupName, policyAssignmentName, top, from, toParameter, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForResourceGroupLevelPolicyAssignment", nil, "Failure preparing request") - return - } - - resp, err := client.SummarizeForResourceGroupLevelPolicyAssignmentSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForResourceGroupLevelPolicyAssignment", resp, "Failure sending request") - return - } - - result, err = client.SummarizeForResourceGroupLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForResourceGroupLevelPolicyAssignment", resp, "Failure responding to request") - return - } - - return -} - -// SummarizeForResourceGroupLevelPolicyAssignmentPreparer prepares the SummarizeForResourceGroupLevelPolicyAssignment request. -func (client PolicyStatesClient) SummarizeForResourceGroupLevelPolicyAssignmentPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, policyAssignmentName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyAssignmentName": autorest.Encode("path", policyAssignmentName), - "policyStatesSummaryResource": autorest.Encode("path", "latest"), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SummarizeForResourceGroupLevelPolicyAssignmentSender sends the SummarizeForResourceGroupLevelPolicyAssignment request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) SummarizeForResourceGroupLevelPolicyAssignmentSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SummarizeForResourceGroupLevelPolicyAssignmentResponder handles the response to the SummarizeForResourceGroupLevelPolicyAssignment request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) SummarizeForResourceGroupLevelPolicyAssignmentResponder(resp *http.Response) (result SummarizeResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SummarizeForSubscription summarizes policy states for the resources under the subscription. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// top - maximum number of records to return. -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -func (client PolicyStatesClient) SummarizeForSubscription(ctx context.Context, subscriptionID string, top *int32, from *date.Time, toParameter *date.Time, filter string) (result SummarizeResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.SummarizeForSubscription") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "SummarizeForSubscription", err.Error()) - } - - req, err := client.SummarizeForSubscriptionPreparer(ctx, subscriptionID, top, from, toParameter, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.SummarizeForSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForSubscription", resp, "Failure sending request") - return - } - - result, err = client.SummarizeForSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForSubscription", resp, "Failure responding to request") - return - } - - return -} - -// SummarizeForSubscriptionPreparer prepares the SummarizeForSubscription request. -func (client PolicyStatesClient) SummarizeForSubscriptionPreparer(ctx context.Context, subscriptionID string, top *int32, from *date.Time, toParameter *date.Time, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyStatesSummaryResource": autorest.Encode("path", "latest"), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SummarizeForSubscriptionSender sends the SummarizeForSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) SummarizeForSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SummarizeForSubscriptionResponder handles the response to the SummarizeForSubscription request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) SummarizeForSubscriptionResponder(resp *http.Response) (result SummarizeResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SummarizeForSubscriptionLevelPolicyAssignment summarizes policy states for the subscription level policy assignment. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// policyAssignmentName - policy assignment name. -// top - maximum number of records to return. -// from - ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, -// the service uses ($to - 1-day). -// toParameter - ISO 8601 formatted timestamp specifying the end time of the interval to query. When not -// specified, the service uses request time. -// filter - oData filter expression. -func (client PolicyStatesClient) SummarizeForSubscriptionLevelPolicyAssignment(ctx context.Context, subscriptionID string, policyAssignmentName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (result SummarizeResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.SummarizeForSubscriptionLevelPolicyAssignment") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyStatesClient", "SummarizeForSubscriptionLevelPolicyAssignment", err.Error()) - } - - req, err := client.SummarizeForSubscriptionLevelPolicyAssignmentPreparer(ctx, subscriptionID, policyAssignmentName, top, from, toParameter, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForSubscriptionLevelPolicyAssignment", nil, "Failure preparing request") - return - } - - resp, err := client.SummarizeForSubscriptionLevelPolicyAssignmentSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForSubscriptionLevelPolicyAssignment", resp, "Failure sending request") - return - } - - result, err = client.SummarizeForSubscriptionLevelPolicyAssignmentResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "SummarizeForSubscriptionLevelPolicyAssignment", resp, "Failure responding to request") - return - } - - return -} - -// SummarizeForSubscriptionLevelPolicyAssignmentPreparer prepares the SummarizeForSubscriptionLevelPolicyAssignment request. -func (client PolicyStatesClient) SummarizeForSubscriptionLevelPolicyAssignmentPreparer(ctx context.Context, subscriptionID string, policyAssignmentName string, top *int32, from *date.Time, toParameter *date.Time, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationNamespace": autorest.Encode("path", "Microsoft.Authorization"), - "policyAssignmentName": autorest.Encode("path", policyAssignmentName), - "policyStatesSummaryResource": autorest.Encode("path", "latest"), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if from != nil { - queryParameters["$from"] = autorest.Encode("query", *from) - } - if toParameter != nil { - queryParameters["$to"] = autorest.Encode("query", *toParameter) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SummarizeForSubscriptionLevelPolicyAssignmentSender sends the SummarizeForSubscriptionLevelPolicyAssignment request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) SummarizeForSubscriptionLevelPolicyAssignmentSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SummarizeForSubscriptionLevelPolicyAssignmentResponder handles the response to the SummarizeForSubscriptionLevelPolicyAssignment request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) SummarizeForSubscriptionLevelPolicyAssignmentResponder(resp *http.Response) (result SummarizeResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// TriggerResourceGroupEvaluation triggers a policy evaluation scan for all the resources under the resource group. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -func (client PolicyStatesClient) TriggerResourceGroupEvaluation(ctx context.Context, subscriptionID string, resourceGroupName string) (result PolicyStatesTriggerResourceGroupEvaluationFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.TriggerResourceGroupEvaluation") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.TriggerResourceGroupEvaluationPreparer(ctx, subscriptionID, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "TriggerResourceGroupEvaluation", nil, "Failure preparing request") - return - } - - result, err = client.TriggerResourceGroupEvaluationSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "TriggerResourceGroupEvaluation", result.Response(), "Failure sending request") - return - } - - return -} - -// TriggerResourceGroupEvaluationPreparer prepares the TriggerResourceGroupEvaluation request. -func (client PolicyStatesClient) TriggerResourceGroupEvaluationPreparer(ctx context.Context, subscriptionID string, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-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.PolicyInsights/policyStates/latest/triggerEvaluation", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// TriggerResourceGroupEvaluationSender sends the TriggerResourceGroupEvaluation request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) TriggerResourceGroupEvaluationSender(req *http.Request) (future PolicyStatesTriggerResourceGroupEvaluationFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// TriggerResourceGroupEvaluationResponder handles the response to the TriggerResourceGroupEvaluation request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) TriggerResourceGroupEvaluationResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// TriggerSubscriptionEvaluation triggers a policy evaluation scan for all the resources under the subscription -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -func (client PolicyStatesClient) TriggerSubscriptionEvaluation(ctx context.Context, subscriptionID string) (result PolicyStatesTriggerSubscriptionEvaluationFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyStatesClient.TriggerSubscriptionEvaluation") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.TriggerSubscriptionEvaluationPreparer(ctx, subscriptionID) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "TriggerSubscriptionEvaluation", nil, "Failure preparing request") - return - } - - result, err = client.TriggerSubscriptionEvaluationSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyStatesClient", "TriggerSubscriptionEvaluation", result.Response(), "Failure sending request") - return - } - - return -} - -// TriggerSubscriptionEvaluationPreparer prepares the TriggerSubscriptionEvaluation request. -func (client PolicyStatesClient) TriggerSubscriptionEvaluationPreparer(ctx context.Context, subscriptionID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// TriggerSubscriptionEvaluationSender sends the TriggerSubscriptionEvaluation request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyStatesClient) TriggerSubscriptionEvaluationSender(req *http.Request) (future PolicyStatesTriggerSubscriptionEvaluationFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// TriggerSubscriptionEvaluationResponder handles the response to the TriggerSubscriptionEvaluation request. The method always -// closes the http.Response Body. -func (client PolicyStatesClient) TriggerSubscriptionEvaluationResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policytrackedresources.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policytrackedresources.go deleted file mode 100644 index 112329726600..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/policytrackedresources.go +++ /dev/null @@ -1,560 +0,0 @@ -package policyinsights - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PolicyTrackedResourcesClient is the client for the PolicyTrackedResources methods of the Policyinsights service. -type PolicyTrackedResourcesClient struct { - BaseClient -} - -// NewPolicyTrackedResourcesClient creates an instance of the PolicyTrackedResourcesClient client. -func NewPolicyTrackedResourcesClient() PolicyTrackedResourcesClient { - return NewPolicyTrackedResourcesClientWithBaseURI(DefaultBaseURI) -} - -// NewPolicyTrackedResourcesClientWithBaseURI creates an instance of the PolicyTrackedResourcesClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewPolicyTrackedResourcesClientWithBaseURI(baseURI string) PolicyTrackedResourcesClient { - return PolicyTrackedResourcesClient{NewWithBaseURI(baseURI)} -} - -// ListQueryResultsForManagementGroup queries policy tracked resources under the management group. -// Parameters: -// managementGroupName - management group name. -// top - maximum number of records to return. -// filter - oData filter expression. -func (client PolicyTrackedResourcesClient) ListQueryResultsForManagementGroup(ctx context.Context, managementGroupName string, top *int32, filter string) (result PolicyTrackedResourcesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesClient.ListQueryResultsForManagementGroup") - defer func() { - sc := -1 - if result.ptrqr.Response.Response != nil { - sc = result.ptrqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForManagementGroup", err.Error()) - } - - result.fn = client.listQueryResultsForManagementGroupNextResults - req, err := client.ListQueryResultsForManagementGroupPreparer(ctx, managementGroupName, top, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForManagementGroupSender(req) - if err != nil { - result.ptrqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForManagementGroup", resp, "Failure sending request") - return - } - - result.ptrqr, err = client.ListQueryResultsForManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForManagementGroup", resp, "Failure responding to request") - return - } - if result.ptrqr.hasNextLink() && result.ptrqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForManagementGroupPreparer prepares the ListQueryResultsForManagementGroup request. -func (client PolicyTrackedResourcesClient) ListQueryResultsForManagementGroupPreparer(ctx context.Context, managementGroupName string, top *int32, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupName": autorest.Encode("path", managementGroupName), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - "policyTrackedResourcesResource": autorest.Encode("path", "default"), - } - - const APIVersion = "2018-07-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForManagementGroupSender sends the ListQueryResultsForManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyTrackedResourcesClient) ListQueryResultsForManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListQueryResultsForManagementGroupResponder handles the response to the ListQueryResultsForManagementGroup request. The method always -// closes the http.Response Body. -func (client PolicyTrackedResourcesClient) ListQueryResultsForManagementGroupResponder(resp *http.Response) (result PolicyTrackedResourcesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForManagementGroupNextResults retrieves the next set of results, if any. -func (client PolicyTrackedResourcesClient) listQueryResultsForManagementGroupNextResults(ctx context.Context, lastResults PolicyTrackedResourcesQueryResults) (result PolicyTrackedResourcesQueryResults, err error) { - req, err := lastResults.policyTrackedResourcesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForManagementGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForManagementGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForManagementGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForManagementGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyTrackedResourcesClient) ListQueryResultsForManagementGroupComplete(ctx context.Context, managementGroupName string, top *int32, filter string) (result PolicyTrackedResourcesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesClient.ListQueryResultsForManagementGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForManagementGroup(ctx, managementGroupName, top, filter) - return -} - -// ListQueryResultsForResource queries policy tracked resources under the resource. -// Parameters: -// resourceID - resource ID. -// top - maximum number of records to return. -// filter - oData filter expression. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResource(ctx context.Context, resourceID string, top *int32, filter string) (result PolicyTrackedResourcesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesClient.ListQueryResultsForResource") - defer func() { - sc := -1 - if result.ptrqr.Response.Response != nil { - sc = result.ptrqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForResource", err.Error()) - } - - result.fn = client.listQueryResultsForResourceNextResults - req, err := client.ListQueryResultsForResourcePreparer(ctx, resourceID, top, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForResource", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForResourceSender(req) - if err != nil { - result.ptrqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForResource", resp, "Failure sending request") - return - } - - result.ptrqr, err = client.ListQueryResultsForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForResource", resp, "Failure responding to request") - return - } - if result.ptrqr.hasNextLink() && result.ptrqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForResourcePreparer prepares the ListQueryResultsForResource request. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResourcePreparer(ctx context.Context, resourceID string, top *int32, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyTrackedResourcesResource": autorest.Encode("path", "default"), - "resourceId": resourceID, - } - - const APIVersion = "2018-07-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForResourceSender sends the ListQueryResultsForResource request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListQueryResultsForResourceResponder handles the response to the ListQueryResultsForResource request. The method always -// closes the http.Response Body. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResourceResponder(resp *http.Response) (result PolicyTrackedResourcesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForResourceNextResults retrieves the next set of results, if any. -func (client PolicyTrackedResourcesClient) listQueryResultsForResourceNextResults(ctx context.Context, lastResults PolicyTrackedResourcesQueryResults) (result PolicyTrackedResourcesQueryResults, err error) { - req, err := lastResults.policyTrackedResourcesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForResourceNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForResourceNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForResourceNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForResourceComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResourceComplete(ctx context.Context, resourceID string, top *int32, filter string) (result PolicyTrackedResourcesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesClient.ListQueryResultsForResource") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForResource(ctx, resourceID, top, filter) - return -} - -// ListQueryResultsForResourceGroup queries policy tracked resources under the resource group. -// Parameters: -// resourceGroupName - resource group name. -// subscriptionID - microsoft Azure subscription ID. -// top - maximum number of records to return. -// filter - oData filter expression. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResourceGroup(ctx context.Context, resourceGroupName string, subscriptionID string, top *int32, filter string) (result PolicyTrackedResourcesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesClient.ListQueryResultsForResourceGroup") - defer func() { - sc := -1 - if result.ptrqr.Response.Response != nil { - sc = result.ptrqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForResourceGroup", err.Error()) - } - - result.fn = client.listQueryResultsForResourceGroupNextResults - req, err := client.ListQueryResultsForResourceGroupPreparer(ctx, resourceGroupName, subscriptionID, top, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForResourceGroupSender(req) - if err != nil { - result.ptrqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForResourceGroup", resp, "Failure sending request") - return - } - - result.ptrqr, err = client.ListQueryResultsForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForResourceGroup", resp, "Failure responding to request") - return - } - if result.ptrqr.hasNextLink() && result.ptrqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForResourceGroupPreparer prepares the ListQueryResultsForResourceGroup request. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResourceGroupPreparer(ctx context.Context, resourceGroupName string, subscriptionID string, top *int32, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyTrackedResourcesResource": autorest.Encode("path", "default"), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2018-07-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForResourceGroupSender sends the ListQueryResultsForResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForResourceGroupResponder handles the response to the ListQueryResultsForResourceGroup request. The method always -// closes the http.Response Body. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResourceGroupResponder(resp *http.Response) (result PolicyTrackedResourcesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForResourceGroupNextResults retrieves the next set of results, if any. -func (client PolicyTrackedResourcesClient) listQueryResultsForResourceGroupNextResults(ctx context.Context, lastResults PolicyTrackedResourcesQueryResults) (result PolicyTrackedResourcesQueryResults, err error) { - req, err := lastResults.policyTrackedResourcesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyTrackedResourcesClient) ListQueryResultsForResourceGroupComplete(ctx context.Context, resourceGroupName string, subscriptionID string, top *int32, filter string) (result PolicyTrackedResourcesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesClient.ListQueryResultsForResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForResourceGroup(ctx, resourceGroupName, subscriptionID, top, filter) - return -} - -// ListQueryResultsForSubscription queries policy tracked resources under the subscription. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// top - maximum number of records to return. -// filter - oData filter expression. -func (client PolicyTrackedResourcesClient) ListQueryResultsForSubscription(ctx context.Context, subscriptionID string, top *int32, filter string) (result PolicyTrackedResourcesQueryResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesClient.ListQueryResultsForSubscription") - defer func() { - sc := -1 - if result.ptrqr.Response.Response != nil { - sc = result.ptrqr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForSubscription", err.Error()) - } - - result.fn = client.listQueryResultsForSubscriptionNextResults - req, err := client.ListQueryResultsForSubscriptionPreparer(ctx, subscriptionID, top, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListQueryResultsForSubscriptionSender(req) - if err != nil { - result.ptrqr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForSubscription", resp, "Failure sending request") - return - } - - result.ptrqr, err = client.ListQueryResultsForSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "ListQueryResultsForSubscription", resp, "Failure responding to request") - return - } - if result.ptrqr.hasNextLink() && result.ptrqr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListQueryResultsForSubscriptionPreparer prepares the ListQueryResultsForSubscription request. -func (client PolicyTrackedResourcesClient) ListQueryResultsForSubscriptionPreparer(ctx context.Context, subscriptionID string, top *int32, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyTrackedResourcesResource": autorest.Encode("path", "default"), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2018-07-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListQueryResultsForSubscriptionSender sends the ListQueryResultsForSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client PolicyTrackedResourcesClient) ListQueryResultsForSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListQueryResultsForSubscriptionResponder handles the response to the ListQueryResultsForSubscription request. The method always -// closes the http.Response Body. -func (client PolicyTrackedResourcesClient) ListQueryResultsForSubscriptionResponder(resp *http.Response) (result PolicyTrackedResourcesQueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listQueryResultsForSubscriptionNextResults retrieves the next set of results, if any. -func (client PolicyTrackedResourcesClient) listQueryResultsForSubscriptionNextResults(ctx context.Context, lastResults PolicyTrackedResourcesQueryResults) (result PolicyTrackedResourcesQueryResults, err error) { - req, err := lastResults.policyTrackedResourcesQueryResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForSubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListQueryResultsForSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForSubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListQueryResultsForSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.PolicyTrackedResourcesClient", "listQueryResultsForSubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListQueryResultsForSubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client PolicyTrackedResourcesClient) ListQueryResultsForSubscriptionComplete(ctx context.Context, subscriptionID string, top *int32, filter string) (result PolicyTrackedResourcesQueryResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PolicyTrackedResourcesClient.ListQueryResultsForSubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListQueryResultsForSubscription(ctx, subscriptionID, top, filter) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/remediations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/remediations.go deleted file mode 100644 index 6f14bcc39333..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/remediations.go +++ /dev/null @@ -1,2306 +0,0 @@ -package policyinsights - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RemediationsClient is the client for the Remediations methods of the Policyinsights service. -type RemediationsClient struct { - BaseClient -} - -// NewRemediationsClient creates an instance of the RemediationsClient client. -func NewRemediationsClient() RemediationsClient { - return NewRemediationsClientWithBaseURI(DefaultBaseURI) -} - -// NewRemediationsClientWithBaseURI creates an instance of the RemediationsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRemediationsClientWithBaseURI(baseURI string) RemediationsClient { - return RemediationsClient{NewWithBaseURI(baseURI)} -} - -// CancelAtManagementGroup cancels a remediation at management group scope. -// Parameters: -// managementGroupID - management group ID. -// remediationName - the name of the remediation. -func (client RemediationsClient) CancelAtManagementGroup(ctx context.Context, managementGroupID string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.CancelAtManagementGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CancelAtManagementGroupPreparer(ctx, managementGroupID, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.CancelAtManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtManagementGroup", resp, "Failure sending request") - return - } - - result, err = client.CancelAtManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtManagementGroup", resp, "Failure responding to request") - return - } - - return -} - -// CancelAtManagementGroupPreparer prepares the CancelAtManagementGroup request. -func (client RemediationsClient) CancelAtManagementGroupPreparer(ctx context.Context, managementGroupID string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - "remediationName": autorest.Encode("path", remediationName), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CancelAtManagementGroupSender sends the CancelAtManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) CancelAtManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CancelAtManagementGroupResponder handles the response to the CancelAtManagementGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) CancelAtManagementGroupResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CancelAtResource cancel a remediation at resource scope. -// Parameters: -// resourceID - resource ID. -// remediationName - the name of the remediation. -func (client RemediationsClient) CancelAtResource(ctx context.Context, resourceID string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.CancelAtResource") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CancelAtResourcePreparer(ctx, resourceID, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtResource", nil, "Failure preparing request") - return - } - - resp, err := client.CancelAtResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtResource", resp, "Failure sending request") - return - } - - result, err = client.CancelAtResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtResource", resp, "Failure responding to request") - return - } - - return -} - -// CancelAtResourcePreparer prepares the CancelAtResource request. -func (client RemediationsClient) CancelAtResourcePreparer(ctx context.Context, resourceID string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceId": resourceID, - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CancelAtResourceSender sends the CancelAtResource request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) CancelAtResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CancelAtResourceResponder handles the response to the CancelAtResource request. The method always -// closes the http.Response Body. -func (client RemediationsClient) CancelAtResourceResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CancelAtResourceGroup cancels a remediation at resource group scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// remediationName - the name of the remediation. -func (client RemediationsClient) CancelAtResourceGroup(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.CancelAtResourceGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CancelAtResourceGroupPreparer(ctx, subscriptionID, resourceGroupName, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.CancelAtResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtResourceGroup", resp, "Failure sending request") - return - } - - result, err = client.CancelAtResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtResourceGroup", resp, "Failure responding to request") - return - } - - return -} - -// CancelAtResourceGroupPreparer prepares the CancelAtResourceGroup request. -func (client RemediationsClient) CancelAtResourceGroupPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-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.PolicyInsights/remediations/{remediationName}/cancel", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CancelAtResourceGroupSender sends the CancelAtResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) CancelAtResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CancelAtResourceGroupResponder handles the response to the CancelAtResourceGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) CancelAtResourceGroupResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CancelAtSubscription cancels a remediation at subscription scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// remediationName - the name of the remediation. -func (client RemediationsClient) CancelAtSubscription(ctx context.Context, subscriptionID string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.CancelAtSubscription") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CancelAtSubscriptionPreparer(ctx, subscriptionID, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.CancelAtSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtSubscription", resp, "Failure sending request") - return - } - - result, err = client.CancelAtSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CancelAtSubscription", resp, "Failure responding to request") - return - } - - return -} - -// CancelAtSubscriptionPreparer prepares the CancelAtSubscription request. -func (client RemediationsClient) CancelAtSubscriptionPreparer(ctx context.Context, subscriptionID string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CancelAtSubscriptionSender sends the CancelAtSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) CancelAtSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CancelAtSubscriptionResponder handles the response to the CancelAtSubscription request. The method always -// closes the http.Response Body. -func (client RemediationsClient) CancelAtSubscriptionResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdateAtManagementGroup creates or updates a remediation at management group scope. -// Parameters: -// managementGroupID - management group ID. -// remediationName - the name of the remediation. -// parameters - the remediation parameters. -func (client RemediationsClient) CreateOrUpdateAtManagementGroup(ctx context.Context, managementGroupID string, remediationName string, parameters Remediation) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.CreateOrUpdateAtManagementGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdateAtManagementGroupPreparer(ctx, managementGroupID, remediationName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateAtManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtManagementGroup", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateAtManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtManagementGroup", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdateAtManagementGroupPreparer prepares the CreateOrUpdateAtManagementGroup request. -func (client RemediationsClient) CreateOrUpdateAtManagementGroupPreparer(ctx context.Context, managementGroupID string, remediationName string, parameters Remediation) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - "remediationName": autorest.Encode("path", remediationName), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.ID = nil - parameters.Type = nil - parameters.Name = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateAtManagementGroupSender sends the CreateOrUpdateAtManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) CreateOrUpdateAtManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateOrUpdateAtManagementGroupResponder handles the response to the CreateOrUpdateAtManagementGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) CreateOrUpdateAtManagementGroupResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdateAtResource creates or updates a remediation at resource scope. -// Parameters: -// resourceID - resource ID. -// remediationName - the name of the remediation. -// parameters - the remediation parameters. -func (client RemediationsClient) CreateOrUpdateAtResource(ctx context.Context, resourceID string, remediationName string, parameters Remediation) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.CreateOrUpdateAtResource") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdateAtResourcePreparer(ctx, resourceID, remediationName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtResource", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateAtResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtResource", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateAtResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtResource", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdateAtResourcePreparer prepares the CreateOrUpdateAtResource request. -func (client RemediationsClient) CreateOrUpdateAtResourcePreparer(ctx context.Context, resourceID string, remediationName string, parameters Remediation) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceId": resourceID, - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.ID = nil - parameters.Type = nil - parameters.Name = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateAtResourceSender sends the CreateOrUpdateAtResource request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) CreateOrUpdateAtResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateOrUpdateAtResourceResponder handles the response to the CreateOrUpdateAtResource request. The method always -// closes the http.Response Body. -func (client RemediationsClient) CreateOrUpdateAtResourceResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdateAtResourceGroup creates or updates a remediation at resource group scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// remediationName - the name of the remediation. -// parameters - the remediation parameters. -func (client RemediationsClient) CreateOrUpdateAtResourceGroup(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string, parameters Remediation) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.CreateOrUpdateAtResourceGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdateAtResourceGroupPreparer(ctx, subscriptionID, resourceGroupName, remediationName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateAtResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtResourceGroup", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateAtResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtResourceGroup", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdateAtResourceGroupPreparer prepares the CreateOrUpdateAtResourceGroup request. -func (client RemediationsClient) CreateOrUpdateAtResourceGroupPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string, parameters Remediation) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.ID = nil - parameters.Type = nil - parameters.Name = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateAtResourceGroupSender sends the CreateOrUpdateAtResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) CreateOrUpdateAtResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateAtResourceGroupResponder handles the response to the CreateOrUpdateAtResourceGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) CreateOrUpdateAtResourceGroupResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdateAtSubscription creates or updates a remediation at subscription scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// remediationName - the name of the remediation. -// parameters - the remediation parameters. -func (client RemediationsClient) CreateOrUpdateAtSubscription(ctx context.Context, subscriptionID string, remediationName string, parameters Remediation) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.CreateOrUpdateAtSubscription") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdateAtSubscriptionPreparer(ctx, subscriptionID, remediationName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateAtSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtSubscription", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateAtSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "CreateOrUpdateAtSubscription", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdateAtSubscriptionPreparer prepares the CreateOrUpdateAtSubscription request. -func (client RemediationsClient) CreateOrUpdateAtSubscriptionPreparer(ctx context.Context, subscriptionID string, remediationName string, parameters Remediation) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.ID = nil - parameters.Type = nil - parameters.Name = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateAtSubscriptionSender sends the CreateOrUpdateAtSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) CreateOrUpdateAtSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateAtSubscriptionResponder handles the response to the CreateOrUpdateAtSubscription request. The method always -// closes the http.Response Body. -func (client RemediationsClient) CreateOrUpdateAtSubscriptionResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteAtManagementGroup deletes an existing remediation at management group scope. -// Parameters: -// managementGroupID - management group ID. -// remediationName - the name of the remediation. -func (client RemediationsClient) DeleteAtManagementGroup(ctx context.Context, managementGroupID string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.DeleteAtManagementGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteAtManagementGroupPreparer(ctx, managementGroupID, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteAtManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtManagementGroup", resp, "Failure sending request") - return - } - - result, err = client.DeleteAtManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtManagementGroup", resp, "Failure responding to request") - return - } - - return -} - -// DeleteAtManagementGroupPreparer prepares the DeleteAtManagementGroup request. -func (client RemediationsClient) DeleteAtManagementGroupPreparer(ctx context.Context, managementGroupID string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - "remediationName": autorest.Encode("path", remediationName), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteAtManagementGroupSender sends the DeleteAtManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) DeleteAtManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteAtManagementGroupResponder handles the response to the DeleteAtManagementGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) DeleteAtManagementGroupResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteAtResource deletes an existing remediation at individual resource scope. -// Parameters: -// resourceID - resource ID. -// remediationName - the name of the remediation. -func (client RemediationsClient) DeleteAtResource(ctx context.Context, resourceID string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.DeleteAtResource") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteAtResourcePreparer(ctx, resourceID, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtResource", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteAtResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtResource", resp, "Failure sending request") - return - } - - result, err = client.DeleteAtResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtResource", resp, "Failure responding to request") - return - } - - return -} - -// DeleteAtResourcePreparer prepares the DeleteAtResource request. -func (client RemediationsClient) DeleteAtResourcePreparer(ctx context.Context, resourceID string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceId": resourceID, - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteAtResourceSender sends the DeleteAtResource request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) DeleteAtResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteAtResourceResponder handles the response to the DeleteAtResource request. The method always -// closes the http.Response Body. -func (client RemediationsClient) DeleteAtResourceResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteAtResourceGroup deletes an existing remediation at resource group scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// remediationName - the name of the remediation. -func (client RemediationsClient) DeleteAtResourceGroup(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.DeleteAtResourceGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteAtResourceGroupPreparer(ctx, subscriptionID, resourceGroupName, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteAtResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtResourceGroup", resp, "Failure sending request") - return - } - - result, err = client.DeleteAtResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtResourceGroup", resp, "Failure responding to request") - return - } - - return -} - -// DeleteAtResourceGroupPreparer prepares the DeleteAtResourceGroup request. -func (client RemediationsClient) DeleteAtResourceGroupPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-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.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteAtResourceGroupSender sends the DeleteAtResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) DeleteAtResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteAtResourceGroupResponder handles the response to the DeleteAtResourceGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) DeleteAtResourceGroupResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteAtSubscription deletes an existing remediation at subscription scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// remediationName - the name of the remediation. -func (client RemediationsClient) DeleteAtSubscription(ctx context.Context, subscriptionID string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.DeleteAtSubscription") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteAtSubscriptionPreparer(ctx, subscriptionID, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteAtSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtSubscription", resp, "Failure sending request") - return - } - - result, err = client.DeleteAtSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "DeleteAtSubscription", resp, "Failure responding to request") - return - } - - return -} - -// DeleteAtSubscriptionPreparer prepares the DeleteAtSubscription request. -func (client RemediationsClient) DeleteAtSubscriptionPreparer(ctx context.Context, subscriptionID string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteAtSubscriptionSender sends the DeleteAtSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) DeleteAtSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteAtSubscriptionResponder handles the response to the DeleteAtSubscription request. The method always -// closes the http.Response Body. -func (client RemediationsClient) DeleteAtSubscriptionResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetAtManagementGroup gets an existing remediation at management group scope. -// Parameters: -// managementGroupID - management group ID. -// remediationName - the name of the remediation. -func (client RemediationsClient) GetAtManagementGroup(ctx context.Context, managementGroupID string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.GetAtManagementGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetAtManagementGroupPreparer(ctx, managementGroupID, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.GetAtManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtManagementGroup", resp, "Failure sending request") - return - } - - result, err = client.GetAtManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtManagementGroup", resp, "Failure responding to request") - return - } - - return -} - -// GetAtManagementGroupPreparer prepares the GetAtManagementGroup request. -func (client RemediationsClient) GetAtManagementGroupPreparer(ctx context.Context, managementGroupID string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - "remediationName": autorest.Encode("path", remediationName), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetAtManagementGroupSender sends the GetAtManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) GetAtManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetAtManagementGroupResponder handles the response to the GetAtManagementGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) GetAtManagementGroupResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetAtResource gets an existing remediation at resource scope. -// Parameters: -// resourceID - resource ID. -// remediationName - the name of the remediation. -func (client RemediationsClient) GetAtResource(ctx context.Context, resourceID string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.GetAtResource") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetAtResourcePreparer(ctx, resourceID, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtResource", nil, "Failure preparing request") - return - } - - resp, err := client.GetAtResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtResource", resp, "Failure sending request") - return - } - - result, err = client.GetAtResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtResource", resp, "Failure responding to request") - return - } - - return -} - -// GetAtResourcePreparer prepares the GetAtResource request. -func (client RemediationsClient) GetAtResourcePreparer(ctx context.Context, resourceID string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceId": resourceID, - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetAtResourceSender sends the GetAtResource request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) GetAtResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetAtResourceResponder handles the response to the GetAtResource request. The method always -// closes the http.Response Body. -func (client RemediationsClient) GetAtResourceResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetAtResourceGroup gets an existing remediation at resource group scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// remediationName - the name of the remediation. -func (client RemediationsClient) GetAtResourceGroup(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.GetAtResourceGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetAtResourceGroupPreparer(ctx, subscriptionID, resourceGroupName, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.GetAtResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtResourceGroup", resp, "Failure sending request") - return - } - - result, err = client.GetAtResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtResourceGroup", resp, "Failure responding to request") - return - } - - return -} - -// GetAtResourceGroupPreparer prepares the GetAtResourceGroup request. -func (client RemediationsClient) GetAtResourceGroupPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-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.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetAtResourceGroupSender sends the GetAtResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) GetAtResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetAtResourceGroupResponder handles the response to the GetAtResourceGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) GetAtResourceGroupResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetAtSubscription gets an existing remediation at subscription scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// remediationName - the name of the remediation. -func (client RemediationsClient) GetAtSubscription(ctx context.Context, subscriptionID string, remediationName string) (result Remediation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.GetAtSubscription") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetAtSubscriptionPreparer(ctx, subscriptionID, remediationName) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.GetAtSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtSubscription", resp, "Failure sending request") - return - } - - result, err = client.GetAtSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "GetAtSubscription", resp, "Failure responding to request") - return - } - - return -} - -// GetAtSubscriptionPreparer prepares the GetAtSubscription request. -func (client RemediationsClient) GetAtSubscriptionPreparer(ctx context.Context, subscriptionID string, remediationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetAtSubscriptionSender sends the GetAtSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) GetAtSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetAtSubscriptionResponder handles the response to the GetAtSubscription request. The method always -// closes the http.Response Body. -func (client RemediationsClient) GetAtSubscriptionResponder(resp *http.Response) (result Remediation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListDeploymentsAtManagementGroup gets all deployments for a remediation at management group scope. -// Parameters: -// managementGroupID - management group ID. -// remediationName - the name of the remediation. -// top - maximum number of records to return. -func (client RemediationsClient) ListDeploymentsAtManagementGroup(ctx context.Context, managementGroupID string, remediationName string, top *int32) (result RemediationDeploymentsListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListDeploymentsAtManagementGroup") - defer func() { - sc := -1 - if result.rdlr.Response.Response != nil { - sc = result.rdlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.RemediationsClient", "ListDeploymentsAtManagementGroup", err.Error()) - } - - result.fn = client.listDeploymentsAtManagementGroupNextResults - req, err := client.ListDeploymentsAtManagementGroupPreparer(ctx, managementGroupID, remediationName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListDeploymentsAtManagementGroupSender(req) - if err != nil { - result.rdlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtManagementGroup", resp, "Failure sending request") - return - } - - result.rdlr, err = client.ListDeploymentsAtManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtManagementGroup", resp, "Failure responding to request") - return - } - if result.rdlr.hasNextLink() && result.rdlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListDeploymentsAtManagementGroupPreparer prepares the ListDeploymentsAtManagementGroup request. -func (client RemediationsClient) ListDeploymentsAtManagementGroupPreparer(ctx context.Context, managementGroupID string, remediationName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - "remediationName": autorest.Encode("path", remediationName), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListDeploymentsAtManagementGroupSender sends the ListDeploymentsAtManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) ListDeploymentsAtManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListDeploymentsAtManagementGroupResponder handles the response to the ListDeploymentsAtManagementGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) ListDeploymentsAtManagementGroupResponder(resp *http.Response) (result RemediationDeploymentsListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listDeploymentsAtManagementGroupNextResults retrieves the next set of results, if any. -func (client RemediationsClient) listDeploymentsAtManagementGroupNextResults(ctx context.Context, lastResults RemediationDeploymentsListResult) (result RemediationDeploymentsListResult, err error) { - req, err := lastResults.remediationDeploymentsListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtManagementGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListDeploymentsAtManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtManagementGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListDeploymentsAtManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtManagementGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListDeploymentsAtManagementGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client RemediationsClient) ListDeploymentsAtManagementGroupComplete(ctx context.Context, managementGroupID string, remediationName string, top *int32) (result RemediationDeploymentsListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListDeploymentsAtManagementGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListDeploymentsAtManagementGroup(ctx, managementGroupID, remediationName, top) - return -} - -// ListDeploymentsAtResource gets all deployments for a remediation at resource scope. -// Parameters: -// resourceID - resource ID. -// remediationName - the name of the remediation. -// top - maximum number of records to return. -func (client RemediationsClient) ListDeploymentsAtResource(ctx context.Context, resourceID string, remediationName string, top *int32) (result RemediationDeploymentsListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListDeploymentsAtResource") - defer func() { - sc := -1 - if result.rdlr.Response.Response != nil { - sc = result.rdlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.RemediationsClient", "ListDeploymentsAtResource", err.Error()) - } - - result.fn = client.listDeploymentsAtResourceNextResults - req, err := client.ListDeploymentsAtResourcePreparer(ctx, resourceID, remediationName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtResource", nil, "Failure preparing request") - return - } - - resp, err := client.ListDeploymentsAtResourceSender(req) - if err != nil { - result.rdlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtResource", resp, "Failure sending request") - return - } - - result.rdlr, err = client.ListDeploymentsAtResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtResource", resp, "Failure responding to request") - return - } - if result.rdlr.hasNextLink() && result.rdlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListDeploymentsAtResourcePreparer prepares the ListDeploymentsAtResource request. -func (client RemediationsClient) ListDeploymentsAtResourcePreparer(ctx context.Context, resourceID string, remediationName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceId": resourceID, - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListDeploymentsAtResourceSender sends the ListDeploymentsAtResource request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) ListDeploymentsAtResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListDeploymentsAtResourceResponder handles the response to the ListDeploymentsAtResource request. The method always -// closes the http.Response Body. -func (client RemediationsClient) ListDeploymentsAtResourceResponder(resp *http.Response) (result RemediationDeploymentsListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listDeploymentsAtResourceNextResults retrieves the next set of results, if any. -func (client RemediationsClient) listDeploymentsAtResourceNextResults(ctx context.Context, lastResults RemediationDeploymentsListResult) (result RemediationDeploymentsListResult, err error) { - req, err := lastResults.remediationDeploymentsListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtResourceNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListDeploymentsAtResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtResourceNextResults", resp, "Failure sending next results request") - } - result, err = client.ListDeploymentsAtResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtResourceNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListDeploymentsAtResourceComplete enumerates all values, automatically crossing page boundaries as required. -func (client RemediationsClient) ListDeploymentsAtResourceComplete(ctx context.Context, resourceID string, remediationName string, top *int32) (result RemediationDeploymentsListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListDeploymentsAtResource") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListDeploymentsAtResource(ctx, resourceID, remediationName, top) - return -} - -// ListDeploymentsAtResourceGroup gets all deployments for a remediation at resource group scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// remediationName - the name of the remediation. -// top - maximum number of records to return. -func (client RemediationsClient) ListDeploymentsAtResourceGroup(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string, top *int32) (result RemediationDeploymentsListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListDeploymentsAtResourceGroup") - defer func() { - sc := -1 - if result.rdlr.Response.Response != nil { - sc = result.rdlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.RemediationsClient", "ListDeploymentsAtResourceGroup", err.Error()) - } - - result.fn = client.listDeploymentsAtResourceGroupNextResults - req, err := client.ListDeploymentsAtResourceGroupPreparer(ctx, subscriptionID, resourceGroupName, remediationName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListDeploymentsAtResourceGroupSender(req) - if err != nil { - result.rdlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtResourceGroup", resp, "Failure sending request") - return - } - - result.rdlr, err = client.ListDeploymentsAtResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtResourceGroup", resp, "Failure responding to request") - return - } - if result.rdlr.hasNextLink() && result.rdlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListDeploymentsAtResourceGroupPreparer prepares the ListDeploymentsAtResourceGroup request. -func (client RemediationsClient) ListDeploymentsAtResourceGroupPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListDeploymentsAtResourceGroupSender sends the ListDeploymentsAtResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) ListDeploymentsAtResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListDeploymentsAtResourceGroupResponder handles the response to the ListDeploymentsAtResourceGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) ListDeploymentsAtResourceGroupResponder(resp *http.Response) (result RemediationDeploymentsListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listDeploymentsAtResourceGroupNextResults retrieves the next set of results, if any. -func (client RemediationsClient) listDeploymentsAtResourceGroupNextResults(ctx context.Context, lastResults RemediationDeploymentsListResult) (result RemediationDeploymentsListResult, err error) { - req, err := lastResults.remediationDeploymentsListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListDeploymentsAtResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListDeploymentsAtResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListDeploymentsAtResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client RemediationsClient) ListDeploymentsAtResourceGroupComplete(ctx context.Context, subscriptionID string, resourceGroupName string, remediationName string, top *int32) (result RemediationDeploymentsListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListDeploymentsAtResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListDeploymentsAtResourceGroup(ctx, subscriptionID, resourceGroupName, remediationName, top) - return -} - -// ListDeploymentsAtSubscription gets all deployments for a remediation at subscription scope. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// remediationName - the name of the remediation. -// top - maximum number of records to return. -func (client RemediationsClient) ListDeploymentsAtSubscription(ctx context.Context, subscriptionID string, remediationName string, top *int32) (result RemediationDeploymentsListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListDeploymentsAtSubscription") - defer func() { - sc := -1 - if result.rdlr.Response.Response != nil { - sc = result.rdlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.RemediationsClient", "ListDeploymentsAtSubscription", err.Error()) - } - - result.fn = client.listDeploymentsAtSubscriptionNextResults - req, err := client.ListDeploymentsAtSubscriptionPreparer(ctx, subscriptionID, remediationName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListDeploymentsAtSubscriptionSender(req) - if err != nil { - result.rdlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtSubscription", resp, "Failure sending request") - return - } - - result.rdlr, err = client.ListDeploymentsAtSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListDeploymentsAtSubscription", resp, "Failure responding to request") - return - } - if result.rdlr.hasNextLink() && result.rdlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListDeploymentsAtSubscriptionPreparer prepares the ListDeploymentsAtSubscription request. -func (client RemediationsClient) ListDeploymentsAtSubscriptionPreparer(ctx context.Context, subscriptionID string, remediationName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "remediationName": autorest.Encode("path", remediationName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListDeploymentsAtSubscriptionSender sends the ListDeploymentsAtSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) ListDeploymentsAtSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListDeploymentsAtSubscriptionResponder handles the response to the ListDeploymentsAtSubscription request. The method always -// closes the http.Response Body. -func (client RemediationsClient) ListDeploymentsAtSubscriptionResponder(resp *http.Response) (result RemediationDeploymentsListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listDeploymentsAtSubscriptionNextResults retrieves the next set of results, if any. -func (client RemediationsClient) listDeploymentsAtSubscriptionNextResults(ctx context.Context, lastResults RemediationDeploymentsListResult) (result RemediationDeploymentsListResult, err error) { - req, err := lastResults.remediationDeploymentsListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtSubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListDeploymentsAtSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtSubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListDeploymentsAtSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listDeploymentsAtSubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListDeploymentsAtSubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client RemediationsClient) ListDeploymentsAtSubscriptionComplete(ctx context.Context, subscriptionID string, remediationName string, top *int32) (result RemediationDeploymentsListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListDeploymentsAtSubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListDeploymentsAtSubscription(ctx, subscriptionID, remediationName, top) - return -} - -// ListForManagementGroup gets all remediations for the management group. -// Parameters: -// managementGroupID - management group ID. -// top - maximum number of records to return. -// filter - oData filter expression. -func (client RemediationsClient) ListForManagementGroup(ctx context.Context, managementGroupID string, top *int32, filter string) (result RemediationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListForManagementGroup") - defer func() { - sc := -1 - if result.rlr.Response.Response != nil { - sc = result.rlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.RemediationsClient", "ListForManagementGroup", err.Error()) - } - - result.fn = client.listForManagementGroupNextResults - req, err := client.ListForManagementGroupPreparer(ctx, managementGroupID, top, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForManagementGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListForManagementGroupSender(req) - if err != nil { - result.rlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForManagementGroup", resp, "Failure sending request") - return - } - - result.rlr, err = client.ListForManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForManagementGroup", resp, "Failure responding to request") - return - } - if result.rlr.hasNextLink() && result.rlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListForManagementGroupPreparer prepares the ListForManagementGroup request. -func (client RemediationsClient) ListForManagementGroupPreparer(ctx context.Context, managementGroupID string, top *int32, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - "managementGroupsNamespace": autorest.Encode("path", "Microsoft.Management"), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForManagementGroupSender sends the ListForManagementGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) ListForManagementGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListForManagementGroupResponder handles the response to the ListForManagementGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) ListForManagementGroupResponder(resp *http.Response) (result RemediationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForManagementGroupNextResults retrieves the next set of results, if any. -func (client RemediationsClient) listForManagementGroupNextResults(ctx context.Context, lastResults RemediationListResult) (result RemediationListResult, err error) { - req, err := lastResults.remediationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForManagementGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForManagementGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForManagementGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForManagementGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForManagementGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForManagementGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client RemediationsClient) ListForManagementGroupComplete(ctx context.Context, managementGroupID string, top *int32, filter string) (result RemediationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListForManagementGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListForManagementGroup(ctx, managementGroupID, top, filter) - return -} - -// ListForResource gets all remediations for a resource. -// Parameters: -// resourceID - resource ID. -// top - maximum number of records to return. -// filter - oData filter expression. -func (client RemediationsClient) ListForResource(ctx context.Context, resourceID string, top *int32, filter string) (result RemediationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListForResource") - defer func() { - sc := -1 - if result.rlr.Response.Response != nil { - sc = result.rlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.RemediationsClient", "ListForResource", err.Error()) - } - - result.fn = client.listForResourceNextResults - req, err := client.ListForResourcePreparer(ctx, resourceID, top, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForResource", nil, "Failure preparing request") - return - } - - resp, err := client.ListForResourceSender(req) - if err != nil { - result.rlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForResource", resp, "Failure sending request") - return - } - - result.rlr, err = client.ListForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForResource", resp, "Failure responding to request") - return - } - if result.rlr.hasNextLink() && result.rlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListForResourcePreparer prepares the ListForResource request. -func (client RemediationsClient) ListForResourcePreparer(ctx context.Context, resourceID string, top *int32, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceId": resourceID, - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/{resourceId}/providers/Microsoft.PolicyInsights/remediations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceSender sends the ListForResource request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) ListForResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListForResourceResponder handles the response to the ListForResource request. The method always -// closes the http.Response Body. -func (client RemediationsClient) ListForResourceResponder(resp *http.Response) (result RemediationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceNextResults retrieves the next set of results, if any. -func (client RemediationsClient) listForResourceNextResults(ctx context.Context, lastResults RemediationListResult) (result RemediationListResult, err error) { - req, err := lastResults.remediationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForResourceNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForResourceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForResourceNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForResourceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForResourceNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForResourceComplete enumerates all values, automatically crossing page boundaries as required. -func (client RemediationsClient) ListForResourceComplete(ctx context.Context, resourceID string, top *int32, filter string) (result RemediationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListForResource") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListForResource(ctx, resourceID, top, filter) - return -} - -// ListForResourceGroup gets all remediations for the subscription. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// resourceGroupName - resource group name. -// top - maximum number of records to return. -// filter - oData filter expression. -func (client RemediationsClient) ListForResourceGroup(ctx context.Context, subscriptionID string, resourceGroupName string, top *int32, filter string) (result RemediationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListForResourceGroup") - defer func() { - sc := -1 - if result.rlr.Response.Response != nil { - sc = result.rlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.RemediationsClient", "ListForResourceGroup", err.Error()) - } - - result.fn = client.listForResourceGroupNextResults - req, err := client.ListForResourceGroupPreparer(ctx, subscriptionID, resourceGroupName, top, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListForResourceGroupSender(req) - if err != nil { - result.rlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForResourceGroup", resp, "Failure sending request") - return - } - - result.rlr, err = client.ListForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForResourceGroup", resp, "Failure responding to request") - return - } - if result.rlr.hasNextLink() && result.rlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListForResourceGroupPreparer prepares the ListForResourceGroup request. -func (client RemediationsClient) ListForResourceGroupPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, top *int32, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForResourceGroupSender sends the ListForResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) ListForResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListForResourceGroupResponder handles the response to the ListForResourceGroup request. The method always -// closes the http.Response Body. -func (client RemediationsClient) ListForResourceGroupResponder(resp *http.Response) (result RemediationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForResourceGroupNextResults retrieves the next set of results, if any. -func (client RemediationsClient) listForResourceGroupNextResults(ctx context.Context, lastResults RemediationListResult) (result RemediationListResult, err error) { - req, err := lastResults.remediationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client RemediationsClient) ListForResourceGroupComplete(ctx context.Context, subscriptionID string, resourceGroupName string, top *int32, filter string) (result RemediationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListForResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListForResourceGroup(ctx, subscriptionID, resourceGroupName, top, filter) - return -} - -// ListForSubscription gets all remediations for the subscription. -// Parameters: -// subscriptionID - microsoft Azure subscription ID. -// top - maximum number of records to return. -// filter - oData filter expression. -func (client RemediationsClient) ListForSubscription(ctx context.Context, subscriptionID string, top *int32, filter string) (result RemediationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListForSubscription") - defer func() { - sc := -1 - if result.rlr.Response.Response != nil { - sc = result.rlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { - return result, validation.NewError("policyinsights.RemediationsClient", "ListForSubscription", err.Error()) - } - - result.fn = client.listForSubscriptionNextResults - req, err := client.ListForSubscriptionPreparer(ctx, subscriptionID, top, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForSubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListForSubscriptionSender(req) - if err != nil { - result.rlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForSubscription", resp, "Failure sending request") - return - } - - result.rlr, err = client.ListForSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "ListForSubscription", resp, "Failure responding to request") - return - } - if result.rlr.hasNextLink() && result.rlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListForSubscriptionPreparer prepares the ListForSubscription request. -func (client RemediationsClient) ListForSubscriptionPreparer(ctx context.Context, subscriptionID string, top *int32, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", subscriptionID), - } - - const APIVersion = "2019-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListForSubscriptionSender sends the ListForSubscription request. The method will close the -// http.Response Body if it receives an error. -func (client RemediationsClient) ListForSubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListForSubscriptionResponder handles the response to the ListForSubscription request. The method always -// closes the http.Response Body. -func (client RemediationsClient) ListForSubscriptionResponder(resp *http.Response) (result RemediationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listForSubscriptionNextResults retrieves the next set of results, if any. -func (client RemediationsClient) listForSubscriptionNextResults(ctx context.Context, lastResults RemediationListResult) (result RemediationListResult, err error) { - req, err := lastResults.remediationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForSubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListForSubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForSubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListForSubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "policyinsights.RemediationsClient", "listForSubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListForSubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client RemediationsClient) ListForSubscriptionComplete(ctx context.Context, subscriptionID string, top *int32, filter string) (result RemediationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RemediationsClient.ListForSubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListForSubscription(ctx, subscriptionID, top, filter) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/version.go deleted file mode 100644 index 021d4f902032..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/policyinsights/mgmt/2019-10-01-preview/policyinsights/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package policyinsights - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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() + " policyinsights/2019-10-01-preview" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/CHANGELOG.md deleted file mode 100644 index 52911e4cc5e4..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/_meta.json deleted file mode 100644 index 68e168c2ffb7..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "3c764635e7d442b3e74caf593029fcd440b3ef82", - "readme": "/_/azure-rest-api-specs/specification/portal/resource-manager/readme.md", - "tag": "package-2019-01-01-preview", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-2019-01-01-preview --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION /_/azure-rest-api-specs/specification/portal/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/client.go deleted file mode 100644 index b38469ac9400..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/client.go +++ /dev/null @@ -1,41 +0,0 @@ -// Package portal implements the Azure ARM Portal service API version 2019-01-01-preview. -// -// -package portal - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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 Portal - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Portal. -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 using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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/preview/portal/mgmt/2019-01-01-preview/portal/dashboards.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/dashboards.go deleted file mode 100644 index 57c3bbc01bb5..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/dashboards.go +++ /dev/null @@ -1,603 +0,0 @@ -package portal - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DashboardsClient is the client for the Dashboards methods of the Portal service. -type DashboardsClient struct { - BaseClient -} - -// NewDashboardsClient creates an instance of the DashboardsClient client. -func NewDashboardsClient(subscriptionID string) DashboardsClient { - return NewDashboardsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDashboardsClientWithBaseURI creates an instance of the DashboardsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewDashboardsClientWithBaseURI(baseURI string, subscriptionID string) DashboardsClient { - return DashboardsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a Dashboard. -// Parameters: -// resourceGroupName - the name of the resource group. -// dashboardName - the name of the dashboard. -// dashboard - the parameters required to create or update a dashboard. -func (client DashboardsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, dashboardName string, dashboard Dashboard) (result Dashboard, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: dashboardName, - Constraints: []validation.Constraint{{Target: "dashboardName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "dashboardName", Name: validation.MinLength, Rule: 3, Chain: nil}}}, - {TargetValue: dashboard, - Constraints: []validation.Constraint{{Target: "dashboard.Location", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("portal.DashboardsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, dashboardName, dashboard) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DashboardsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, dashboardName string, dashboard Dashboard) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "dashboardName": autorest.Encode("path", dashboardName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2019-01-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - dashboard.ID = nil - dashboard.Name = nil - dashboard.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}", pathParameters), - autorest.WithJSON(dashboard), - 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 DashboardsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DashboardsClient) CreateOrUpdateResponder(resp *http.Response) (result Dashboard, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the Dashboard. -// Parameters: -// resourceGroupName - the name of the resource group. -// dashboardName - the name of the dashboard. -func (client DashboardsClient) Delete(ctx context.Context, resourceGroupName string, dashboardName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: dashboardName, - Constraints: []validation.Constraint{{Target: "dashboardName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "dashboardName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { - return result, validation.NewError("portal.DashboardsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, dashboardName) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DashboardsClient) DeletePreparer(ctx context.Context, resourceGroupName string, dashboardName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "dashboardName": autorest.Encode("path", dashboardName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2019-01-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}", 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 DashboardsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DashboardsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the Dashboard. -// Parameters: -// resourceGroupName - the name of the resource group. -// dashboardName - the name of the dashboard. -func (client DashboardsClient) Get(ctx context.Context, resourceGroupName string, dashboardName string) (result Dashboard, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: dashboardName, - Constraints: []validation.Constraint{{Target: "dashboardName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "dashboardName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { - return result, validation.NewError("portal.DashboardsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, dashboardName) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DashboardsClient) GetPreparer(ctx context.Context, resourceGroupName string, dashboardName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "dashboardName": autorest.Encode("path", dashboardName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2019-01-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}", 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 DashboardsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DashboardsClient) GetResponder(resp *http.Response) (result Dashboard, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNotFound), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByResourceGroup gets all the Dashboards within a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client DashboardsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result DashboardListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.dlr.Response.Response != nil { - sc = result.dlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.dlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.dlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.dlr.hasNextLink() && result.dlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client DashboardsClient) 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 = "2019-01-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards", 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 DashboardsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client DashboardsClient) ListByResourceGroupResponder(resp *http.Response) (result DashboardListResult, err error) { - err = autorest.Respond( - resp, - 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 DashboardsClient) listByResourceGroupNextResults(ctx context.Context, lastResults DashboardListResult) (result DashboardListResult, err error) { - req, err := lastResults.dashboardListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "portal.DashboardsClient", "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, "portal.DashboardsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client DashboardsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result DashboardListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// ListBySubscription gets all the dashboards within a subscription. -func (client DashboardsClient) ListBySubscription(ctx context.Context) (result DashboardListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardsClient.ListBySubscription") - defer func() { - sc := -1 - if result.dlr.Response.Response != nil { - sc = result.dlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.dlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.dlr, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.dlr.hasNextLink() && result.dlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client DashboardsClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2019-01-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Portal/dashboards", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client DashboardsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client DashboardsClient) ListBySubscriptionResponder(resp *http.Response) (result DashboardListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client DashboardsClient) listBySubscriptionNextResults(ctx context.Context, lastResults DashboardListResult) (result DashboardListResult, err error) { - req, err := lastResults.dashboardListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "portal.DashboardsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "portal.DashboardsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client DashboardsClient) ListBySubscriptionComplete(ctx context.Context) (result DashboardListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardsClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx) - return -} - -// Update updates an existing Dashboard. -// Parameters: -// resourceGroupName - the name of the resource group. -// dashboardName - the name of the dashboard. -// dashboard - the updatable fields of a Dashboard. -func (client DashboardsClient) Update(ctx context.Context, resourceGroupName string, dashboardName string, dashboard PatchableDashboard) (result Dashboard, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardsClient.Update") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: dashboardName, - Constraints: []validation.Constraint{{Target: "dashboardName", Name: validation.MaxLength, Rule: 64, Chain: nil}, - {Target: "dashboardName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { - return result, validation.NewError("portal.DashboardsClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, resourceGroupName, dashboardName, dashboard) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "Update", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "Update", resp, "Failure sending request") - return - } - - result, err = client.UpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.DashboardsClient", "Update", resp, "Failure responding to request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client DashboardsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, dashboardName string, dashboard PatchableDashboard) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "dashboardName": autorest.Encode("path", dashboardName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2019-01-01-preview" - 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.Portal/dashboards/{dashboardName}", pathParameters), - autorest.WithJSON(dashboard), - 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 DashboardsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client DashboardsClient) UpdateResponder(resp *http.Response) (result Dashboard, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNotFound), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/models.go deleted file mode 100644 index 3aea1c0ca90f..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/models.go +++ /dev/null @@ -1,801 +0,0 @@ -package portal - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/to" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal" - -// AzureEntityResource the resource model definition for an Azure Resource Manager resource with an etag. -type AzureEntityResource struct { - // Etag - READ-ONLY; Resource Etag. - Etag *string `json:"etag,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureEntityResource. -func (aer AzureEntityResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Configuration tenant configuration. -type Configuration struct { - autorest.Response `json:"-"` - // ConfigurationProperties - Tenant configuration properties. - *ConfigurationProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Configuration. -func (c Configuration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if c.ConfigurationProperties != nil { - objectMap["properties"] = c.ConfigurationProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Configuration struct. -func (c *Configuration) 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 configurationProperties ConfigurationProperties - err = json.Unmarshal(*v, &configurationProperties) - if err != nil { - return err - } - c.ConfigurationProperties = &configurationProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - c.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - c.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - c.Type = &typeVar - } - } - } - - return nil -} - -// ConfigurationList list of tenant configurations. -type ConfigurationList struct { - autorest.Response `json:"-"` - // Value - The array of tenant configurations. - Value *[]Configuration `json:"value,omitempty"` - // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ConfigurationProperties tenant configuration properties. -type ConfigurationProperties struct { - // EnforcePrivateMarkdownStorage - When flag is set to true Markdown tile will require external storage configuration (URI). The inline content configuration will be prohibited. - EnforcePrivateMarkdownStorage *bool `json:"enforcePrivateMarkdownStorage,omitempty"` -} - -// Dashboard the shared dashboard resource definition. -type Dashboard struct { - autorest.Response `json:"-"` - // DashboardProperties - The shared dashboard properties. - *DashboardProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Dashboard. -func (d Dashboard) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if d.DashboardProperties != nil { - objectMap["properties"] = d.DashboardProperties - } - if d.Location != nil { - objectMap["location"] = d.Location - } - if d.Tags != nil { - objectMap["tags"] = d.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Dashboard struct. -func (d *Dashboard) 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 dashboardProperties DashboardProperties - err = json.Unmarshal(*v, &dashboardProperties) - if err != nil { - return err - } - d.DashboardProperties = &dashboardProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - d.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - d.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - d.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - d.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - d.Tags = tags - } - } - } - - return nil -} - -// DashboardLens a dashboard lens. -type DashboardLens struct { - // Order - The lens order. - Order *int32 `json:"order,omitempty"` - // Parts - The dashboard parts. - Parts map[string]*DashboardParts `json:"parts"` - // Metadata - The dashboard len's metadata. - Metadata map[string]interface{} `json:"metadata"` -} - -// MarshalJSON is the custom marshaler for DashboardLens. -func (dl DashboardLens) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dl.Order != nil { - objectMap["order"] = dl.Order - } - if dl.Parts != nil { - objectMap["parts"] = dl.Parts - } - if dl.Metadata != nil { - objectMap["metadata"] = dl.Metadata - } - return json.Marshal(objectMap) -} - -// DashboardListResult list of dashboards. -type DashboardListResult struct { - autorest.Response `json:"-"` - // Value - The array of custom resource provider manifests. - Value *[]Dashboard `json:"value,omitempty"` - // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// DashboardListResultIterator provides access to a complete listing of Dashboard values. -type DashboardListResultIterator struct { - i int - page DashboardListResultPage -} - -// NextWithContext 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 *DashboardListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *DashboardListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter DashboardListResultIterator) 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 DashboardListResultIterator) Response() DashboardListResult { - 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 DashboardListResultIterator) Value() Dashboard { - if !iter.page.NotDone() { - return Dashboard{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the DashboardListResultIterator type. -func NewDashboardListResultIterator(page DashboardListResultPage) DashboardListResultIterator { - return DashboardListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (dlr DashboardListResult) IsEmpty() bool { - return dlr.Value == nil || len(*dlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (dlr DashboardListResult) hasNextLink() bool { - return dlr.NextLink != nil && len(*dlr.NextLink) != 0 -} - -// dashboardListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (dlr DashboardListResult) dashboardListResultPreparer(ctx context.Context) (*http.Request, error) { - if !dlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(dlr.NextLink))) -} - -// DashboardListResultPage contains a page of Dashboard values. -type DashboardListResultPage struct { - fn func(context.Context, DashboardListResult) (DashboardListResult, error) - dlr DashboardListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DashboardListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DashboardListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.dlr) - if err != nil { - return err - } - page.dlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DashboardListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DashboardListResultPage) NotDone() bool { - return !page.dlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DashboardListResultPage) Response() DashboardListResult { - return page.dlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DashboardListResultPage) Values() []Dashboard { - if page.dlr.IsEmpty() { - return nil - } - return *page.dlr.Value -} - -// Creates a new instance of the DashboardListResultPage type. -func NewDashboardListResultPage(cur DashboardListResult, getNextPage func(context.Context, DashboardListResult) (DashboardListResult, error)) DashboardListResultPage { - return DashboardListResultPage{ - fn: getNextPage, - dlr: cur, - } -} - -// DashboardParts a dashboard part. -type DashboardParts struct { - // Position - The dashboard's part position. - Position *DashboardPartsPosition `json:"position,omitempty"` - // Metadata - The dashboard part's metadata. - Metadata map[string]interface{} `json:"metadata"` -} - -// MarshalJSON is the custom marshaler for DashboardParts. -func (dp DashboardParts) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dp.Position != nil { - objectMap["position"] = dp.Position - } - if dp.Metadata != nil { - objectMap["metadata"] = dp.Metadata - } - return json.Marshal(objectMap) -} - -// DashboardPartsPosition the dashboard's part position. -type DashboardPartsPosition struct { - // X - The dashboard's part x coordinate. - X *int32 `json:"x,omitempty"` - // Y - The dashboard's part y coordinate. - Y *int32 `json:"y,omitempty"` - // RowSpan - The dashboard's part row span. - RowSpan *int32 `json:"rowSpan,omitempty"` - // ColSpan - The dashboard's part column span. - ColSpan *int32 `json:"colSpan,omitempty"` - // Metadata - The dashboard part's metadata. - Metadata map[string]interface{} `json:"metadata"` -} - -// MarshalJSON is the custom marshaler for DashboardPartsPosition. -func (dp DashboardPartsPosition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dp.X != nil { - objectMap["x"] = dp.X - } - if dp.Y != nil { - objectMap["y"] = dp.Y - } - if dp.RowSpan != nil { - objectMap["rowSpan"] = dp.RowSpan - } - if dp.ColSpan != nil { - objectMap["colSpan"] = dp.ColSpan - } - if dp.Metadata != nil { - objectMap["metadata"] = dp.Metadata - } - return json.Marshal(objectMap) -} - -// DashboardProperties the shared dashboard properties. -type DashboardProperties struct { - // Lenses - The dashboard lenses. - Lenses map[string]*DashboardLens `json:"lenses"` - // Metadata - The dashboard metadata. - Metadata map[string]interface{} `json:"metadata"` -} - -// MarshalJSON is the custom marshaler for DashboardProperties. -func (dp DashboardProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dp.Lenses != nil { - objectMap["lenses"] = dp.Lenses - } - if dp.Metadata != nil { - objectMap["metadata"] = dp.Metadata - } - return json.Marshal(objectMap) -} - -// ErrorDefinition error definition. -type ErrorDefinition struct { - // Code - READ-ONLY; Service specific error code which serves as the substatus for the HTTP error code. - Code *int32 `json:"code,omitempty"` - // Message - READ-ONLY; Description of the error. - Message *string `json:"message,omitempty"` - // Details - READ-ONLY; Internal error details. - Details *[]ErrorDefinition `json:"details,omitempty"` -} - -// MarshalJSON is the custom marshaler for ErrorDefinition. -func (ed ErrorDefinition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ErrorResponse error response. -type ErrorResponse struct { - // Error - The error details. - Error *ErrorDefinition `json:"error,omitempty"` -} - -// PatchableDashboard the shared dashboard resource definition. -type PatchableDashboard struct { - // DashboardProperties - The shared dashboard properties. - *DashboardProperties `json:"properties,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for PatchableDashboard. -func (pd PatchableDashboard) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pd.DashboardProperties != nil { - objectMap["properties"] = pd.DashboardProperties - } - if pd.Tags != nil { - objectMap["tags"] = pd.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PatchableDashboard struct. -func (pd *PatchableDashboard) 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 dashboardProperties DashboardProperties - err = json.Unmarshal(*v, &dashboardProperties) - if err != nil { - return err - } - pd.DashboardProperties = &dashboardProperties - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - pd.Tags = tags - } - } - } - - return nil -} - -// ProxyResource the resource model definition for an Azure Resource Manager proxy resource. It will have -// everything other than required location and tags -type ProxyResource struct { - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for ProxyResource. -func (pr ProxyResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Resource common fields that are returned in the response for all Azure Resource Manager resources -type Resource struct { - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ResourceProviderOperation supported operations of this resource provider. -type ResourceProviderOperation struct { - // Name - Operation name, in format of {provider}/{resource}/{operation} - Name *string `json:"name,omitempty"` - // IsDataAction - Indicates whether the operation applies to data-plane. - IsDataAction *string `json:"isDataAction,omitempty"` - // Display - Display metadata associated with the operation. - Display *ResourceProviderOperationDisplay `json:"display,omitempty"` -} - -// ResourceProviderOperationDisplay display metadata associated with the operation. -type ResourceProviderOperationDisplay struct { - // Provider - Resource provider: Microsoft Custom Providers. - Provider *string `json:"provider,omitempty"` - // Resource - Resource on which the operation is performed. - Resource *string `json:"resource,omitempty"` - // Operation - Type of operation: get, read, delete, etc. - Operation *string `json:"operation,omitempty"` - // Description - Description of this operation. - Description *string `json:"description,omitempty"` -} - -// ResourceProviderOperationList results of the request to list operations. -type ResourceProviderOperationList struct { - autorest.Response `json:"-"` - // Value - List of operations supported by this resource provider. - Value *[]ResourceProviderOperation `json:"value,omitempty"` - // NextLink - The URL to use for getting the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ResourceProviderOperationListIterator provides access to a complete listing of ResourceProviderOperation -// values. -type ResourceProviderOperationListIterator struct { - i int - page ResourceProviderOperationListPage -} - -// NextWithContext 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 *ResourceProviderOperationListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceProviderOperationListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ResourceProviderOperationListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ResourceProviderOperationListIterator) 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 ResourceProviderOperationListIterator) Response() ResourceProviderOperationList { - 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 ResourceProviderOperationListIterator) Value() ResourceProviderOperation { - if !iter.page.NotDone() { - return ResourceProviderOperation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ResourceProviderOperationListIterator type. -func NewResourceProviderOperationListIterator(page ResourceProviderOperationListPage) ResourceProviderOperationListIterator { - return ResourceProviderOperationListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rpol ResourceProviderOperationList) IsEmpty() bool { - return rpol.Value == nil || len(*rpol.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rpol ResourceProviderOperationList) hasNextLink() bool { - return rpol.NextLink != nil && len(*rpol.NextLink) != 0 -} - -// resourceProviderOperationListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rpol ResourceProviderOperationList) resourceProviderOperationListPreparer(ctx context.Context) (*http.Request, error) { - if !rpol.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rpol.NextLink))) -} - -// ResourceProviderOperationListPage contains a page of ResourceProviderOperation values. -type ResourceProviderOperationListPage struct { - fn func(context.Context, ResourceProviderOperationList) (ResourceProviderOperationList, error) - rpol ResourceProviderOperationList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ResourceProviderOperationListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceProviderOperationListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rpol) - if err != nil { - return err - } - page.rpol = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ResourceProviderOperationListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ResourceProviderOperationListPage) NotDone() bool { - return !page.rpol.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ResourceProviderOperationListPage) Response() ResourceProviderOperationList { - return page.rpol -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ResourceProviderOperationListPage) Values() []ResourceProviderOperation { - if page.rpol.IsEmpty() { - return nil - } - return *page.rpol.Value -} - -// Creates a new instance of the ResourceProviderOperationListPage type. -func NewResourceProviderOperationListPage(cur ResourceProviderOperationList, getNextPage func(context.Context, ResourceProviderOperationList) (ResourceProviderOperationList, error)) ResourceProviderOperationListPage { - return ResourceProviderOperationListPage{ - fn: getNextPage, - rpol: cur, - } -} - -// TrackedResource the resource model definition for an Azure Resource Manager tracked top level resource -type TrackedResource struct { - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` - // Location - The geo-location where the resource lives - Location *string `json:"location,omitempty"` - // ID - READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; The name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" - 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.Tags != nil { - objectMap["tags"] = tr.Tags - } - if tr.Location != nil { - objectMap["location"] = tr.Location - } - return json.Marshal(objectMap) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/operations.go deleted file mode 100644 index 4dea94ef0a37..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/operations.go +++ /dev/null @@ -1,140 +0,0 @@ -package portal - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// OperationsClient is the client for the Operations methods of the Portal service. -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 using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List the Microsoft Portal operations API. -func (client OperationsClient) List(ctx context.Context) (result ResourceProviderOperationListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.rpol.Response.Response != nil { - sc = result.rpol.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.OperationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rpol.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "portal.OperationsClient", "List", resp, "Failure sending request") - return - } - - result.rpol, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.OperationsClient", "List", resp, "Failure responding to request") - return - } - if result.rpol.hasNextLink() && result.rpol.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2019-01-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.Portal/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 client.Send(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 ResourceProviderOperationList, err error) { - err = autorest.Respond( - resp, - 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(ctx context.Context, lastResults ResourceProviderOperationList) (result ResourceProviderOperationList, err error) { - req, err := lastResults.resourceProviderOperationListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "portal.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, "portal.OperationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.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 ResourceProviderOperationListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/tenantconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/tenantconfigurations.go deleted file mode 100644 index 5a0aad7a5cee..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/tenantconfigurations.go +++ /dev/null @@ -1,316 +0,0 @@ -package portal - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// TenantConfigurationsClient is the client for the TenantConfigurations methods of the Portal service. -type TenantConfigurationsClient struct { - BaseClient -} - -// NewTenantConfigurationsClient creates an instance of the TenantConfigurationsClient client. -func NewTenantConfigurationsClient(subscriptionID string) TenantConfigurationsClient { - return NewTenantConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewTenantConfigurationsClientWithBaseURI creates an instance of the TenantConfigurationsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewTenantConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) TenantConfigurationsClient { - return TenantConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create create the tenant configuration. If configuration already exists - update it. User has to be a Tenant Admin -// for this operation. -// Parameters: -// tenantConfiguration - the parameters required to create or update tenant configuration. -func (client TenantConfigurationsClient) Create(ctx context.Context, tenantConfiguration Configuration) (result Configuration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TenantConfigurationsClient.Create") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreatePreparer(ctx, tenantConfiguration) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "Create", nil, "Failure preparing request") - return - } - - resp, err := client.CreateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "Create", resp, "Failure sending request") - return - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "Create", resp, "Failure responding to request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client TenantConfigurationsClient) CreatePreparer(ctx context.Context, tenantConfiguration Configuration) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", "default"), - } - - const APIVersion = "2019-01-01-preview" - 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("/providers/Microsoft.Portal/tenantConfigurations/{configurationName}", pathParameters), - autorest.WithJSON(tenantConfiguration), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client TenantConfigurationsClient) CreateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client TenantConfigurationsClient) CreateResponder(resp *http.Response) (result Configuration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the tenant configuration. User has to be a Tenant Admin for this operation. -func (client TenantConfigurationsClient) Delete(ctx context.Context) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TenantConfigurationsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client TenantConfigurationsClient) DeletePreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", "default"), - } - - const APIVersion = "2019-01-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/Microsoft.Portal/tenantConfigurations/{configurationName}", 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 TenantConfigurationsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client TenantConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the tenant configuration. -func (client TenantConfigurationsClient) Get(ctx context.Context) (result Configuration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TenantConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client TenantConfigurationsClient) GetPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", "default"), - } - - const APIVersion = "2019-01-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/Microsoft.Portal/tenantConfigurations/{configurationName}", 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 TenantConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client TenantConfigurationsClient) GetResponder(resp *http.Response) (result Configuration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNotFound), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets list of the tenant configurations. -func (client TenantConfigurationsClient) List(ctx context.Context) (result ConfigurationList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TenantConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "portal.TenantConfigurationsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client TenantConfigurationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2019-01-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.Portal/tenantConfigurations"), - 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 TenantConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(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 TenantConfigurationsClient) ListResponder(resp *http.Response) (result ConfigurationList, err error) { - err = autorest.Respond( - resp, - 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/preview/portal/mgmt/2019-01-01-preview/portal/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/version.go deleted file mode 100644 index 28798e95de42..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/portal/mgmt/2019-01-01-preview/portal/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package portal - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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() + " portal/2019-01-01-preview" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/CHANGELOG.md deleted file mode 100644 index 52911e4cc5e4..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/_meta.json deleted file mode 100644 index 48dcf3c45aac..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "af463c3f9502d353b8a009685177f13335adb8cd", - "readme": "/_/azure-rest-api-specs/specification/servicebus/resource-manager/readme.md", - "tag": "package-2021-06-preview", - "use": "@microsoft.azure/autorest.go@2.1.187", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.187 --tag=package-2021-06-preview --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix /_/azure-rest-api-specs/specification/servicebus/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION --enum-prefix" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/client.go deleted file mode 100644 index 149da60ad477..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/client.go +++ /dev/null @@ -1,41 +0,0 @@ -// Package servicebus implements the Azure ARM Servicebus service API version 2021-06-01-preview. -// -// -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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 using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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/preview/servicebus/mgmt/2021-06-01-preview/servicebus/disasterrecoveryconfigs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/disasterrecoveryconfigs.go deleted file mode 100644 index e9857e1e57f8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/disasterrecoveryconfigs.go +++ /dev/null @@ -1,1040 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DisasterRecoveryConfigsClient is the client for the DisasterRecoveryConfigs methods of the Servicebus service. -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 using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.BreakPairing") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.CheckNameAvailabilityMethod") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = resp - return -} - -// FailOver invokes 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 -// parameters - parameters required to create an Alias(Disaster Recovery configuration) -func (client DisasterRecoveryConfigsClient) FailOver(ctx context.Context, resourceGroupName string, namespaceName string, alias string, parameters *FailoverProperties) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.FailOver") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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, parameters) - 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 - } - - return -} - -// FailOverPreparer prepares the FailOver request. -func (client DisasterRecoveryConfigsClient) FailOverPreparer(ctx context.Context, resourceGroupName string, namespaceName string, alias string, parameters *FailoverProperties) (*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 = "2021-06-01-preview" - 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/{alias}/failover", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if parameters != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(parameters)) - } - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 authorization rule name. -func (client DisasterRecoveryConfigsClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, alias string, authorizationRuleName string) (result SBAuthorizationRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.GetAuthorizationRule") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.List") - defer func() { - sc := -1 - if result.adrlr.Response.Response != nil { - sc = result.adrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - if result.adrlr.hasNextLink() && result.adrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults ArmDisasterRecoveryListResult) (result ArmDisasterRecoveryListResult, err error) { - req, err := lastResults.armDisasterRecoveryListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.ListAuthorizationRules") - defer func() { - sc := -1 - if result.sarlr.Response.Response != nil { - sc = result.sarlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - if result.sarlr.hasNextLink() && result.sarlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) { - req, err := lastResults.sBAuthorizationRuleListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.ListAuthorizationRules") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 authorization rule name. -func (client DisasterRecoveryConfigsClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, alias string, authorizationRuleName string) (result AccessKeys, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DisasterRecoveryConfigsClient.ListKeys") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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/preview/servicebus/mgmt/2021-06-01-preview/servicebus/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/enums.go deleted file mode 100644 index 52ad60d6ba50..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/enums.go +++ /dev/null @@ -1,310 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// AccessRights enumerates the values for access rights. -type AccessRights string - -const ( - // AccessRightsListen ... - AccessRightsListen AccessRights = "Listen" - // AccessRightsManage ... - AccessRightsManage AccessRights = "Manage" - // AccessRightsSend ... - AccessRightsSend AccessRights = "Send" -) - -// PossibleAccessRightsValues returns an array of possible values for the AccessRights const type. -func PossibleAccessRightsValues() []AccessRights { - return []AccessRights{AccessRightsListen, AccessRightsManage, AccessRightsSend} -} - -// CreatedByType enumerates the values for created by type. -type CreatedByType string - -const ( - // CreatedByTypeApplication ... - CreatedByTypeApplication CreatedByType = "Application" - // CreatedByTypeKey ... - CreatedByTypeKey CreatedByType = "Key" - // CreatedByTypeManagedIdentity ... - CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" - // CreatedByTypeUser ... - CreatedByTypeUser CreatedByType = "User" -) - -// PossibleCreatedByTypeValues returns an array of possible values for the CreatedByType const type. -func PossibleCreatedByTypeValues() []CreatedByType { - return []CreatedByType{CreatedByTypeApplication, CreatedByTypeKey, CreatedByTypeManagedIdentity, CreatedByTypeUser} -} - -// DefaultAction enumerates the values for default action. -type DefaultAction string - -const ( - // DefaultActionAllow ... - DefaultActionAllow DefaultAction = "Allow" - // DefaultActionDeny ... - DefaultActionDeny DefaultAction = "Deny" -) - -// PossibleDefaultActionValues returns an array of possible values for the DefaultAction const type. -func PossibleDefaultActionValues() []DefaultAction { - return []DefaultAction{DefaultActionAllow, DefaultActionDeny} -} - -// EndPointProvisioningState enumerates the values for end point provisioning state. -type EndPointProvisioningState string - -const ( - // EndPointProvisioningStateCanceled ... - EndPointProvisioningStateCanceled EndPointProvisioningState = "Canceled" - // EndPointProvisioningStateCreating ... - EndPointProvisioningStateCreating EndPointProvisioningState = "Creating" - // EndPointProvisioningStateDeleting ... - EndPointProvisioningStateDeleting EndPointProvisioningState = "Deleting" - // EndPointProvisioningStateFailed ... - EndPointProvisioningStateFailed EndPointProvisioningState = "Failed" - // EndPointProvisioningStateSucceeded ... - EndPointProvisioningStateSucceeded EndPointProvisioningState = "Succeeded" - // EndPointProvisioningStateUpdating ... - EndPointProvisioningStateUpdating EndPointProvisioningState = "Updating" -) - -// PossibleEndPointProvisioningStateValues returns an array of possible values for the EndPointProvisioningState const type. -func PossibleEndPointProvisioningStateValues() []EndPointProvisioningState { - return []EndPointProvisioningState{EndPointProvisioningStateCanceled, EndPointProvisioningStateCreating, EndPointProvisioningStateDeleting, EndPointProvisioningStateFailed, EndPointProvisioningStateSucceeded, EndPointProvisioningStateUpdating} -} - -// EntityStatus enumerates the values for entity status. -type EntityStatus string - -const ( - // EntityStatusActive ... - EntityStatusActive EntityStatus = "Active" - // EntityStatusCreating ... - EntityStatusCreating EntityStatus = "Creating" - // EntityStatusDeleting ... - EntityStatusDeleting EntityStatus = "Deleting" - // EntityStatusDisabled ... - EntityStatusDisabled EntityStatus = "Disabled" - // EntityStatusReceiveDisabled ... - EntityStatusReceiveDisabled EntityStatus = "ReceiveDisabled" - // EntityStatusRenaming ... - EntityStatusRenaming EntityStatus = "Renaming" - // EntityStatusRestoring ... - EntityStatusRestoring EntityStatus = "Restoring" - // EntityStatusSendDisabled ... - EntityStatusSendDisabled EntityStatus = "SendDisabled" - // EntityStatusUnknown ... - EntityStatusUnknown EntityStatus = "Unknown" -) - -// PossibleEntityStatusValues returns an array of possible values for the EntityStatus const type. -func PossibleEntityStatusValues() []EntityStatus { - return []EntityStatus{EntityStatusActive, EntityStatusCreating, EntityStatusDeleting, EntityStatusDisabled, EntityStatusReceiveDisabled, EntityStatusRenaming, EntityStatusRestoring, EntityStatusSendDisabled, EntityStatusUnknown} -} - -// 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} -} - -// KeySource enumerates the values for key source. -type KeySource string - -const ( - // KeySourceMicrosoftKeyVault ... - KeySourceMicrosoftKeyVault KeySource = "Microsoft.KeyVault" -) - -// PossibleKeySourceValues returns an array of possible values for the KeySource const type. -func PossibleKeySourceValues() []KeySource { - return []KeySource{KeySourceMicrosoftKeyVault} -} - -// KeyType enumerates the values for key type. -type KeyType string - -const ( - // KeyTypePrimaryKey ... - KeyTypePrimaryKey KeyType = "PrimaryKey" - // KeyTypeSecondaryKey ... - KeyTypeSecondaryKey KeyType = "SecondaryKey" -) - -// PossibleKeyTypeValues returns an array of possible values for the KeyType const type. -func PossibleKeyTypeValues() []KeyType { - return []KeyType{KeyTypePrimaryKey, KeyTypeSecondaryKey} -} - -// ManagedServiceIdentityType enumerates the values for managed service identity type. -type ManagedServiceIdentityType string - -const ( - // ManagedServiceIdentityTypeNone ... - ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" - // ManagedServiceIdentityTypeSystemAssigned ... - ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" - // ManagedServiceIdentityTypeSystemAssignedUserAssigned ... - ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned, UserAssigned" - // ManagedServiceIdentityTypeUserAssigned ... - ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" -) - -// PossibleManagedServiceIdentityTypeValues returns an array of possible values for the ManagedServiceIdentityType const type. -func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { - return []ManagedServiceIdentityType{ManagedServiceIdentityTypeNone, ManagedServiceIdentityTypeSystemAssigned, ManagedServiceIdentityTypeSystemAssignedUserAssigned, ManagedServiceIdentityTypeUserAssigned} -} - -// NetworkRuleIPAction enumerates the values for network rule ip action. -type NetworkRuleIPAction string - -const ( - // NetworkRuleIPActionAllow ... - NetworkRuleIPActionAllow NetworkRuleIPAction = "Allow" -) - -// PossibleNetworkRuleIPActionValues returns an array of possible values for the NetworkRuleIPAction const type. -func PossibleNetworkRuleIPActionValues() []NetworkRuleIPAction { - return []NetworkRuleIPAction{NetworkRuleIPActionAllow} -} - -// PrivateLinkConnectionStatus enumerates the values for private link connection status. -type PrivateLinkConnectionStatus string - -const ( - // PrivateLinkConnectionStatusApproved ... - PrivateLinkConnectionStatusApproved PrivateLinkConnectionStatus = "Approved" - // PrivateLinkConnectionStatusDisconnected ... - PrivateLinkConnectionStatusDisconnected PrivateLinkConnectionStatus = "Disconnected" - // PrivateLinkConnectionStatusPending ... - PrivateLinkConnectionStatusPending PrivateLinkConnectionStatus = "Pending" - // PrivateLinkConnectionStatusRejected ... - PrivateLinkConnectionStatusRejected PrivateLinkConnectionStatus = "Rejected" -) - -// PossiblePrivateLinkConnectionStatusValues returns an array of possible values for the PrivateLinkConnectionStatus const type. -func PossiblePrivateLinkConnectionStatusValues() []PrivateLinkConnectionStatus { - return []PrivateLinkConnectionStatus{PrivateLinkConnectionStatusApproved, PrivateLinkConnectionStatusDisconnected, PrivateLinkConnectionStatusPending, PrivateLinkConnectionStatusRejected} -} - -// ProvisioningStateDR enumerates the values for provisioning state dr. -type ProvisioningStateDR string - -const ( - // ProvisioningStateDRAccepted ... - ProvisioningStateDRAccepted ProvisioningStateDR = "Accepted" - // ProvisioningStateDRFailed ... - ProvisioningStateDRFailed ProvisioningStateDR = "Failed" - // ProvisioningStateDRSucceeded ... - ProvisioningStateDRSucceeded ProvisioningStateDR = "Succeeded" -) - -// PossibleProvisioningStateDRValues returns an array of possible values for the ProvisioningStateDR const type. -func PossibleProvisioningStateDRValues() []ProvisioningStateDR { - return []ProvisioningStateDR{ProvisioningStateDRAccepted, ProvisioningStateDRFailed, ProvisioningStateDRSucceeded} -} - -// PublicNetworkAccessFlag enumerates the values for public network access flag. -type PublicNetworkAccessFlag string - -const ( - // PublicNetworkAccessFlagDisabled ... - PublicNetworkAccessFlagDisabled PublicNetworkAccessFlag = "Disabled" - // PublicNetworkAccessFlagEnabled ... - PublicNetworkAccessFlagEnabled PublicNetworkAccessFlag = "Enabled" -) - -// PossiblePublicNetworkAccessFlagValues returns an array of possible values for the PublicNetworkAccessFlag const type. -func PossiblePublicNetworkAccessFlagValues() []PublicNetworkAccessFlag { - return []PublicNetworkAccessFlag{PublicNetworkAccessFlagDisabled, PublicNetworkAccessFlagEnabled} -} - -// RoleDisasterRecovery enumerates the values for role disaster recovery. -type RoleDisasterRecovery string - -const ( - // RoleDisasterRecoveryPrimary ... - RoleDisasterRecoveryPrimary RoleDisasterRecovery = "Primary" - // RoleDisasterRecoveryPrimaryNotReplicating ... - RoleDisasterRecoveryPrimaryNotReplicating RoleDisasterRecovery = "PrimaryNotReplicating" - // RoleDisasterRecoverySecondary ... - RoleDisasterRecoverySecondary RoleDisasterRecovery = "Secondary" -) - -// PossibleRoleDisasterRecoveryValues returns an array of possible values for the RoleDisasterRecovery const type. -func PossibleRoleDisasterRecoveryValues() []RoleDisasterRecovery { - return []RoleDisasterRecovery{RoleDisasterRecoveryPrimary, RoleDisasterRecoveryPrimaryNotReplicating, RoleDisasterRecoverySecondary} -} - -// SkuName enumerates the values for sku name. -type SkuName string - -const ( - // SkuNameBasic ... - SkuNameBasic SkuName = "Basic" - // SkuNamePremium ... - SkuNamePremium SkuName = "Premium" - // SkuNameStandard ... - SkuNameStandard SkuName = "Standard" -) - -// PossibleSkuNameValues returns an array of possible values for the SkuName const type. -func PossibleSkuNameValues() []SkuName { - return []SkuName{SkuNameBasic, SkuNamePremium, SkuNameStandard} -} - -// 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 ( - // UnavailableReasonInvalidName ... - UnavailableReasonInvalidName UnavailableReason = "InvalidName" - // UnavailableReasonNameInLockdown ... - UnavailableReasonNameInLockdown UnavailableReason = "NameInLockdown" - // UnavailableReasonNameInUse ... - UnavailableReasonNameInUse UnavailableReason = "NameInUse" - // UnavailableReasonNone ... - UnavailableReasonNone UnavailableReason = "None" - // UnavailableReasonSubscriptionIsDisabled ... - UnavailableReasonSubscriptionIsDisabled UnavailableReason = "SubscriptionIsDisabled" - // UnavailableReasonTooManyNamespaceInCurrentSubscription ... - UnavailableReasonTooManyNamespaceInCurrentSubscription UnavailableReason = "TooManyNamespaceInCurrentSubscription" -) - -// PossibleUnavailableReasonValues returns an array of possible values for the UnavailableReason const type. -func PossibleUnavailableReasonValues() []UnavailableReason { - return []UnavailableReason{UnavailableReasonInvalidName, UnavailableReasonNameInLockdown, UnavailableReasonNameInUse, UnavailableReasonNone, UnavailableReasonSubscriptionIsDisabled, UnavailableReasonTooManyNamespaceInCurrentSubscription} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/migrationconfigs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/migrationconfigs.go deleted file mode 100644 index 4157d2940a9c..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/migrationconfigs.go +++ /dev/null @@ -1,608 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// MigrationConfigsClient is the client for the MigrationConfigs methods of the Servicebus service. -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 using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -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 entities 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MigrationConfigsClient.CompleteMigration") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = resp - return -} - -// CreateAndStartMigration creates Migration configuration and starts migration of entities 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MigrationConfigsClient.CreateAndStartMigration") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - 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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MigrationConfigsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MigrationConfigsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MigrationConfigsClient.List") - defer func() { - sc := -1 - if result.mclr.Response.Response != nil { - sc = result.mclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - if result.mclr.hasNextLink() && result.mclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults MigrationConfigListResult) (result MigrationConfigListResult, err error) { - req, err := lastResults.migrationConfigListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MigrationConfigsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MigrationConfigsClient.Revert") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/models.go deleted file mode 100644 index 13755feaedd0..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/models.go +++ /dev/null @@ -1,3989 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus" - -// AccessKeys namespace/ServiceBus Connection String -type AccessKeys struct { - autorest.Response `json:"-"` - // PrimaryConnectionString - READ-ONLY; Primary connection string of the created namespace authorization rule. - PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` - // SecondaryConnectionString - READ-ONLY; Secondary connection string of the created namespace authorization rule. - SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` - // AliasPrimaryConnectionString - READ-ONLY; Primary connection string of the alias if GEO DR is enabled - AliasPrimaryConnectionString *string `json:"aliasPrimaryConnectionString,omitempty"` - // AliasSecondaryConnectionString - READ-ONLY; Secondary connection string of the alias if GEO DR is enabled - AliasSecondaryConnectionString *string `json:"aliasSecondaryConnectionString,omitempty"` - // PrimaryKey - READ-ONLY; A base64-encoded 256-bit primary key for signing and validating the SAS token. - PrimaryKey *string `json:"primaryKey,omitempty"` - // SecondaryKey - READ-ONLY; A base64-encoded 256-bit primary key for signing and validating the SAS token. - SecondaryKey *string `json:"secondaryKey,omitempty"` - // KeyName - READ-ONLY; A string that describes the authorization rule. - KeyName *string `json:"keyName,omitempty"` -} - -// MarshalJSON is the custom marshaler for AccessKeys. -func (ak AccessKeys) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// 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"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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 - } - 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 "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - adr.SystemData = &systemData - } - 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 - READ-ONLY; Link to the next set of results. Not empty if Value contains incomplete list of Alias(Disaster Recovery configuration) - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ArmDisasterRecoveryListResult. -func (adrlr ArmDisasterRecoveryListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if adrlr.Value != nil { - objectMap["value"] = adrlr.Value - } - return json.Marshal(objectMap) -} - -// ArmDisasterRecoveryListResultIterator provides access to a complete listing of ArmDisasterRecovery -// values. -type ArmDisasterRecoveryListResultIterator struct { - i int - page ArmDisasterRecoveryListResultPage -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ArmDisasterRecoveryListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ArmDisasterRecoveryListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the ArmDisasterRecoveryListResultIterator type. -func NewArmDisasterRecoveryListResultIterator(page ArmDisasterRecoveryListResultPage) ArmDisasterRecoveryListResultIterator { - return ArmDisasterRecoveryListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (adrlr ArmDisasterRecoveryListResult) IsEmpty() bool { - return adrlr.Value == nil || len(*adrlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (adrlr ArmDisasterRecoveryListResult) hasNextLink() bool { - return adrlr.NextLink != nil && len(*adrlr.NextLink) != 0 -} - -// armDisasterRecoveryListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (adrlr ArmDisasterRecoveryListResult) armDisasterRecoveryListResultPreparer(ctx context.Context) (*http.Request, error) { - if !adrlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(adrlr.NextLink))) -} - -// ArmDisasterRecoveryListResultPage contains a page of ArmDisasterRecovery values. -type ArmDisasterRecoveryListResultPage struct { - fn func(context.Context, ArmDisasterRecoveryListResult) (ArmDisasterRecoveryListResult, error) - adrlr ArmDisasterRecoveryListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ArmDisasterRecoveryListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ArmDisasterRecoveryListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.adrlr) - if err != nil { - return err - } - page.adrlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ArmDisasterRecoveryListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the ArmDisasterRecoveryListResultPage type. -func NewArmDisasterRecoveryListResultPage(cur ArmDisasterRecoveryListResult, getNextPage func(context.Context, ArmDisasterRecoveryListResult) (ArmDisasterRecoveryListResult, error)) ArmDisasterRecoveryListResultPage { - return ArmDisasterRecoveryListResultPage{ - fn: getNextPage, - adrlr: cur, - } -} - -// ArmDisasterRecoveryProperties properties required to the Create Or Update Alias(Disaster Recovery -// configurations) -type ArmDisasterRecoveryProperties struct { - // ProvisioningState - READ-ONLY; Provisioning state of the Alias(Disaster Recovery configuration) - possible values 'Accepted' or 'Succeeded' or 'Failed'. Possible values include: 'ProvisioningStateDRAccepted', 'ProvisioningStateDRSucceeded', 'ProvisioningStateDRFailed' - ProvisioningState ProvisioningStateDR `json:"provisioningState,omitempty"` - // PendingReplicationOperationsCount - READ-ONLY; 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 pairing - PartnerNamespace *string `json:"partnerNamespace,omitempty"` - // AlternateName - Primary/Secondary eventhub namespace name, which is part of GEO DR pairing - AlternateName *string `json:"alternateName,omitempty"` - // Role - READ-ONLY; role of namespace in GEO DR - possible values 'Primary' or 'PrimaryNotReplicating' or 'Secondary'. Possible values include: 'RoleDisasterRecoveryPrimary', 'RoleDisasterRecoveryPrimaryNotReplicating', 'RoleDisasterRecoverySecondary' - Role RoleDisasterRecovery `json:"role,omitempty"` -} - -// MarshalJSON is the custom marshaler for ArmDisasterRecoveryProperties. -func (adr ArmDisasterRecoveryProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if adr.PartnerNamespace != nil { - objectMap["partnerNamespace"] = adr.PartnerNamespace - } - if adr.AlternateName != nil { - objectMap["alternateName"] = adr.AlternateName - } - return json.Marshal(objectMap) -} - -// CheckNameAvailability description of a Check Name availability request properties. -type CheckNameAvailability struct { - // Name - The Name to check the namespace 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 - READ-ONLY; 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: 'UnavailableReasonNone', 'UnavailableReasonInvalidName', 'UnavailableReasonSubscriptionIsDisabled', 'UnavailableReasonNameInUse', 'UnavailableReasonNameInLockdown', 'UnavailableReasonTooManyNamespaceInCurrentSubscription' - Reason UnavailableReason `json:"reason,omitempty"` -} - -// MarshalJSON is the custom marshaler for CheckNameAvailabilityResult. -func (cnar CheckNameAvailabilityResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cnar.NameAvailable != nil { - objectMap["nameAvailable"] = cnar.NameAvailable - } - if cnar.Reason != "" { - objectMap["reason"] = cnar.Reason - } - return json.Marshal(objectMap) -} - -// ConnectionState connectionState information. -type ConnectionState struct { - // Status - Status of the connection. Possible values include: 'PrivateLinkConnectionStatusPending', 'PrivateLinkConnectionStatusApproved', 'PrivateLinkConnectionStatusRejected', 'PrivateLinkConnectionStatusDisconnected' - Status PrivateLinkConnectionStatus `json:"status,omitempty"` - // Description - Description of the connection state. - Description *string `json:"description,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) -} - -// Encryption properties to configure Encryption -type Encryption struct { - // KeyVaultProperties - Properties of KeyVault - KeyVaultProperties *[]KeyVaultProperties `json:"keyVaultProperties,omitempty"` - // KeySource - Enumerates the possible value of keySource for Encryption. Possible values include: 'KeySourceMicrosoftKeyVault' - KeySource KeySource `json:"keySource,omitempty"` - // RequireInfrastructureEncryption - Enable Infrastructure Encryption (Double Encryption) - RequireInfrastructureEncryption *bool `json:"requireInfrastructureEncryption,omitempty"` -} - -// ErrorAdditionalInfo the resource management error additional info. -type ErrorAdditionalInfo struct { - // Type - READ-ONLY; The additional info type. - Type *string `json:"type,omitempty"` - // Info - READ-ONLY; The additional info. - Info interface{} `json:"info,omitempty"` -} - -// MarshalJSON is the custom marshaler for ErrorAdditionalInfo. -func (eai ErrorAdditionalInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ErrorResponse the resource management error response. -type ErrorResponse struct { - // Error - The error object. - Error *ErrorResponseError `json:"error,omitempty"` -} - -// ErrorResponseError the error object. -type ErrorResponseError struct { - // Code - READ-ONLY; The error code. - Code *string `json:"code,omitempty"` - // Message - READ-ONLY; The error message. - Message *string `json:"message,omitempty"` - // Target - READ-ONLY; The error target. - Target *string `json:"target,omitempty"` - // Details - READ-ONLY; The error details. - Details *[]ErrorResponse `json:"details,omitempty"` - // AdditionalInfo - READ-ONLY; The error additional info. - AdditionalInfo *[]ErrorAdditionalInfo `json:"additionalInfo,omitempty"` -} - -// MarshalJSON is the custom marshaler for ErrorResponseError. -func (er ErrorResponseError) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// FailoverProperties safe failover is to indicate the service should wait for pending replication to -// finish before switching to the secondary. -type FailoverProperties struct { - // FailoverPropertiesProperties - Safe failover is to indicate the service should wait for pending replication to finish before switching to the secondary. - *FailoverPropertiesProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for FailoverProperties. -func (fp FailoverProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fp.FailoverPropertiesProperties != nil { - objectMap["properties"] = fp.FailoverPropertiesProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for FailoverProperties struct. -func (fp *FailoverProperties) 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 failoverPropertiesProperties FailoverPropertiesProperties - err = json.Unmarshal(*v, &failoverPropertiesProperties) - if err != nil { - return err - } - fp.FailoverPropertiesProperties = &failoverPropertiesProperties - } - } - } - - return nil -} - -// FailoverPropertiesProperties safe failover is to indicate the service should wait for pending -// replication to finish before switching to the secondary. -type FailoverPropertiesProperties struct { - // IsSafeFailover - Safe failover is to indicate the service should wait for pending replication to finish before switching to the secondary. - IsSafeFailover *bool `json:"IsSafeFailover,omitempty"` -} - -// Identity properties to configure User Assigned Identities for Bring your Own Keys -type Identity struct { - // PrincipalID - READ-ONLY; ObjectId from the KeyVault - PrincipalID *string `json:"principalId,omitempty"` - // TenantID - READ-ONLY; TenantId from the KeyVault - TenantID *string `json:"tenantId,omitempty"` - // Type - Type of managed service identity. Possible values include: 'ManagedServiceIdentityTypeSystemAssigned', 'ManagedServiceIdentityTypeUserAssigned', 'ManagedServiceIdentityTypeSystemAssignedUserAssigned', 'ManagedServiceIdentityTypeNone' - Type ManagedServiceIdentityType `json:"type,omitempty"` - // UserAssignedIdentities - Properties for User Assigned Identities - UserAssignedIdentities map[string]*UserAssignedIdentity `json:"userAssignedIdentities"` -} - -// MarshalJSON is the custom marshaler for Identity. -func (i Identity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if i.Type != "" { - objectMap["type"] = i.Type - } - if i.UserAssignedIdentities != nil { - objectMap["userAssignedIdentities"] = i.UserAssignedIdentities - } - return json.Marshal(objectMap) -} - -// KeyVaultProperties properties to configure keyVault Properties -type KeyVaultProperties struct { - // KeyName - Name of the Key from KeyVault - KeyName *string `json:"keyName,omitempty"` - // KeyVaultURI - Uri of KeyVault - KeyVaultURI *string `json:"keyVaultUri,omitempty"` - // KeyVersion - Version of KeyVault - KeyVersion *string `json:"keyVersion,omitempty"` - Identity *UserAssignedIdentityProperties `json:"identity,omitempty"` -} - -// MessageCountDetails message Count Details. -type MessageCountDetails struct { - // ActiveMessageCount - READ-ONLY; Number of active messages in the queue, topic, or subscription. - ActiveMessageCount *int64 `json:"activeMessageCount,omitempty"` - // DeadLetterMessageCount - READ-ONLY; Number of messages that are dead lettered. - DeadLetterMessageCount *int64 `json:"deadLetterMessageCount,omitempty"` - // ScheduledMessageCount - READ-ONLY; Number of scheduled messages. - ScheduledMessageCount *int64 `json:"scheduledMessageCount,omitempty"` - // TransferMessageCount - READ-ONLY; Number of messages transferred to another queue, topic, or subscription. - TransferMessageCount *int64 `json:"transferMessageCount,omitempty"` - // TransferDeadLetterMessageCount - READ-ONLY; Number of messages transferred into dead letters. - TransferDeadLetterMessageCount *int64 `json:"transferDeadLetterMessageCount,omitempty"` -} - -// MarshalJSON is the custom marshaler for MessageCountDetails. -func (mcd MessageCountDetails) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// 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 - READ-ONLY; Link to the next set of results. Not empty if Value contains incomplete list of migrationConfigurations - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for MigrationConfigListResult. -func (mclr MigrationConfigListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mclr.Value != nil { - objectMap["value"] = mclr.Value - } - return json.Marshal(objectMap) -} - -// MigrationConfigListResultIterator provides access to a complete listing of MigrationConfigProperties -// values. -type MigrationConfigListResultIterator struct { - i int - page MigrationConfigListResultPage -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MigrationConfigListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *MigrationConfigListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the MigrationConfigListResultIterator type. -func NewMigrationConfigListResultIterator(page MigrationConfigListResultPage) MigrationConfigListResultIterator { - return MigrationConfigListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (mclr MigrationConfigListResult) IsEmpty() bool { - return mclr.Value == nil || len(*mclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (mclr MigrationConfigListResult) hasNextLink() bool { - return mclr.NextLink != nil && len(*mclr.NextLink) != 0 -} - -// migrationConfigListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (mclr MigrationConfigListResult) migrationConfigListResultPreparer(ctx context.Context) (*http.Request, error) { - if !mclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(mclr.NextLink))) -} - -// MigrationConfigListResultPage contains a page of MigrationConfigProperties values. -type MigrationConfigListResultPage struct { - fn func(context.Context, MigrationConfigListResult) (MigrationConfigListResult, error) - mclr MigrationConfigListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *MigrationConfigListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/MigrationConfigListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.mclr) - if err != nil { - return err - } - page.mclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *MigrationConfigListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the MigrationConfigListResultPage type. -func NewMigrationConfigListResultPage(cur MigrationConfigListResult, getNextPage func(context.Context, MigrationConfigListResult) (MigrationConfigListResult, error)) MigrationConfigListResultPage { - return MigrationConfigListResultPage{ - fn: getNextPage, - mclr: cur, - } -} - -// 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"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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 - } - 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 "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - mcp.SystemData = &systemData - } - 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 - READ-ONLY; Provisioning state of Migration Configuration - ProvisioningState *string `json:"provisioningState,omitempty"` - // PendingReplicationOperationsCount - READ-ONLY; 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"` - // MigrationState - READ-ONLY; State in which Standard to Premium Migration is, possible values : Unknown, Reverting, Completing, Initiating, Syncing, Active - MigrationState *string `json:"migrationState,omitempty"` -} - -// MarshalJSON is the custom marshaler for MigrationConfigPropertiesProperties. -func (mcp MigrationConfigPropertiesProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mcp.TargetNamespace != nil { - objectMap["targetNamespace"] = mcp.TargetNamespace - } - if mcp.PostMigrationName != nil { - objectMap["postMigrationName"] = mcp.PostMigrationName - } - return json.Marshal(objectMap) -} - -// MigrationConfigsCreateAndStartMigrationFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type MigrationConfigsCreateAndStartMigrationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(MigrationConfigsClient) (MigrationConfigProperties, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *MigrationConfigsCreateAndStartMigrationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for MigrationConfigsCreateAndStartMigrationFuture.Result. -func (future *MigrationConfigsCreateAndStartMigrationFuture) result(client MigrationConfigsClient) (mcp MigrationConfigProperties, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsCreateAndStartMigrationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - mcp.Response.Response = future.Response() - 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.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(NamespacesClient) (SBNamespace, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *NamespacesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for NamespacesCreateOrUpdateFuture.Result. -func (future *NamespacesCreateOrUpdateFuture) result(client NamespacesClient) (sn SBNamespace, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.NamespacesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sn.Response.Response = future.Response() - 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.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(NamespacesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *NamespacesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for NamespacesDeleteFuture.Result. -func (future *NamespacesDeleteFuture) result(client NamespacesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.NamespacesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("servicebus.NamespacesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// NetworkRuleSet description of NetworkRuleSet resource. -type NetworkRuleSet struct { - autorest.Response `json:"-"` - // NetworkRuleSetProperties - NetworkRuleSet properties - *NetworkRuleSetProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for NetworkRuleSet. -func (nrs NetworkRuleSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if nrs.NetworkRuleSetProperties != nil { - objectMap["properties"] = nrs.NetworkRuleSetProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for NetworkRuleSet struct. -func (nrs *NetworkRuleSet) 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 networkRuleSetProperties NetworkRuleSetProperties - err = json.Unmarshal(*v, &networkRuleSetProperties) - if err != nil { - return err - } - nrs.NetworkRuleSetProperties = &networkRuleSetProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - nrs.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - nrs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - nrs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - nrs.Type = &typeVar - } - } - } - - return nil -} - -// NetworkRuleSetListResult the response of the List NetworkRuleSet operation. -type NetworkRuleSetListResult struct { - autorest.Response `json:"-"` - // Value - Result of the List NetworkRuleSet operation. - Value *[]NetworkRuleSet `json:"value,omitempty"` - // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of NetworkRuleSet. - NextLink *string `json:"nextLink,omitempty"` -} - -// NetworkRuleSetListResultIterator provides access to a complete listing of NetworkRuleSet values. -type NetworkRuleSetListResultIterator struct { - i int - page NetworkRuleSetListResultPage -} - -// NextWithContext 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 *NetworkRuleSetListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NetworkRuleSetListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *NetworkRuleSetListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter NetworkRuleSetListResultIterator) 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 NetworkRuleSetListResultIterator) Response() NetworkRuleSetListResult { - 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 NetworkRuleSetListResultIterator) Value() NetworkRuleSet { - if !iter.page.NotDone() { - return NetworkRuleSet{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the NetworkRuleSetListResultIterator type. -func NewNetworkRuleSetListResultIterator(page NetworkRuleSetListResultPage) NetworkRuleSetListResultIterator { - return NetworkRuleSetListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (nrslr NetworkRuleSetListResult) IsEmpty() bool { - return nrslr.Value == nil || len(*nrslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (nrslr NetworkRuleSetListResult) hasNextLink() bool { - return nrslr.NextLink != nil && len(*nrslr.NextLink) != 0 -} - -// networkRuleSetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (nrslr NetworkRuleSetListResult) networkRuleSetListResultPreparer(ctx context.Context) (*http.Request, error) { - if !nrslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(nrslr.NextLink))) -} - -// NetworkRuleSetListResultPage contains a page of NetworkRuleSet values. -type NetworkRuleSetListResultPage struct { - fn func(context.Context, NetworkRuleSetListResult) (NetworkRuleSetListResult, error) - nrslr NetworkRuleSetListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *NetworkRuleSetListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NetworkRuleSetListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.nrslr) - if err != nil { - return err - } - page.nrslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *NetworkRuleSetListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page NetworkRuleSetListResultPage) NotDone() bool { - return !page.nrslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page NetworkRuleSetListResultPage) Response() NetworkRuleSetListResult { - return page.nrslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page NetworkRuleSetListResultPage) Values() []NetworkRuleSet { - if page.nrslr.IsEmpty() { - return nil - } - return *page.nrslr.Value -} - -// Creates a new instance of the NetworkRuleSetListResultPage type. -func NewNetworkRuleSetListResultPage(cur NetworkRuleSetListResult, getNextPage func(context.Context, NetworkRuleSetListResult) (NetworkRuleSetListResult, error)) NetworkRuleSetListResultPage { - return NetworkRuleSetListResultPage{ - fn: getNextPage, - nrslr: cur, - } -} - -// NetworkRuleSetProperties networkRuleSet properties -type NetworkRuleSetProperties struct { - // TrustedServiceAccessEnabled - Value that indicates whether Trusted Service Access is Enabled or not. - TrustedServiceAccessEnabled *bool `json:"trustedServiceAccessEnabled,omitempty"` - // DefaultAction - Default Action for Network Rule Set. Possible values include: 'DefaultActionAllow', 'DefaultActionDeny' - DefaultAction DefaultAction `json:"defaultAction,omitempty"` - // VirtualNetworkRules - List VirtualNetwork Rules - VirtualNetworkRules *[]NWRuleSetVirtualNetworkRules `json:"virtualNetworkRules,omitempty"` - // IPRules - List of IpRules - IPRules *[]NWRuleSetIPRules `json:"ipRules,omitempty"` - // PublicNetworkAccess - This determines if traffic is allowed over public network. By default it is enabled. Possible values include: 'PublicNetworkAccessFlagEnabled', 'PublicNetworkAccessFlagDisabled' - PublicNetworkAccess PublicNetworkAccessFlag `json:"publicNetworkAccess,omitempty"` -} - -// NWRuleSetIPRules description of NetWorkRuleSet - IpRules resource. -type NWRuleSetIPRules struct { - // IPMask - IP Mask - IPMask *string `json:"ipMask,omitempty"` - // Action - The IP Filter Action. Possible values include: 'NetworkRuleIPActionAllow' - Action NetworkRuleIPAction `json:"action,omitempty"` -} - -// NWRuleSetVirtualNetworkRules description of VirtualNetworkRules - NetworkRules resource. -type NWRuleSetVirtualNetworkRules struct { - // Subnet - Subnet properties - Subnet *Subnet `json:"subnet,omitempty"` - // IgnoreMissingVnetServiceEndpoint - Value that indicates whether to ignore missing VNet Service Endpoint - IgnoreMissingVnetServiceEndpoint *bool `json:"ignoreMissingVnetServiceEndpoint,omitempty"` -} - -// Operation a ServiceBus REST API operation -type Operation struct { - // Name - READ-ONLY; Operation name: {provider}/{resource}/{operation} - Name *string `json:"name,omitempty"` - // Display - The object that represents the operation. - Display *OperationDisplay `json:"display,omitempty"` -} - -// MarshalJSON is the custom marshaler for Operation. -func (o Operation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if o.Display != nil { - objectMap["display"] = o.Display - } - return json.Marshal(objectMap) -} - -// OperationDisplay the object that represents the operation. -type OperationDisplay struct { - // Provider - READ-ONLY; Service provider: Microsoft.ServiceBus - Provider *string `json:"provider,omitempty"` - // Resource - READ-ONLY; Resource on which the operation is performed: Invoice, etc. - Resource *string `json:"resource,omitempty"` - // Operation - READ-ONLY; Operation type: Read, write, delete, etc. - Operation *string `json:"operation,omitempty"` -} - -// MarshalJSON is the custom marshaler for OperationDisplay. -func (o OperationDisplay) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// 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 - READ-ONLY; List of ServiceBus operations supported by the Microsoft.ServiceBus resource provider. - Value *[]Operation `json:"value,omitempty"` - // NextLink - READ-ONLY; URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for OperationListResult. -func (olr OperationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// OperationListResultIterator provides access to a complete listing of Operation values. -type OperationListResultIterator struct { - i int - page OperationListResultPage -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *OperationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the OperationListResultIterator type. -func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator { - return OperationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (olr OperationListResult) IsEmpty() bool { - return olr.Value == nil || len(*olr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (olr OperationListResult) hasNextLink() bool { - return olr.NextLink != nil && len(*olr.NextLink) != 0 -} - -// operationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (olr OperationListResult) operationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !olr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(olr.NextLink))) -} - -// OperationListResultPage contains a page of Operation values. -type OperationListResultPage struct { - fn func(context.Context, OperationListResult) (OperationListResult, error) - olr OperationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.olr) - if err != nil { - return err - } - page.olr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *OperationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the OperationListResultPage type. -func NewOperationListResultPage(cur OperationListResult, getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage { - return OperationListResultPage{ - fn: getNextPage, - olr: cur, - } -} - -// PrivateEndpoint privateEndpoint information. -type PrivateEndpoint struct { - // ID - The ARM identifier for Private Endpoint. - ID *string `json:"id,omitempty"` -} - -// PrivateEndpointConnection properties of the PrivateEndpointConnection. -type PrivateEndpointConnection struct { - autorest.Response `json:"-"` - // PrivateEndpointConnectionProperties - Properties of the PrivateEndpointConnection. - *PrivateEndpointConnectionProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointConnection. -func (pec PrivateEndpointConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pec.PrivateEndpointConnectionProperties != nil { - objectMap["properties"] = pec.PrivateEndpointConnectionProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateEndpointConnection struct. -func (pec *PrivateEndpointConnection) 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 privateEndpointConnectionProperties PrivateEndpointConnectionProperties - err = json.Unmarshal(*v, &privateEndpointConnectionProperties) - if err != nil { - return err - } - pec.PrivateEndpointConnectionProperties = &privateEndpointConnectionProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - pec.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pec.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pec.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pec.Type = &typeVar - } - } - } - - return nil -} - -// PrivateEndpointConnectionListResult result of the list of all private endpoint connections operation. -type PrivateEndpointConnectionListResult struct { - autorest.Response `json:"-"` - // Value - A collection of private endpoint connection resources. - Value *[]PrivateEndpointConnection `json:"value,omitempty"` - // NextLink - A link for the next page of private endpoint connection resources. - NextLink *string `json:"nextLink,omitempty"` -} - -// PrivateEndpointConnectionListResultIterator provides access to a complete listing of -// PrivateEndpointConnection values. -type PrivateEndpointConnectionListResultIterator struct { - i int - page PrivateEndpointConnectionListResultPage -} - -// NextWithContext 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 *PrivateEndpointConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PrivateEndpointConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PrivateEndpointConnectionListResultIterator) 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 PrivateEndpointConnectionListResultIterator) Response() PrivateEndpointConnectionListResult { - 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 PrivateEndpointConnectionListResultIterator) Value() PrivateEndpointConnection { - if !iter.page.NotDone() { - return PrivateEndpointConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PrivateEndpointConnectionListResultIterator type. -func NewPrivateEndpointConnectionListResultIterator(page PrivateEndpointConnectionListResultPage) PrivateEndpointConnectionListResultIterator { - return PrivateEndpointConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (peclr PrivateEndpointConnectionListResult) IsEmpty() bool { - return peclr.Value == nil || len(*peclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (peclr PrivateEndpointConnectionListResult) hasNextLink() bool { - return peclr.NextLink != nil && len(*peclr.NextLink) != 0 -} - -// privateEndpointConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (peclr PrivateEndpointConnectionListResult) privateEndpointConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !peclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(peclr.NextLink))) -} - -// PrivateEndpointConnectionListResultPage contains a page of PrivateEndpointConnection values. -type PrivateEndpointConnectionListResultPage struct { - fn func(context.Context, PrivateEndpointConnectionListResult) (PrivateEndpointConnectionListResult, error) - peclr PrivateEndpointConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PrivateEndpointConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.peclr) - if err != nil { - return err - } - page.peclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PrivateEndpointConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PrivateEndpointConnectionListResultPage) NotDone() bool { - return !page.peclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PrivateEndpointConnectionListResultPage) Response() PrivateEndpointConnectionListResult { - return page.peclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PrivateEndpointConnectionListResultPage) Values() []PrivateEndpointConnection { - if page.peclr.IsEmpty() { - return nil - } - return *page.peclr.Value -} - -// Creates a new instance of the PrivateEndpointConnectionListResultPage type. -func NewPrivateEndpointConnectionListResultPage(cur PrivateEndpointConnectionListResult, getNextPage func(context.Context, PrivateEndpointConnectionListResult) (PrivateEndpointConnectionListResult, error)) PrivateEndpointConnectionListResultPage { - return PrivateEndpointConnectionListResultPage{ - fn: getNextPage, - peclr: cur, - } -} - -// PrivateEndpointConnectionProperties properties of the private endpoint connection resource. -type PrivateEndpointConnectionProperties struct { - // PrivateEndpoint - The Private Endpoint resource for this Connection. - PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` - // PrivateLinkServiceConnectionState - Details about the state of the connection. - PrivateLinkServiceConnectionState *ConnectionState `json:"privateLinkServiceConnectionState,omitempty"` - // ProvisioningState - Provisioning state of the Private Endpoint Connection. Possible values include: 'EndPointProvisioningStateCreating', 'EndPointProvisioningStateUpdating', 'EndPointProvisioningStateDeleting', 'EndPointProvisioningStateSucceeded', 'EndPointProvisioningStateCanceled', 'EndPointProvisioningStateFailed' - ProvisioningState EndPointProvisioningState `json:"provisioningState,omitempty"` -} - -// PrivateEndpointConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PrivateEndpointConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateEndpointConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateEndpointConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateEndpointConnectionsDeleteFuture.Result. -func (future *PrivateEndpointConnectionsDeleteFuture) result(client PrivateEndpointConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("servicebus.PrivateEndpointConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PrivateLinkResource information of the private link resource. -type PrivateLinkResource struct { - // PrivateLinkResourceProperties - Properties of the private link resource. - *PrivateLinkResourceProperties `json:"properties,omitempty"` - // ID - Fully qualified identifier of the resource. - ID *string `json:"id,omitempty"` - // Name - Name of the resource - Name *string `json:"name,omitempty"` - // Type - Type of the resource - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkResource. -func (plr PrivateLinkResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if plr.PrivateLinkResourceProperties != nil { - objectMap["properties"] = plr.PrivateLinkResourceProperties - } - if plr.ID != nil { - objectMap["id"] = plr.ID - } - if plr.Name != nil { - objectMap["name"] = plr.Name - } - if plr.Type != nil { - objectMap["type"] = plr.Type - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateLinkResource struct. -func (plr *PrivateLinkResource) 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 privateLinkResourceProperties PrivateLinkResourceProperties - err = json.Unmarshal(*v, &privateLinkResourceProperties) - if err != nil { - return err - } - plr.PrivateLinkResourceProperties = &privateLinkResourceProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - plr.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - plr.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - plr.Type = &typeVar - } - } - } - - return nil -} - -// PrivateLinkResourceProperties properties of PrivateLinkResource -type PrivateLinkResourceProperties struct { - GroupID *string `json:"groupId,omitempty"` - // RequiredMembers - Required Members - RequiredMembers *[]string `json:"requiredMembers,omitempty"` - // RequiredZoneNames - Required Zone Names - RequiredZoneNames *[]string `json:"requiredZoneNames,omitempty"` -} - -// PrivateLinkResourcesListResult result of the List private link resources operation. -type PrivateLinkResourcesListResult struct { - autorest.Response `json:"-"` - // Value - A collection of private link resources - Value *[]PrivateLinkResource `json:"value,omitempty"` - // NextLink - A link for the next page of private link resources. - NextLink *string `json:"nextLink,omitempty"` -} - -// RegenerateAccessKeyParameters parameters supplied to the Regenerate Authorization Rule operation, -// specifies which key needs to be reset. -type RegenerateAccessKeyParameters struct { - // KeyType - The access key to regenerate. Possible values include: 'KeyTypePrimaryKey', 'KeyTypeSecondaryKey' - 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 - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// 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 - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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 - } - return json.Marshal(objectMap) -} - -// Rule description of Rule Resource. -type Rule struct { - autorest.Response `json:"-"` - // Ruleproperties - Properties of Rule resource - *Ruleproperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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 - } - 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 "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - r.SystemData = &systemData - } - 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 -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the RuleListResultIterator type. -func NewRuleListResultIterator(page RuleListResultPage) RuleListResultIterator { - return RuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rlr RuleListResult) IsEmpty() bool { - return rlr.Value == nil || len(*rlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rlr RuleListResult) hasNextLink() bool { - return rlr.NextLink != nil && len(*rlr.NextLink) != 0 -} - -// ruleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rlr RuleListResult) ruleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rlr.NextLink))) -} - -// RuleListResultPage contains a page of Rule values. -type RuleListResultPage struct { - fn func(context.Context, RuleListResult) (RuleListResult, error) - rlr RuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rlr) - if err != nil { - return err - } - page.rlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the RuleListResultPage type. -func NewRuleListResultPage(cur RuleListResult, getNextPage func(context.Context, RuleListResult) (RuleListResult, error)) RuleListResultPage { - return RuleListResultPage{ - fn: getNextPage, - rlr: cur, - } -} - -// 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"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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 - } - 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 "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - sar.SystemData = &systemData - } - 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 -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBAuthorizationRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SBAuthorizationRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the SBAuthorizationRuleListResultIterator type. -func NewSBAuthorizationRuleListResultIterator(page SBAuthorizationRuleListResultPage) SBAuthorizationRuleListResultIterator { - return SBAuthorizationRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sarlr SBAuthorizationRuleListResult) IsEmpty() bool { - return sarlr.Value == nil || len(*sarlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sarlr SBAuthorizationRuleListResult) hasNextLink() bool { - return sarlr.NextLink != nil && len(*sarlr.NextLink) != 0 -} - -// sBAuthorizationRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sarlr SBAuthorizationRuleListResult) sBAuthorizationRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !sarlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sarlr.NextLink))) -} - -// SBAuthorizationRuleListResultPage contains a page of SBAuthorizationRule values. -type SBAuthorizationRuleListResultPage struct { - fn func(context.Context, SBAuthorizationRuleListResult) (SBAuthorizationRuleListResult, error) - sarlr SBAuthorizationRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SBAuthorizationRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBAuthorizationRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sarlr) - if err != nil { - return err - } - page.sarlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SBAuthorizationRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the SBAuthorizationRuleListResultPage type. -func NewSBAuthorizationRuleListResultPage(cur SBAuthorizationRuleListResult, getNextPage func(context.Context, SBAuthorizationRuleListResult) (SBAuthorizationRuleListResult, error)) SBAuthorizationRuleListResultPage { - return SBAuthorizationRuleListResultPage{ - fn: getNextPage, - sarlr: cur, - } -} - -// SBAuthorizationRuleProperties authorizationRule properties. -type SBAuthorizationRuleProperties struct { - // Rights - The rights associated with the rule. - Rights *[]AccessRights `json:"rights,omitempty"` -} - -// SBClientAffineProperties properties specific to client affine subscriptions. -type SBClientAffineProperties struct { - // ClientID - Indicates the Client ID of the application that created the client-affine subscription. - ClientID *string `json:"clientId,omitempty"` - // IsDurable - For client-affine subscriptions, this value indicates whether the subscription is durable or not. - IsDurable *bool `json:"isDurable,omitempty"` - // IsShared - For client-affine subscriptions, this value indicates whether the subscription is shared or not. - IsShared *bool `json:"isShared,omitempty"` -} - -// SBNamespace description of a namespace resource. -type SBNamespace struct { - autorest.Response `json:"-"` - // Sku - Properties of SKU - Sku *SBSku `json:"sku,omitempty"` - // Identity - Properties of BYOK Identity description - Identity *Identity `json:"identity,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,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 - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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.Identity != nil { - objectMap["identity"] = sn.Identity - } - if sn.SBNamespaceProperties != nil { - objectMap["properties"] = sn.SBNamespaceProperties - } - if sn.Location != nil { - objectMap["location"] = sn.Location - } - if sn.Tags != nil { - objectMap["tags"] = sn.Tags - } - 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 "identity": - if v != nil { - var identity Identity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - sn.Identity = &identity - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - sn.SystemData = &systemData - } - 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 -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBNamespaceListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SBNamespaceListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the SBNamespaceListResultIterator type. -func NewSBNamespaceListResultIterator(page SBNamespaceListResultPage) SBNamespaceListResultIterator { - return SBNamespaceListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (snlr SBNamespaceListResult) IsEmpty() bool { - return snlr.Value == nil || len(*snlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (snlr SBNamespaceListResult) hasNextLink() bool { - return snlr.NextLink != nil && len(*snlr.NextLink) != 0 -} - -// sBNamespaceListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (snlr SBNamespaceListResult) sBNamespaceListResultPreparer(ctx context.Context) (*http.Request, error) { - if !snlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(snlr.NextLink))) -} - -// SBNamespaceListResultPage contains a page of SBNamespace values. -type SBNamespaceListResultPage struct { - fn func(context.Context, SBNamespaceListResult) (SBNamespaceListResult, error) - snlr SBNamespaceListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SBNamespaceListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBNamespaceListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.snlr) - if err != nil { - return err - } - page.snlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SBNamespaceListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the SBNamespaceListResultPage type. -func NewSBNamespaceListResultPage(cur SBNamespaceListResult, getNextPage func(context.Context, SBNamespaceListResult) (SBNamespaceListResult, error)) SBNamespaceListResultPage { - return SBNamespaceListResultPage{ - fn: getNextPage, - snlr: cur, - } -} - -// SBNamespaceProperties properties of the namespace. -type SBNamespaceProperties struct { - // ProvisioningState - READ-ONLY; Provisioning state of the namespace. - ProvisioningState *string `json:"provisioningState,omitempty"` - // Status - READ-ONLY; Status of the namespace. - Status *string `json:"status,omitempty"` - // CreatedAt - READ-ONLY; The time the namespace was created - CreatedAt *date.Time `json:"createdAt,omitempty"` - // UpdatedAt - READ-ONLY; The time the namespace was updated. - UpdatedAt *date.Time `json:"updatedAt,omitempty"` - // ServiceBusEndpoint - READ-ONLY; Endpoint you can use to perform Service Bus operations. - ServiceBusEndpoint *string `json:"serviceBusEndpoint,omitempty"` - // MetricID - READ-ONLY; Identifier for Azure Insights metrics - MetricID *string `json:"metricId,omitempty"` - // ZoneRedundant - Enabling this property creates a Premium Service Bus Namespace in regions supported availability zones. - ZoneRedundant *bool `json:"zoneRedundant,omitempty"` - // Encryption - Properties of BYOK Encryption description - Encryption *Encryption `json:"encryption,omitempty"` - // PrivateEndpointConnections - List of private endpoint connections. - PrivateEndpointConnections *[]PrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` - // DisableLocalAuth - This property disables SAS authentication for the Service Bus namespace. - DisableLocalAuth *bool `json:"disableLocalAuth,omitempty"` -} - -// MarshalJSON is the custom marshaler for SBNamespaceProperties. -func (snp SBNamespaceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if snp.ZoneRedundant != nil { - objectMap["zoneRedundant"] = snp.ZoneRedundant - } - if snp.Encryption != nil { - objectMap["encryption"] = snp.Encryption - } - if snp.PrivateEndpointConnections != nil { - objectMap["privateEndpointConnections"] = snp.PrivateEndpointConnections - } - if snp.DisableLocalAuth != nil { - objectMap["disableLocalAuth"] = snp.DisableLocalAuth - } - return json.Marshal(objectMap) -} - -// SBNamespaceUpdateParameters description of a namespace resource. -type SBNamespaceUpdateParameters struct { - // Sku - Properties of SKU - Sku *SBSku `json:"sku,omitempty"` - // SBNamespaceProperties - Properties of the namespace. - *SBNamespaceProperties `json:"properties,omitempty"` - // Identity - Properties of BYOK Identity description - Identity *Identity `json:"identity,omitempty"` - // Location - Resource location - Location *string `json:"location,omitempty"` - // Tags - Resource tags - Tags map[string]*string `json:"tags"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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.Identity != nil { - objectMap["identity"] = snup.Identity - } - if snup.Location != nil { - objectMap["location"] = snup.Location - } - if snup.Tags != nil { - objectMap["tags"] = snup.Tags - } - 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 "identity": - if v != nil { - var identity Identity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - snup.Identity = &identity - } - 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"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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 - } - 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 "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - sq.SystemData = &systemData - } - 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 -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBQueueListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SBQueueListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the SBQueueListResultIterator type. -func NewSBQueueListResultIterator(page SBQueueListResultPage) SBQueueListResultIterator { - return SBQueueListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sqlr SBQueueListResult) IsEmpty() bool { - return sqlr.Value == nil || len(*sqlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sqlr SBQueueListResult) hasNextLink() bool { - return sqlr.NextLink != nil && len(*sqlr.NextLink) != 0 -} - -// sBQueueListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sqlr SBQueueListResult) sBQueueListResultPreparer(ctx context.Context) (*http.Request, error) { - if !sqlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sqlr.NextLink))) -} - -// SBQueueListResultPage contains a page of SBQueue values. -type SBQueueListResultPage struct { - fn func(context.Context, SBQueueListResult) (SBQueueListResult, error) - sqlr SBQueueListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SBQueueListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBQueueListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sqlr) - if err != nil { - return err - } - page.sqlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SBQueueListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the SBQueueListResultPage type. -func NewSBQueueListResultPage(cur SBQueueListResult, getNextPage func(context.Context, SBQueueListResult) (SBQueueListResult, error)) SBQueueListResultPage { - return SBQueueListResultPage{ - fn: getNextPage, - sqlr: cur, - } -} - -// SBQueueProperties the Queue Properties definition. -type SBQueueProperties struct { - // CountDetails - READ-ONLY; Message Count Details. - CountDetails *MessageCountDetails `json:"countDetails,omitempty"` - // CreatedAt - READ-ONLY; The exact time the message was created. - CreatedAt *date.Time `json:"createdAt,omitempty"` - // UpdatedAt - READ-ONLY; The exact time the message was updated. - UpdatedAt *date.Time `json:"updatedAt,omitempty"` - // AccessedAt - READ-ONLY; 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 - READ-ONLY; The size of the queue, in bytes. - SizeInBytes *int64 `json:"sizeInBytes,omitempty"` - // MessageCount - READ-ONLY; 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"` - // MaxMessageSizeInKilobytes - Maximum size (in KB) of the message payload that can be accepted by the queue. This property is only used in Premium today and default is 1024. - MaxMessageSizeInKilobytes *int64 `json:"maxMessageSizeInKilobytes,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: 'EntityStatusActive', 'EntityStatusDisabled', 'EntityStatusRestoring', 'EntityStatusSendDisabled', 'EntityStatusReceiveDisabled', 'EntityStatusCreating', 'EntityStatusDeleting', 'EntityStatusRenaming', 'EntityStatusUnknown' - 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"` -} - -// MarshalJSON is the custom marshaler for SBQueueProperties. -func (sqp SBQueueProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sqp.LockDuration != nil { - objectMap["lockDuration"] = sqp.LockDuration - } - if sqp.MaxSizeInMegabytes != nil { - objectMap["maxSizeInMegabytes"] = sqp.MaxSizeInMegabytes - } - if sqp.MaxMessageSizeInKilobytes != nil { - objectMap["maxMessageSizeInKilobytes"] = sqp.MaxMessageSizeInKilobytes - } - if sqp.RequiresDuplicateDetection != nil { - objectMap["requiresDuplicateDetection"] = sqp.RequiresDuplicateDetection - } - if sqp.RequiresSession != nil { - objectMap["requiresSession"] = sqp.RequiresSession - } - if sqp.DefaultMessageTimeToLive != nil { - objectMap["defaultMessageTimeToLive"] = sqp.DefaultMessageTimeToLive - } - if sqp.DeadLetteringOnMessageExpiration != nil { - objectMap["deadLetteringOnMessageExpiration"] = sqp.DeadLetteringOnMessageExpiration - } - if sqp.DuplicateDetectionHistoryTimeWindow != nil { - objectMap["duplicateDetectionHistoryTimeWindow"] = sqp.DuplicateDetectionHistoryTimeWindow - } - if sqp.MaxDeliveryCount != nil { - objectMap["maxDeliveryCount"] = sqp.MaxDeliveryCount - } - if sqp.Status != "" { - objectMap["status"] = sqp.Status - } - if sqp.EnableBatchedOperations != nil { - objectMap["enableBatchedOperations"] = sqp.EnableBatchedOperations - } - if sqp.AutoDeleteOnIdle != nil { - objectMap["autoDeleteOnIdle"] = sqp.AutoDeleteOnIdle - } - if sqp.EnablePartitioning != nil { - objectMap["enablePartitioning"] = sqp.EnablePartitioning - } - if sqp.EnableExpress != nil { - objectMap["enableExpress"] = sqp.EnableExpress - } - if sqp.ForwardTo != nil { - objectMap["forwardTo"] = sqp.ForwardTo - } - if sqp.ForwardDeadLetteredMessagesTo != nil { - objectMap["forwardDeadLetteredMessagesTo"] = sqp.ForwardDeadLetteredMessagesTo - } - return json.Marshal(objectMap) -} - -// SBSku SKU of the namespace. -type SBSku struct { - // Name - Name of this SKU. Possible values include: 'SkuNameBasic', 'SkuNameStandard', 'SkuNamePremium' - 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"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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 - } - 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 "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - ss.SystemData = &systemData - } - 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 -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBSubscriptionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SBSubscriptionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the SBSubscriptionListResultIterator type. -func NewSBSubscriptionListResultIterator(page SBSubscriptionListResultPage) SBSubscriptionListResultIterator { - return SBSubscriptionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sslr SBSubscriptionListResult) IsEmpty() bool { - return sslr.Value == nil || len(*sslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sslr SBSubscriptionListResult) hasNextLink() bool { - return sslr.NextLink != nil && len(*sslr.NextLink) != 0 -} - -// sBSubscriptionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sslr SBSubscriptionListResult) sBSubscriptionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !sslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sslr.NextLink))) -} - -// SBSubscriptionListResultPage contains a page of SBSubscription values. -type SBSubscriptionListResultPage struct { - fn func(context.Context, SBSubscriptionListResult) (SBSubscriptionListResult, error) - sslr SBSubscriptionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SBSubscriptionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBSubscriptionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sslr) - if err != nil { - return err - } - page.sslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SBSubscriptionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the SBSubscriptionListResultPage type. -func NewSBSubscriptionListResultPage(cur SBSubscriptionListResult, getNextPage func(context.Context, SBSubscriptionListResult) (SBSubscriptionListResult, error)) SBSubscriptionListResultPage { - return SBSubscriptionListResultPage{ - fn: getNextPage, - sslr: cur, - } -} - -// SBSubscriptionProperties description of Subscription Resource. -type SBSubscriptionProperties struct { - // MessageCount - READ-ONLY; Number of messages. - MessageCount *int64 `json:"messageCount,omitempty"` - // CreatedAt - READ-ONLY; Exact time the message was created. - CreatedAt *date.Time `json:"createdAt,omitempty"` - // AccessedAt - READ-ONLY; Last time there was a receive request to this subscription. - AccessedAt *date.Time `json:"accessedAt,omitempty"` - // UpdatedAt - READ-ONLY; The exact time the message was updated. - UpdatedAt *date.Time `json:"updatedAt,omitempty"` - // CountDetails - READ-ONLY; 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: 'EntityStatusActive', 'EntityStatusDisabled', 'EntityStatusRestoring', 'EntityStatusSendDisabled', 'EntityStatusReceiveDisabled', 'EntityStatusCreating', 'EntityStatusDeleting', 'EntityStatusRenaming', 'EntityStatusUnknown' - 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"` - // IsClientAffine - Value that indicates whether the subscription has an affinity to the client id. - IsClientAffine *bool `json:"isClientAffine,omitempty"` - // ClientAffineProperties - Properties specific to client affine subscriptions. - ClientAffineProperties *SBClientAffineProperties `json:"clientAffineProperties,omitempty"` -} - -// MarshalJSON is the custom marshaler for SBSubscriptionProperties. -func (ssp SBSubscriptionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ssp.LockDuration != nil { - objectMap["lockDuration"] = ssp.LockDuration - } - if ssp.RequiresSession != nil { - objectMap["requiresSession"] = ssp.RequiresSession - } - if ssp.DefaultMessageTimeToLive != nil { - objectMap["defaultMessageTimeToLive"] = ssp.DefaultMessageTimeToLive - } - if ssp.DeadLetteringOnFilterEvaluationExceptions != nil { - objectMap["deadLetteringOnFilterEvaluationExceptions"] = ssp.DeadLetteringOnFilterEvaluationExceptions - } - if ssp.DeadLetteringOnMessageExpiration != nil { - objectMap["deadLetteringOnMessageExpiration"] = ssp.DeadLetteringOnMessageExpiration - } - if ssp.DuplicateDetectionHistoryTimeWindow != nil { - objectMap["duplicateDetectionHistoryTimeWindow"] = ssp.DuplicateDetectionHistoryTimeWindow - } - if ssp.MaxDeliveryCount != nil { - objectMap["maxDeliveryCount"] = ssp.MaxDeliveryCount - } - if ssp.Status != "" { - objectMap["status"] = ssp.Status - } - if ssp.EnableBatchedOperations != nil { - objectMap["enableBatchedOperations"] = ssp.EnableBatchedOperations - } - if ssp.AutoDeleteOnIdle != nil { - objectMap["autoDeleteOnIdle"] = ssp.AutoDeleteOnIdle - } - if ssp.ForwardTo != nil { - objectMap["forwardTo"] = ssp.ForwardTo - } - if ssp.ForwardDeadLetteredMessagesTo != nil { - objectMap["forwardDeadLetteredMessagesTo"] = ssp.ForwardDeadLetteredMessagesTo - } - if ssp.IsClientAffine != nil { - objectMap["isClientAffine"] = ssp.IsClientAffine - } - if ssp.ClientAffineProperties != nil { - objectMap["clientAffineProperties"] = ssp.ClientAffineProperties - } - return json.Marshal(objectMap) -} - -// SBTopic description of topic resource. -type SBTopic struct { - autorest.Response `json:"-"` - // SBTopicProperties - Properties of topic resource. - *SBTopicProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system meta data relating to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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 - } - 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 "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - st.SystemData = &systemData - } - 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 -} - -// NextWithContext 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) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBTopicListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SBTopicListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// 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] -} - -// Creates a new instance of the SBTopicListResultIterator type. -func NewSBTopicListResultIterator(page SBTopicListResultPage) SBTopicListResultIterator { - return SBTopicListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (stlr SBTopicListResult) IsEmpty() bool { - return stlr.Value == nil || len(*stlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (stlr SBTopicListResult) hasNextLink() bool { - return stlr.NextLink != nil && len(*stlr.NextLink) != 0 -} - -// sBTopicListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (stlr SBTopicListResult) sBTopicListResultPreparer(ctx context.Context) (*http.Request, error) { - if !stlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(stlr.NextLink))) -} - -// SBTopicListResultPage contains a page of SBTopic values. -type SBTopicListResultPage struct { - fn func(context.Context, SBTopicListResult) (SBTopicListResult, error) - stlr SBTopicListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SBTopicListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SBTopicListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.stlr) - if err != nil { - return err - } - page.stlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SBTopicListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// 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 -} - -// Creates a new instance of the SBTopicListResultPage type. -func NewSBTopicListResultPage(cur SBTopicListResult, getNextPage func(context.Context, SBTopicListResult) (SBTopicListResult, error)) SBTopicListResultPage { - return SBTopicListResultPage{ - fn: getNextPage, - stlr: cur, - } -} - -// SBTopicProperties the Topic Properties definition. -type SBTopicProperties struct { - // SizeInBytes - READ-ONLY; Size of the topic, in bytes. - SizeInBytes *int64 `json:"sizeInBytes,omitempty"` - // CreatedAt - READ-ONLY; Exact time the message was created. - CreatedAt *date.Time `json:"createdAt,omitempty"` - // UpdatedAt - READ-ONLY; The exact time the message was updated. - UpdatedAt *date.Time `json:"updatedAt,omitempty"` - // AccessedAt - READ-ONLY; Last time the message was sent, or a request was received, for this topic. - AccessedAt *date.Time `json:"accessedAt,omitempty"` - // SubscriptionCount - READ-ONLY; Number of subscriptions. - SubscriptionCount *int32 `json:"subscriptionCount,omitempty"` - // CountDetails - READ-ONLY; Message count details - 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"` - // MaxMessageSizeInKilobytes - Maximum size (in KB) of the message payload that can be accepted by the topic. This property is only used in Premium today and default is 1024. - MaxMessageSizeInKilobytes *int64 `json:"maxMessageSizeInKilobytes,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: 'EntityStatusActive', 'EntityStatusDisabled', 'EntityStatusRestoring', 'EntityStatusSendDisabled', 'EntityStatusReceiveDisabled', 'EntityStatusCreating', 'EntityStatusDeleting', 'EntityStatusRenaming', 'EntityStatusUnknown' - 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"` -} - -// MarshalJSON is the custom marshaler for SBTopicProperties. -func (stp SBTopicProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if stp.DefaultMessageTimeToLive != nil { - objectMap["defaultMessageTimeToLive"] = stp.DefaultMessageTimeToLive - } - if stp.MaxSizeInMegabytes != nil { - objectMap["maxSizeInMegabytes"] = stp.MaxSizeInMegabytes - } - if stp.MaxMessageSizeInKilobytes != nil { - objectMap["maxMessageSizeInKilobytes"] = stp.MaxMessageSizeInKilobytes - } - if stp.RequiresDuplicateDetection != nil { - objectMap["requiresDuplicateDetection"] = stp.RequiresDuplicateDetection - } - if stp.DuplicateDetectionHistoryTimeWindow != nil { - objectMap["duplicateDetectionHistoryTimeWindow"] = stp.DuplicateDetectionHistoryTimeWindow - } - if stp.EnableBatchedOperations != nil { - objectMap["enableBatchedOperations"] = stp.EnableBatchedOperations - } - if stp.Status != "" { - objectMap["status"] = stp.Status - } - if stp.SupportOrdering != nil { - objectMap["supportOrdering"] = stp.SupportOrdering - } - if stp.AutoDeleteOnIdle != nil { - objectMap["autoDeleteOnIdle"] = stp.AutoDeleteOnIdle - } - if stp.EnablePartitioning != nil { - objectMap["enablePartitioning"] = stp.EnablePartitioning - } - if stp.EnableExpress != nil { - objectMap["enableExpress"] = stp.EnableExpress - } - return json.Marshal(objectMap) -} - -// 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"` -} - -// Subnet properties supplied for Subnet -type Subnet struct { - // ID - Resource ID of Virtual Network Subnet - ID *string `json:"id,omitempty"` -} - -// SystemData metadata pertaining to creation and last modification of the resource. -type SystemData struct { - // CreatedBy - The identity that created the resource. - CreatedBy *string `json:"createdBy,omitempty"` - // CreatedByType - The type of identity that created the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' - CreatedByType CreatedByType `json:"createdByType,omitempty"` - // CreatedAt - The timestamp of resource creation (UTC). - CreatedAt *date.Time `json:"createdAt,omitempty"` - // LastModifiedBy - The identity that last modified the resource. - LastModifiedBy *string `json:"lastModifiedBy,omitempty"` - // LastModifiedByType - The type of identity that last modified the resource. Possible values include: 'CreatedByTypeUser', 'CreatedByTypeApplication', 'CreatedByTypeManagedIdentity', 'CreatedByTypeKey' - LastModifiedByType CreatedByType `json:"lastModifiedByType,omitempty"` - // LastModifiedAt - The type of identity that last modified the resource. - LastModifiedAt *date.Time `json:"lastModifiedAt,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 - READ-ONLY; Resource Id - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; 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 - } - return json.Marshal(objectMap) -} - -// UserAssignedIdentity recognized Dictionary value. -type UserAssignedIdentity struct { - // PrincipalID - READ-ONLY; Principal Id of user assigned identity - PrincipalID *string `json:"principalId,omitempty"` - // ClientID - READ-ONLY; Client Id of user assigned identity - ClientID *string `json:"clientId,omitempty"` -} - -// MarshalJSON is the custom marshaler for UserAssignedIdentity. -func (uai UserAssignedIdentity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// UserAssignedIdentityProperties ... -type UserAssignedIdentityProperties struct { - // UserAssignedIdentity - ARM ID of user Identity selected for encryption - UserAssignedIdentity *string `json:"userAssignedIdentity,omitempty"` -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/namespaces.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/namespaces.go deleted file mode 100644 index 6e34c5da36d8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/namespaces.go +++ /dev/null @@ -1,1600 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// NamespacesClient is the client for the Namespaces methods of the Servicebus service. -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 using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.CheckNameAvailabilityMethod") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - 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, - 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 authorization rule 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.CreateOrUpdateAuthorizationRule") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 client.Send(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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdateNetworkRuleSet create or update NetworkRuleSet for a Namespace. -// Parameters: -// resourceGroupName - name of the Resource group within the Azure subscription. -// namespaceName - the namespace name -// parameters - the Namespace IpFilterRule. -func (client NamespacesClient) CreateOrUpdateNetworkRuleSet(ctx context.Context, resourceGroupName string, namespaceName string, parameters NetworkRuleSet) (result NetworkRuleSet, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.CreateOrUpdateNetworkRuleSet") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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", "CreateOrUpdateNetworkRuleSet", err.Error()) - } - - req, err := client.CreateOrUpdateNetworkRuleSetPreparer(ctx, resourceGroupName, namespaceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CreateOrUpdateNetworkRuleSet", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateNetworkRuleSetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CreateOrUpdateNetworkRuleSet", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateNetworkRuleSetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CreateOrUpdateNetworkRuleSet", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdateNetworkRuleSetPreparer prepares the CreateOrUpdateNetworkRuleSet request. -func (client NamespacesClient) CreateOrUpdateNetworkRuleSetPreparer(ctx context.Context, resourceGroupName string, namespaceName string, parameters NetworkRuleSet) (*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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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}/networkRuleSets/default", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateNetworkRuleSetSender sends the CreateOrUpdateNetworkRuleSet request. The method will close the -// http.Response Body if it receives an error. -func (client NamespacesClient) CreateOrUpdateNetworkRuleSetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateNetworkRuleSetResponder handles the response to the CreateOrUpdateNetworkRuleSet request. The method always -// closes the http.Response Body. -func (client NamespacesClient) CreateOrUpdateNetworkRuleSetResponder(resp *http.Response) (result NetworkRuleSet, err error) { - err = autorest.Respond( - resp, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 = "2021-06-01-preview" - 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 - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - 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, - 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 authorization rule name. -func (client NamespacesClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.DeleteAuthorizationRule") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 authorization rule name. -func (client NamespacesClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string) (result SBAuthorizationRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.GetAuthorizationRule") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetNetworkRuleSet gets NetworkRuleSet for a Namespace. -// Parameters: -// resourceGroupName - name of the Resource group within the Azure subscription. -// namespaceName - the namespace name -func (client NamespacesClient) GetNetworkRuleSet(ctx context.Context, resourceGroupName string, namespaceName string) (result NetworkRuleSet, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.GetNetworkRuleSet") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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", "GetNetworkRuleSet", err.Error()) - } - - req, err := client.GetNetworkRuleSetPreparer(ctx, resourceGroupName, namespaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "GetNetworkRuleSet", nil, "Failure preparing request") - return - } - - resp, err := client.GetNetworkRuleSetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "GetNetworkRuleSet", resp, "Failure sending request") - return - } - - result, err = client.GetNetworkRuleSetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "GetNetworkRuleSet", resp, "Failure responding to request") - return - } - - return -} - -// GetNetworkRuleSetPreparer prepares the GetNetworkRuleSet request. -func (client NamespacesClient) GetNetworkRuleSetPreparer(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 = "2021-06-01-preview" - 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}/networkRuleSets/default", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetNetworkRuleSetSender sends the GetNetworkRuleSet request. The method will close the -// http.Response Body if it receives an error. -func (client NamespacesClient) GetNetworkRuleSetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetNetworkRuleSetResponder handles the response to the GetNetworkRuleSet request. The method always -// closes the http.Response Body. -func (client NamespacesClient) GetNetworkRuleSetResponder(resp *http.Response) (result NetworkRuleSet, err error) { - err = autorest.Respond( - resp, - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.List") - defer func() { - sc := -1 - if result.snlr.Response.Response != nil { - sc = result.snlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - if result.snlr.hasNextLink() && result.snlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults SBNamespaceListResult) (result SBNamespaceListResult, err error) { - req, err := lastResults.sBNamespaceListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.ListAuthorizationRules") - defer func() { - sc := -1 - if result.sarlr.Response.Response != nil { - sc = result.sarlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - if result.sarlr.hasNextLink() && result.sarlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) { - req, err := lastResults.sBAuthorizationRuleListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.ListAuthorizationRules") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.snlr.Response.Response != nil { - sc = result.snlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - if result.snlr.hasNextLink() && result.snlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults SBNamespaceListResult) (result SBNamespaceListResult, err error) { - req, err := lastResults.sBNamespaceListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 authorization rule name. -func (client NamespacesClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string) (result AccessKeys, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.ListKeys") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListNetworkRuleSets gets list of NetworkRuleSet for a Namespace. -// Parameters: -// resourceGroupName - name of the Resource group within the Azure subscription. -// namespaceName - the namespace name -func (client NamespacesClient) ListNetworkRuleSets(ctx context.Context, resourceGroupName string, namespaceName string) (result NetworkRuleSetListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.ListNetworkRuleSets") - defer func() { - sc := -1 - if result.nrslr.Response.Response != nil { - sc = result.nrslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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", "ListNetworkRuleSets", err.Error()) - } - - result.fn = client.listNetworkRuleSetsNextResults - req, err := client.ListNetworkRuleSetsPreparer(ctx, resourceGroupName, namespaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListNetworkRuleSets", nil, "Failure preparing request") - return - } - - resp, err := client.ListNetworkRuleSetsSender(req) - if err != nil { - result.nrslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListNetworkRuleSets", resp, "Failure sending request") - return - } - - result.nrslr, err = client.ListNetworkRuleSetsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListNetworkRuleSets", resp, "Failure responding to request") - return - } - if result.nrslr.hasNextLink() && result.nrslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListNetworkRuleSetsPreparer prepares the ListNetworkRuleSets request. -func (client NamespacesClient) ListNetworkRuleSetsPreparer(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 = "2021-06-01-preview" - 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}/networkRuleSets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListNetworkRuleSetsSender sends the ListNetworkRuleSets request. The method will close the -// http.Response Body if it receives an error. -func (client NamespacesClient) ListNetworkRuleSetsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListNetworkRuleSetsResponder handles the response to the ListNetworkRuleSets request. The method always -// closes the http.Response Body. -func (client NamespacesClient) ListNetworkRuleSetsResponder(resp *http.Response) (result NetworkRuleSetListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNetworkRuleSetsNextResults retrieves the next set of results, if any. -func (client NamespacesClient) listNetworkRuleSetsNextResults(ctx context.Context, lastResults NetworkRuleSetListResult) (result NetworkRuleSetListResult, err error) { - req, err := lastResults.networkRuleSetListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listNetworkRuleSetsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListNetworkRuleSetsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listNetworkRuleSetsNextResults", resp, "Failure sending next results request") - } - result, err = client.ListNetworkRuleSetsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listNetworkRuleSetsNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListNetworkRuleSetsComplete enumerates all values, automatically crossing page boundaries as required. -func (client NamespacesClient) ListNetworkRuleSetsComplete(ctx context.Context, resourceGroupName string, namespaceName string) (result NetworkRuleSetListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.ListNetworkRuleSets") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListNetworkRuleSets(ctx, resourceGroupName, namespaceName) - 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 authorization rule 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.RegenerateKeys") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NamespacesClient.Update") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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/preview/servicebus/mgmt/2021-06-01-preview/servicebus/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/operations.go deleted file mode 100644 index 9bcd98ac66db..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/operations.go +++ /dev/null @@ -1,140 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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/tracing" - "net/http" -) - -// OperationsClient is the client for the Operations methods of the Servicebus service. -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 using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.olr.Response.Response != nil { - sc = result.olr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - if result.olr.hasNextLink() && result.olr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults OperationListResult) (result OperationListResult, err error) { - req, err := lastResults.operationListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/privateendpointconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/privateendpointconnections.go deleted file mode 100644 index d6ea029c1544..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/privateendpointconnections.go +++ /dev/null @@ -1,431 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PrivateEndpointConnectionsClient is the client for the PrivateEndpointConnections methods of the Servicebus service. -type PrivateEndpointConnectionsClient struct { - BaseClient -} - -// NewPrivateEndpointConnectionsClient creates an instance of the PrivateEndpointConnectionsClient client. -func NewPrivateEndpointConnectionsClient(subscriptionID string) PrivateEndpointConnectionsClient { - return NewPrivateEndpointConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPrivateEndpointConnectionsClientWithBaseURI creates an instance of the PrivateEndpointConnectionsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewPrivateEndpointConnectionsClientWithBaseURI(baseURI string, subscriptionID string) PrivateEndpointConnectionsClient { - return PrivateEndpointConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates PrivateEndpointConnections of service namespace. -// Parameters: -// resourceGroupName - name of the Resource group within the Azure subscription. -// namespaceName - the namespace name -// privateEndpointConnectionName - the PrivateEndpointConnection name -// parameters - parameters supplied to update Status of PrivateEndPoint Connection to namespace resource. -func (client PrivateEndpointConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, privateEndpointConnectionName string, parameters PrivateEndpointConnection) (result PrivateEndpointConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.PrivateEndpointConnectionsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, namespaceName, privateEndpointConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "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.PrivateEndpointConnectionsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PrivateEndpointConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, privateEndpointConnectionName string, parameters PrivateEndpointConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "namespaceName": autorest.Encode("path", namespaceName), - "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PrivateEndpointConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes an existing Private Endpoint Connection. -// Parameters: -// resourceGroupName - name of the Resource group within the Azure subscription. -// namespaceName - the namespace name -// privateEndpointConnectionName - the PrivateEndpointConnection name -func (client PrivateEndpointConnectionsClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, privateEndpointConnectionName string) (result PrivateEndpointConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.PrivateEndpointConnectionsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName, privateEndpointConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PrivateEndpointConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string, privateEndpointConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "namespaceName": autorest.Encode("path", namespaceName), - "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-06-01-preview" - 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}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) DeleteSender(req *http.Request) (future PrivateEndpointConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PrivateEndpointConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a description for the specified Private Endpoint Connection. -// Parameters: -// resourceGroupName - name of the Resource group within the Azure subscription. -// namespaceName - the namespace name -// privateEndpointConnectionName - the PrivateEndpointConnection name -func (client PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, privateEndpointConnectionName string) (result PrivateEndpointConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.PrivateEndpointConnectionsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName, privateEndpointConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "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.PrivateEndpointConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PrivateEndpointConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string, privateEndpointConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "namespaceName": autorest.Encode("path", namespaceName), - "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2021-06-01-preview" - 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}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PrivateEndpointConnectionsClient) GetResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets the available PrivateEndpointConnections within a namespace. -// Parameters: -// resourceGroupName - name of the Resource group within the Azure subscription. -// namespaceName - the namespace name -func (client PrivateEndpointConnectionsClient) List(ctx context.Context, resourceGroupName string, namespaceName string) (result PrivateEndpointConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.List") - defer func() { - sc := -1 - if result.peclr.Response.Response != nil { - sc = result.peclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.PrivateEndpointConnectionsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, namespaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.peclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.peclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.peclr.hasNextLink() && result.peclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PrivateEndpointConnectionsClient) 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 = "2021-06-01-preview" - 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}/privateEndpointConnections", 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 PrivateEndpointConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PrivateEndpointConnectionsClient) ListResponder(resp *http.Response) (result PrivateEndpointConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 PrivateEndpointConnectionsClient) listNextResults(ctx context.Context, lastResults PrivateEndpointConnectionListResult) (result PrivateEndpointConnectionListResult, err error) { - req, err := lastResults.privateEndpointConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "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.PrivateEndpointConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateEndpointConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PrivateEndpointConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, namespaceName string) (result PrivateEndpointConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, namespaceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/privatelinkresources.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/privatelinkresources.go deleted file mode 100644 index 456d9a3947bb..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/privatelinkresources.go +++ /dev/null @@ -1,119 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PrivateLinkResourcesClient is the client for the PrivateLinkResources methods of the Servicebus service. -type PrivateLinkResourcesClient struct { - BaseClient -} - -// NewPrivateLinkResourcesClient creates an instance of the PrivateLinkResourcesClient client. -func NewPrivateLinkResourcesClient(subscriptionID string) PrivateLinkResourcesClient { - return NewPrivateLinkResourcesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPrivateLinkResourcesClientWithBaseURI creates an instance of the PrivateLinkResourcesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewPrivateLinkResourcesClientWithBaseURI(baseURI string, subscriptionID string) PrivateLinkResourcesClient { - return PrivateLinkResourcesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets lists of resources that supports Privatelinks. -// Parameters: -// resourceGroupName - name of the Resource group within the Azure subscription. -// namespaceName - the namespace name -func (client PrivateLinkResourcesClient) Get(ctx context.Context, resourceGroupName string, namespaceName string) (result PrivateLinkResourcesListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.PrivateLinkResourcesClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateLinkResourcesClient", "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.PrivateLinkResourcesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "servicebus.PrivateLinkResourcesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PrivateLinkResourcesClient) 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 = "2021-06-01-preview" - 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}/privateLinkResources", 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 PrivateLinkResourcesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PrivateLinkResourcesClient) GetResponder(resp *http.Response) (result PrivateLinkResourcesListResult, err error) { - err = autorest.Respond( - resp, - 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/preview/servicebus/mgmt/2021-06-01-preview/servicebus/queues.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/queues.go deleted file mode 100644 index 51860ed7400f..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/queues.go +++ /dev/null @@ -1,1069 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// QueuesClient is the client for the Queues methods of the Servicebus service. -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 using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 client.Send(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, - 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 authorization rule 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.CreateOrUpdateAuthorizationRule") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 authorization rule name. -func (client QueuesClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.DeleteAuthorizationRule") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 authorization rule name. -func (client QueuesClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result SBAuthorizationRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.GetAuthorizationRule") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListAuthorizationRules") - defer func() { - sc := -1 - if result.sarlr.Response.Response != nil { - sc = result.sarlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - if result.sarlr.hasNextLink() && result.sarlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) { - req, err := lastResults.sBAuthorizationRuleListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListAuthorizationRules") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListByNamespace") - defer func() { - sc := -1 - if result.sqlr.Response.Response != nil { - sc = result.sqlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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: int64(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: int64(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 - } - if result.sqlr.hasNextLink() && result.sqlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults SBQueueListResult) (result SBQueueListResult, err error) { - req, err := lastResults.sBQueueListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListByNamespace") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 authorization rule name. -func (client QueuesClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result AccessKeys, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListKeys") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 authorization rule 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.RegenerateKeys") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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/preview/servicebus/mgmt/2021-06-01-preview/servicebus/rules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/rules.go deleted file mode 100644 index 9fd10bb35e11..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/rules.go +++ /dev/null @@ -1,492 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RulesClient is the client for the Rules methods of the Servicebus service. -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 using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RulesClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RulesClient.ListBySubscriptions") - defer func() { - sc := -1 - if result.rlr.Response.Response != nil { - sc = result.rlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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: int64(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: int64(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 - } - if result.rlr.hasNextLink() && result.rlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults RuleListResult) (result RuleListResult, err error) { - req, err := lastResults.ruleListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RulesClient.ListBySubscriptions") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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/preview/servicebus/mgmt/2021-06-01-preview/servicebus/subscriptions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/subscriptions.go deleted file mode 100644 index 0f78e281c66e..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/subscriptions.go +++ /dev/null @@ -1,472 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SubscriptionsClient is the client for the Subscriptions methods of the Servicebus service. -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 using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionsClient.ListByTopic") - defer func() { - sc := -1 - if result.sslr.Response.Response != nil { - sc = result.sslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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: int64(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: int64(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 - } - if result.sslr.hasNextLink() && result.sslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults SBSubscriptionListResult) (result SBSubscriptionListResult, err error) { - req, err := lastResults.sBSubscriptionListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionsClient.ListByTopic") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByTopic(ctx, resourceGroupName, namespaceName, topicName, skip, top) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/topics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/topics.go deleted file mode 100644 index 91462d403a84..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/topics.go +++ /dev/null @@ -1,1069 +0,0 @@ -package servicebus - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// TopicsClient is the client for the Topics methods of the Servicebus service. -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 using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 client.Send(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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdateAuthorizationRule creates an authorization 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 authorization rule 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.CreateOrUpdateAuthorizationRule") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 authorization rule name. -func (client TopicsClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.DeleteAuthorizationRule") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 authorization rule name. -func (client TopicsClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) (result SBAuthorizationRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.GetAuthorizationRule") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListAuthorizationRules") - defer func() { - sc := -1 - if result.sarlr.Response.Response != nil { - sc = result.sarlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - if result.sarlr.hasNextLink() && result.sarlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) { - req, err := lastResults.sBAuthorizationRuleListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListAuthorizationRules") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListByNamespace") - defer func() { - sc := -1 - if result.stlr.Response.Response != nil { - sc = result.stlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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: int64(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: int64(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 - } - if result.stlr.hasNextLink() && result.stlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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(ctx context.Context, lastResults SBTopicListResult) (result SBTopicListResult, err error) { - req, err := lastResults.sBTopicListResultPreparer(ctx) - 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) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListByNamespace") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 authorization rule name. -func (client TopicsClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) (result AccessKeys, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListKeys") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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 authorization rule 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 tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.RegenerateKeys") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 - } - - 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 = "2021-06-01-preview" - 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 client.Send(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, - 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/preview/servicebus/mgmt/2021-06-01-preview/servicebus/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/version.go deleted file mode 100644 index 3da1a0663295..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package servicebus - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// 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() + " servicebus/2021-06-01-preview" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go deleted file mode 100644 index 63dc05785144..000000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go +++ /dev/null @@ -1,200 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto - -package descriptor - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - descriptorpb "google.golang.org/protobuf/types/descriptorpb" - reflect "reflect" -) - -// Symbols defined in public import of google/protobuf/descriptor.proto. - -type FieldDescriptorProto_Type = descriptorpb.FieldDescriptorProto_Type - -const FieldDescriptorProto_TYPE_DOUBLE = descriptorpb.FieldDescriptorProto_TYPE_DOUBLE -const FieldDescriptorProto_TYPE_FLOAT = descriptorpb.FieldDescriptorProto_TYPE_FLOAT -const FieldDescriptorProto_TYPE_INT64 = descriptorpb.FieldDescriptorProto_TYPE_INT64 -const FieldDescriptorProto_TYPE_UINT64 = descriptorpb.FieldDescriptorProto_TYPE_UINT64 -const FieldDescriptorProto_TYPE_INT32 = descriptorpb.FieldDescriptorProto_TYPE_INT32 -const FieldDescriptorProto_TYPE_FIXED64 = descriptorpb.FieldDescriptorProto_TYPE_FIXED64 -const FieldDescriptorProto_TYPE_FIXED32 = descriptorpb.FieldDescriptorProto_TYPE_FIXED32 -const FieldDescriptorProto_TYPE_BOOL = descriptorpb.FieldDescriptorProto_TYPE_BOOL -const FieldDescriptorProto_TYPE_STRING = descriptorpb.FieldDescriptorProto_TYPE_STRING -const FieldDescriptorProto_TYPE_GROUP = descriptorpb.FieldDescriptorProto_TYPE_GROUP -const FieldDescriptorProto_TYPE_MESSAGE = descriptorpb.FieldDescriptorProto_TYPE_MESSAGE -const FieldDescriptorProto_TYPE_BYTES = descriptorpb.FieldDescriptorProto_TYPE_BYTES -const FieldDescriptorProto_TYPE_UINT32 = descriptorpb.FieldDescriptorProto_TYPE_UINT32 -const FieldDescriptorProto_TYPE_ENUM = descriptorpb.FieldDescriptorProto_TYPE_ENUM -const FieldDescriptorProto_TYPE_SFIXED32 = descriptorpb.FieldDescriptorProto_TYPE_SFIXED32 -const FieldDescriptorProto_TYPE_SFIXED64 = descriptorpb.FieldDescriptorProto_TYPE_SFIXED64 -const FieldDescriptorProto_TYPE_SINT32 = descriptorpb.FieldDescriptorProto_TYPE_SINT32 -const FieldDescriptorProto_TYPE_SINT64 = descriptorpb.FieldDescriptorProto_TYPE_SINT64 - -var FieldDescriptorProto_Type_name = descriptorpb.FieldDescriptorProto_Type_name -var FieldDescriptorProto_Type_value = descriptorpb.FieldDescriptorProto_Type_value - -type FieldDescriptorProto_Label = descriptorpb.FieldDescriptorProto_Label - -const FieldDescriptorProto_LABEL_OPTIONAL = descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL -const FieldDescriptorProto_LABEL_REQUIRED = descriptorpb.FieldDescriptorProto_LABEL_REQUIRED -const FieldDescriptorProto_LABEL_REPEATED = descriptorpb.FieldDescriptorProto_LABEL_REPEATED - -var FieldDescriptorProto_Label_name = descriptorpb.FieldDescriptorProto_Label_name -var FieldDescriptorProto_Label_value = descriptorpb.FieldDescriptorProto_Label_value - -type FileOptions_OptimizeMode = descriptorpb.FileOptions_OptimizeMode - -const FileOptions_SPEED = descriptorpb.FileOptions_SPEED -const FileOptions_CODE_SIZE = descriptorpb.FileOptions_CODE_SIZE -const FileOptions_LITE_RUNTIME = descriptorpb.FileOptions_LITE_RUNTIME - -var FileOptions_OptimizeMode_name = descriptorpb.FileOptions_OptimizeMode_name -var FileOptions_OptimizeMode_value = descriptorpb.FileOptions_OptimizeMode_value - -type FieldOptions_CType = descriptorpb.FieldOptions_CType - -const FieldOptions_STRING = descriptorpb.FieldOptions_STRING -const FieldOptions_CORD = descriptorpb.FieldOptions_CORD -const FieldOptions_STRING_PIECE = descriptorpb.FieldOptions_STRING_PIECE - -var FieldOptions_CType_name = descriptorpb.FieldOptions_CType_name -var FieldOptions_CType_value = descriptorpb.FieldOptions_CType_value - -type FieldOptions_JSType = descriptorpb.FieldOptions_JSType - -const FieldOptions_JS_NORMAL = descriptorpb.FieldOptions_JS_NORMAL -const FieldOptions_JS_STRING = descriptorpb.FieldOptions_JS_STRING -const FieldOptions_JS_NUMBER = descriptorpb.FieldOptions_JS_NUMBER - -var FieldOptions_JSType_name = descriptorpb.FieldOptions_JSType_name -var FieldOptions_JSType_value = descriptorpb.FieldOptions_JSType_value - -type MethodOptions_IdempotencyLevel = descriptorpb.MethodOptions_IdempotencyLevel - -const MethodOptions_IDEMPOTENCY_UNKNOWN = descriptorpb.MethodOptions_IDEMPOTENCY_UNKNOWN -const MethodOptions_NO_SIDE_EFFECTS = descriptorpb.MethodOptions_NO_SIDE_EFFECTS -const MethodOptions_IDEMPOTENT = descriptorpb.MethodOptions_IDEMPOTENT - -var MethodOptions_IdempotencyLevel_name = descriptorpb.MethodOptions_IdempotencyLevel_name -var MethodOptions_IdempotencyLevel_value = descriptorpb.MethodOptions_IdempotencyLevel_value - -type FileDescriptorSet = descriptorpb.FileDescriptorSet -type FileDescriptorProto = descriptorpb.FileDescriptorProto -type DescriptorProto = descriptorpb.DescriptorProto -type ExtensionRangeOptions = descriptorpb.ExtensionRangeOptions -type FieldDescriptorProto = descriptorpb.FieldDescriptorProto -type OneofDescriptorProto = descriptorpb.OneofDescriptorProto -type EnumDescriptorProto = descriptorpb.EnumDescriptorProto -type EnumValueDescriptorProto = descriptorpb.EnumValueDescriptorProto -type ServiceDescriptorProto = descriptorpb.ServiceDescriptorProto -type MethodDescriptorProto = descriptorpb.MethodDescriptorProto - -const Default_MethodDescriptorProto_ClientStreaming = descriptorpb.Default_MethodDescriptorProto_ClientStreaming -const Default_MethodDescriptorProto_ServerStreaming = descriptorpb.Default_MethodDescriptorProto_ServerStreaming - -type FileOptions = descriptorpb.FileOptions - -const Default_FileOptions_JavaMultipleFiles = descriptorpb.Default_FileOptions_JavaMultipleFiles -const Default_FileOptions_JavaStringCheckUtf8 = descriptorpb.Default_FileOptions_JavaStringCheckUtf8 -const Default_FileOptions_OptimizeFor = descriptorpb.Default_FileOptions_OptimizeFor -const Default_FileOptions_CcGenericServices = descriptorpb.Default_FileOptions_CcGenericServices -const Default_FileOptions_JavaGenericServices = descriptorpb.Default_FileOptions_JavaGenericServices -const Default_FileOptions_PyGenericServices = descriptorpb.Default_FileOptions_PyGenericServices -const Default_FileOptions_PhpGenericServices = descriptorpb.Default_FileOptions_PhpGenericServices -const Default_FileOptions_Deprecated = descriptorpb.Default_FileOptions_Deprecated -const Default_FileOptions_CcEnableArenas = descriptorpb.Default_FileOptions_CcEnableArenas - -type MessageOptions = descriptorpb.MessageOptions - -const Default_MessageOptions_MessageSetWireFormat = descriptorpb.Default_MessageOptions_MessageSetWireFormat -const Default_MessageOptions_NoStandardDescriptorAccessor = descriptorpb.Default_MessageOptions_NoStandardDescriptorAccessor -const Default_MessageOptions_Deprecated = descriptorpb.Default_MessageOptions_Deprecated - -type FieldOptions = descriptorpb.FieldOptions - -const Default_FieldOptions_Ctype = descriptorpb.Default_FieldOptions_Ctype -const Default_FieldOptions_Jstype = descriptorpb.Default_FieldOptions_Jstype -const Default_FieldOptions_Lazy = descriptorpb.Default_FieldOptions_Lazy -const Default_FieldOptions_Deprecated = descriptorpb.Default_FieldOptions_Deprecated -const Default_FieldOptions_Weak = descriptorpb.Default_FieldOptions_Weak - -type OneofOptions = descriptorpb.OneofOptions -type EnumOptions = descriptorpb.EnumOptions - -const Default_EnumOptions_Deprecated = descriptorpb.Default_EnumOptions_Deprecated - -type EnumValueOptions = descriptorpb.EnumValueOptions - -const Default_EnumValueOptions_Deprecated = descriptorpb.Default_EnumValueOptions_Deprecated - -type ServiceOptions = descriptorpb.ServiceOptions - -const Default_ServiceOptions_Deprecated = descriptorpb.Default_ServiceOptions_Deprecated - -type MethodOptions = descriptorpb.MethodOptions - -const Default_MethodOptions_Deprecated = descriptorpb.Default_MethodOptions_Deprecated -const Default_MethodOptions_IdempotencyLevel = descriptorpb.Default_MethodOptions_IdempotencyLevel - -type UninterpretedOption = descriptorpb.UninterpretedOption -type SourceCodeInfo = descriptorpb.SourceCodeInfo -type GeneratedCodeInfo = descriptorpb.GeneratedCodeInfo -type DescriptorProto_ExtensionRange = descriptorpb.DescriptorProto_ExtensionRange -type DescriptorProto_ReservedRange = descriptorpb.DescriptorProto_ReservedRange -type EnumDescriptorProto_EnumReservedRange = descriptorpb.EnumDescriptorProto_EnumReservedRange -type UninterpretedOption_NamePart = descriptorpb.UninterpretedOption_NamePart -type SourceCodeInfo_Location = descriptorpb.SourceCodeInfo_Location -type GeneratedCodeInfo_Annotation = descriptorpb.GeneratedCodeInfo_Annotation - -var File_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto protoreflect.FileDescriptor - -var file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_rawDesc = []byte{ - 0x0a, 0x44, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, - 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, - 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, - 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x40, 0x5a, 0x3e, 0x67, 0x69, 0x74, 0x68, - 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, - 0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x3b, - 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x32, -} - -var file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_goTypes = []interface{}{} -var file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_init() } -func file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_init() { - if File_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_rawDesc, - NumEnums: 0, - NumMessages: 0, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_goTypes, - DependencyIndexes: file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_depIdxs, - }.Build() - File_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto = out.File - file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_rawDesc = nil - file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_goTypes = nil - file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_depIdxs = nil -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/README.md b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/README.md deleted file mode 100644 index a63d482d089a..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/README.md +++ /dev/null @@ -1,175 +0,0 @@ - -## `github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores` Documentation - -The `configurationstores` SDK allows for interaction with the Azure Resource Manager Service `appconfiguration` (API Version `2020-06-01`). - -This readme covers example usages, but further information on [using this SDK can be found in the project root](https://github.com/hashicorp/go-azure-sdk/tree/main/docs). - -### Import Path - -```go -import "github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores" -``` - - -### Client Initialization - -```go -client := configurationstores.NewConfigurationStoresClientWithBaseURI("https://management.azure.com") -client.Client.Authorizer = authorizer -``` - - -### Example Usage: `ConfigurationStoresClient.Create` - -```go -ctx := context.TODO() -id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") - -payload := configurationstores.ConfigurationStore{ - // ... -} - - -if err := client.CreateThenPoll(ctx, id, payload); err != nil { - // handle the error -} -``` - - -### Example Usage: `ConfigurationStoresClient.Delete` - -```go -ctx := context.TODO() -id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") - -if err := client.DeleteThenPoll(ctx, id); err != nil { - // handle the error -} -``` - - -### Example Usage: `ConfigurationStoresClient.Get` - -```go -ctx := context.TODO() -id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") - -read, err := client.Get(ctx, id) -if err != nil { - // handle the error -} -if model := read.Model; model != nil { - // do something with the model/response object -} -``` - - -### Example Usage: `ConfigurationStoresClient.List` - -```go -ctx := context.TODO() -id := configurationstores.NewSubscriptionID() - -// alternatively `client.List(ctx, id)` can be used to do batched pagination -items, err := client.ListComplete(ctx, id) -if err != nil { - // handle the error -} -for _, item := range items { - // do something -} -``` - - -### Example Usage: `ConfigurationStoresClient.ListByResourceGroup` - -```go -ctx := context.TODO() -id := configurationstores.NewResourceGroupID() - -// alternatively `client.ListByResourceGroup(ctx, id)` can be used to do batched pagination -items, err := client.ListByResourceGroupComplete(ctx, id) -if err != nil { - // handle the error -} -for _, item := range items { - // do something -} -``` - - -### Example Usage: `ConfigurationStoresClient.ListKeyValue` - -```go -ctx := context.TODO() -id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") - -payload := configurationstores.ListKeyValueParameters{ - // ... -} - - -read, err := client.ListKeyValue(ctx, id, payload) -if err != nil { - // handle the error -} -if model := read.Model; model != nil { - // do something with the model/response object -} -``` - - -### Example Usage: `ConfigurationStoresClient.ListKeys` - -```go -ctx := context.TODO() -id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") - -// alternatively `client.ListKeys(ctx, id)` can be used to do batched pagination -items, err := client.ListKeysComplete(ctx, id) -if err != nil { - // handle the error -} -for _, item := range items { - // do something -} -``` - - -### Example Usage: `ConfigurationStoresClient.RegenerateKey` - -```go -ctx := context.TODO() -id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") - -payload := configurationstores.RegenerateKeyParameters{ - // ... -} - - -read, err := client.RegenerateKey(ctx, id, payload) -if err != nil { - // handle the error -} -if model := read.Model; model != nil { - // do something with the model/response object -} -``` - - -### Example Usage: `ConfigurationStoresClient.Update` - -```go -ctx := context.TODO() -id := configurationstores.NewConfigurationStoreID("12345678-1234-9876-4563-123456789012", "example-resource-group", "configStoreValue") - -payload := configurationstores.ConfigurationStoreUpdateParameters{ - // ... -} - - -if err := client.UpdateThenPoll(ctx, id, payload); err != nil { - // handle the error -} -``` diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/client.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/client.go deleted file mode 100644 index a8a958bcfcfe..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/client.go +++ /dev/null @@ -1,18 +0,0 @@ -package configurationstores - -import "github.com/Azure/go-autorest/autorest" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ConfigurationStoresClient struct { - Client autorest.Client - baseUri string -} - -func NewConfigurationStoresClientWithBaseURI(endpoint string) ConfigurationStoresClient { - return ConfigurationStoresClient{ - Client: autorest.NewClientWithUserAgent(userAgent()), - baseUri: endpoint, - } -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/constants.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/constants.go deleted file mode 100644 index 38f2d8690346..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/constants.go +++ /dev/null @@ -1,136 +0,0 @@ -package configurationstores - -import "strings" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ActionsRequired string - -const ( - ActionsRequiredNone ActionsRequired = "None" - ActionsRequiredRecreate ActionsRequired = "Recreate" -) - -func PossibleValuesForActionsRequired() []string { - return []string{ - string(ActionsRequiredNone), - string(ActionsRequiredRecreate), - } -} - -func parseActionsRequired(input string) (*ActionsRequired, error) { - vals := map[string]ActionsRequired{ - "none": ActionsRequiredNone, - "recreate": ActionsRequiredRecreate, - } - if v, ok := vals[strings.ToLower(input)]; ok { - return &v, nil - } - - // otherwise presume it's an undefined value and best-effort it - out := ActionsRequired(input) - return &out, nil -} - -type ConnectionStatus string - -const ( - ConnectionStatusApproved ConnectionStatus = "Approved" - ConnectionStatusDisconnected ConnectionStatus = "Disconnected" - ConnectionStatusPending ConnectionStatus = "Pending" - ConnectionStatusRejected ConnectionStatus = "Rejected" -) - -func PossibleValuesForConnectionStatus() []string { - return []string{ - string(ConnectionStatusApproved), - string(ConnectionStatusDisconnected), - string(ConnectionStatusPending), - string(ConnectionStatusRejected), - } -} - -func parseConnectionStatus(input string) (*ConnectionStatus, error) { - vals := map[string]ConnectionStatus{ - "approved": ConnectionStatusApproved, - "disconnected": ConnectionStatusDisconnected, - "pending": ConnectionStatusPending, - "rejected": ConnectionStatusRejected, - } - if v, ok := vals[strings.ToLower(input)]; ok { - return &v, nil - } - - // otherwise presume it's an undefined value and best-effort it - out := ConnectionStatus(input) - return &out, nil -} - -type ProvisioningState string - -const ( - ProvisioningStateCanceled ProvisioningState = "Canceled" - ProvisioningStateCreating ProvisioningState = "Creating" - ProvisioningStateDeleting ProvisioningState = "Deleting" - ProvisioningStateFailed ProvisioningState = "Failed" - ProvisioningStateSucceeded ProvisioningState = "Succeeded" - ProvisioningStateUpdating ProvisioningState = "Updating" -) - -func PossibleValuesForProvisioningState() []string { - return []string{ - string(ProvisioningStateCanceled), - string(ProvisioningStateCreating), - string(ProvisioningStateDeleting), - string(ProvisioningStateFailed), - string(ProvisioningStateSucceeded), - string(ProvisioningStateUpdating), - } -} - -func parseProvisioningState(input string) (*ProvisioningState, error) { - vals := map[string]ProvisioningState{ - "canceled": ProvisioningStateCanceled, - "creating": ProvisioningStateCreating, - "deleting": ProvisioningStateDeleting, - "failed": ProvisioningStateFailed, - "succeeded": ProvisioningStateSucceeded, - "updating": ProvisioningStateUpdating, - } - if v, ok := vals[strings.ToLower(input)]; ok { - return &v, nil - } - - // otherwise presume it's an undefined value and best-effort it - out := ProvisioningState(input) - return &out, nil -} - -type PublicNetworkAccess string - -const ( - PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" - PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" -) - -func PossibleValuesForPublicNetworkAccess() []string { - return []string{ - string(PublicNetworkAccessDisabled), - string(PublicNetworkAccessEnabled), - } -} - -func parsePublicNetworkAccess(input string) (*PublicNetworkAccess, error) { - vals := map[string]PublicNetworkAccess{ - "disabled": PublicNetworkAccessDisabled, - "enabled": PublicNetworkAccessEnabled, - } - if v, ok := vals[strings.ToLower(input)]; ok { - return &v, nil - } - - // otherwise presume it's an undefined value and best-effort it - out := PublicNetworkAccess(input) - return &out, nil -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/id_configurationstore.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/id_configurationstore.go deleted file mode 100644 index 5e9fc5e6977b..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/id_configurationstore.go +++ /dev/null @@ -1,124 +0,0 @@ -package configurationstores - -import ( - "fmt" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" -) - -var _ resourceids.ResourceId = ConfigurationStoreId{} - -// ConfigurationStoreId is a struct representing the Resource ID for a Configuration Store -type ConfigurationStoreId struct { - SubscriptionId string - ResourceGroupName string - ConfigStoreName string -} - -// NewConfigurationStoreID returns a new ConfigurationStoreId struct -func NewConfigurationStoreID(subscriptionId string, resourceGroupName string, configStoreName string) ConfigurationStoreId { - return ConfigurationStoreId{ - SubscriptionId: subscriptionId, - ResourceGroupName: resourceGroupName, - ConfigStoreName: configStoreName, - } -} - -// ParseConfigurationStoreID parses 'input' into a ConfigurationStoreId -func ParseConfigurationStoreID(input string) (*ConfigurationStoreId, error) { - parser := resourceids.NewParserFromResourceIdType(ConfigurationStoreId{}) - parsed, err := parser.Parse(input, false) - if err != nil { - return nil, fmt.Errorf("parsing %q: %+v", input, err) - } - - var ok bool - id := ConfigurationStoreId{} - - if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { - return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) - } - - if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { - return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) - } - - if id.ConfigStoreName, ok = parsed.Parsed["configStoreName"]; !ok { - return nil, fmt.Errorf("the segment 'configStoreName' was not found in the resource id %q", input) - } - - return &id, nil -} - -// ParseConfigurationStoreIDInsensitively parses 'input' case-insensitively into a ConfigurationStoreId -// note: this method should only be used for API response data and not user input -func ParseConfigurationStoreIDInsensitively(input string) (*ConfigurationStoreId, error) { - parser := resourceids.NewParserFromResourceIdType(ConfigurationStoreId{}) - parsed, err := parser.Parse(input, true) - if err != nil { - return nil, fmt.Errorf("parsing %q: %+v", input, err) - } - - var ok bool - id := ConfigurationStoreId{} - - if id.SubscriptionId, ok = parsed.Parsed["subscriptionId"]; !ok { - return nil, fmt.Errorf("the segment 'subscriptionId' was not found in the resource id %q", input) - } - - if id.ResourceGroupName, ok = parsed.Parsed["resourceGroupName"]; !ok { - return nil, fmt.Errorf("the segment 'resourceGroupName' was not found in the resource id %q", input) - } - - if id.ConfigStoreName, ok = parsed.Parsed["configStoreName"]; !ok { - return nil, fmt.Errorf("the segment 'configStoreName' was not found in the resource id %q", input) - } - - return &id, nil -} - -// ValidateConfigurationStoreID checks that 'input' can be parsed as a Configuration Store ID -func ValidateConfigurationStoreID(input interface{}, key string) (warnings []string, errors []error) { - v, ok := input.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected %q to be a string", key)) - return - } - - if _, err := ParseConfigurationStoreID(v); err != nil { - errors = append(errors, err) - } - - return -} - -// ID returns the formatted Configuration Store ID -func (id ConfigurationStoreId) ID() string { - fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.AppConfiguration/configurationStores/%s" - return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ConfigStoreName) -} - -// Segments returns a slice of Resource ID Segments which comprise this Configuration Store ID -func (id ConfigurationStoreId) Segments() []resourceids.Segment { - return []resourceids.Segment{ - resourceids.StaticSegment("staticSubscriptions", "subscriptions", "subscriptions"), - resourceids.SubscriptionIdSegment("subscriptionId", "12345678-1234-9876-4563-123456789012"), - resourceids.StaticSegment("staticResourceGroups", "resourceGroups", "resourceGroups"), - resourceids.ResourceGroupSegment("resourceGroupName", "example-resource-group"), - resourceids.StaticSegment("staticProviders", "providers", "providers"), - resourceids.ResourceProviderSegment("staticMicrosoftAppConfiguration", "Microsoft.AppConfiguration", "Microsoft.AppConfiguration"), - resourceids.StaticSegment("staticConfigurationStores", "configurationStores", "configurationStores"), - resourceids.UserSpecifiedSegment("configStoreName", "configStoreValue"), - } -} - -// String returns a human-readable description of this Configuration Store ID -func (id ConfigurationStoreId) String() string { - components := []string{ - fmt.Sprintf("Subscription: %q", id.SubscriptionId), - fmt.Sprintf("Resource Group Name: %q", id.ResourceGroupName), - fmt.Sprintf("Config Store Name: %q", id.ConfigStoreName), - } - return fmt.Sprintf("Configuration Store (%s)", strings.Join(components, "\n")) -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_create_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_create_autorest.go deleted file mode 100644 index 584ebb8933eb..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_create_autorest.go +++ /dev/null @@ -1,79 +0,0 @@ -package configurationstores - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/go-azure-helpers/polling" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type CreateOperationResponse struct { - Poller polling.LongRunningPoller - HttpResponse *http.Response -} - -// Create ... -func (c ConfigurationStoresClient) Create(ctx context.Context, id ConfigurationStoreId, input ConfigurationStore) (result CreateOperationResponse, err error) { - req, err := c.preparerForCreate(ctx, id, input) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Create", nil, "Failure preparing request") - return - } - - result, err = c.senderForCreate(ctx, req) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Create", result.HttpResponse, "Failure sending request") - return - } - - return -} - -// CreateThenPoll performs Create then polls until it's completed -func (c ConfigurationStoresClient) CreateThenPoll(ctx context.Context, id ConfigurationStoreId, input ConfigurationStore) error { - result, err := c.Create(ctx, id, input) - if err != nil { - return fmt.Errorf("performing Create: %+v", err) - } - - if err := result.Poller.PollUntilDone(); err != nil { - return fmt.Errorf("polling after Create: %+v", err) - } - - return nil -} - -// preparerForCreate prepares the Create request. -func (c ConfigurationStoresClient) preparerForCreate(ctx context.Context, id ConfigurationStoreId, input ConfigurationStore) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "api-version": defaultApiVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(id.ID()), - autorest.WithJSON(input), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// senderForCreate sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (c ConfigurationStoresClient) senderForCreate(ctx context.Context, req *http.Request) (future CreateOperationResponse, err error) { - var resp *http.Response - resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - return - } - - future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) - return -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_delete_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_delete_autorest.go deleted file mode 100644 index aaff0f3cd6d6..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_delete_autorest.go +++ /dev/null @@ -1,78 +0,0 @@ -package configurationstores - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/go-azure-helpers/polling" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type DeleteOperationResponse struct { - Poller polling.LongRunningPoller - HttpResponse *http.Response -} - -// Delete ... -func (c ConfigurationStoresClient) Delete(ctx context.Context, id ConfigurationStoreId) (result DeleteOperationResponse, err error) { - req, err := c.preparerForDelete(ctx, id) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = c.senderForDelete(ctx, req) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Delete", result.HttpResponse, "Failure sending request") - return - } - - return -} - -// DeleteThenPoll performs Delete then polls until it's completed -func (c ConfigurationStoresClient) DeleteThenPoll(ctx context.Context, id ConfigurationStoreId) error { - result, err := c.Delete(ctx, id) - if err != nil { - return fmt.Errorf("performing Delete: %+v", err) - } - - if err := result.Poller.PollUntilDone(); err != nil { - return fmt.Errorf("polling after Delete: %+v", err) - } - - return nil -} - -// preparerForDelete prepares the Delete request. -func (c ConfigurationStoresClient) preparerForDelete(ctx context.Context, id ConfigurationStoreId) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "api-version": defaultApiVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(id.ID()), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// senderForDelete sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (c ConfigurationStoresClient) senderForDelete(ctx context.Context, req *http.Request) (future DeleteOperationResponse, err error) { - var resp *http.Response - resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - return - } - - future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) - return -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_get_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_get_autorest.go deleted file mode 100644 index 4428f3531bff..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_get_autorest.go +++ /dev/null @@ -1,67 +0,0 @@ -package configurationstores - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type GetOperationResponse struct { - HttpResponse *http.Response - Model *ConfigurationStore -} - -// Get ... -func (c ConfigurationStoresClient) Get(ctx context.Context, id ConfigurationStoreId) (result GetOperationResponse, err error) { - req, err := c.preparerForGet(ctx, id) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Get", nil, "Failure preparing request") - return - } - - result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Get", result.HttpResponse, "Failure sending request") - return - } - - result, err = c.responderForGet(result.HttpResponse) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Get", result.HttpResponse, "Failure responding to request") - return - } - - return -} - -// preparerForGet prepares the Get request. -func (c ConfigurationStoresClient) preparerForGet(ctx context.Context, id ConfigurationStoreId) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "api-version": defaultApiVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(id.ID()), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// responderForGet handles the response to the Get request. The method always -// closes the http.Response Body. -func (c ConfigurationStoresClient) responderForGet(resp *http.Response) (result GetOperationResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Model), - autorest.ByClosing()) - result.HttpResponse = resp - return -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_list_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_list_autorest.go deleted file mode 100644 index 1cf6264b5b35..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_list_autorest.go +++ /dev/null @@ -1,187 +0,0 @@ -package configurationstores - -import ( - "context" - "fmt" - "net/http" - "net/url" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ListOperationResponse struct { - HttpResponse *http.Response - Model *[]ConfigurationStore - - nextLink *string - nextPageFunc func(ctx context.Context, nextLink string) (ListOperationResponse, error) -} - -type ListCompleteResult struct { - Items []ConfigurationStore -} - -func (r ListOperationResponse) HasMore() bool { - return r.nextLink != nil -} - -func (r ListOperationResponse) LoadMore(ctx context.Context) (resp ListOperationResponse, err error) { - if !r.HasMore() { - err = fmt.Errorf("no more pages returned") - return - } - return r.nextPageFunc(ctx, *r.nextLink) -} - -// List ... -func (c ConfigurationStoresClient) List(ctx context.Context, id commonids.SubscriptionId) (resp ListOperationResponse, err error) { - req, err := c.preparerForList(ctx, id) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", nil, "Failure preparing request") - return - } - - resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", resp.HttpResponse, "Failure sending request") - return - } - - resp, err = c.responderForList(resp.HttpResponse) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", resp.HttpResponse, "Failure responding to request") - return - } - return -} - -// ListComplete retrieves all of the results into a single object -func (c ConfigurationStoresClient) ListComplete(ctx context.Context, id commonids.SubscriptionId) (ListCompleteResult, error) { - return c.ListCompleteMatchingPredicate(ctx, id, ConfigurationStoreOperationPredicate{}) -} - -// ListCompleteMatchingPredicate retrieves all of the results and then applied the predicate -func (c ConfigurationStoresClient) ListCompleteMatchingPredicate(ctx context.Context, id commonids.SubscriptionId, predicate ConfigurationStoreOperationPredicate) (resp ListCompleteResult, err error) { - items := make([]ConfigurationStore, 0) - - page, err := c.List(ctx, id) - if err != nil { - err = fmt.Errorf("loading the initial page: %+v", err) - return - } - if page.Model != nil { - for _, v := range *page.Model { - if predicate.Matches(v) { - items = append(items, v) - } - } - } - - for page.HasMore() { - page, err = page.LoadMore(ctx) - if err != nil { - err = fmt.Errorf("loading the next page: %+v", err) - return - } - - if page.Model != nil { - for _, v := range *page.Model { - if predicate.Matches(v) { - items = append(items, v) - } - } - } - } - - out := ListCompleteResult{ - Items: items, - } - return out, nil -} - -// preparerForList prepares the List request. -func (c ConfigurationStoresClient) preparerForList(ctx context.Context, id commonids.SubscriptionId) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "api-version": defaultApiVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.AppConfiguration/configurationStores", id.ID())), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// preparerForListWithNextLink prepares the List request with the given nextLink token. -func (c ConfigurationStoresClient) preparerForListWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { - uri, err := url.Parse(nextLink) - if err != nil { - return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) - } - queryParameters := map[string]interface{}{} - for k, v := range uri.Query() { - if len(v) == 0 { - continue - } - val := v[0] - val = autorest.Encode("query", val) - queryParameters[k] = val - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(uri.Path), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// responderForList handles the response to the List request. The method always -// closes the http.Response Body. -func (c ConfigurationStoresClient) responderForList(resp *http.Response) (result ListOperationResponse, err error) { - type page struct { - Values []ConfigurationStore `json:"value"` - NextLink *string `json:"nextLink"` - } - var respObj page - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&respObj), - autorest.ByClosing()) - result.HttpResponse = resp - result.Model = &respObj.Values - result.nextLink = respObj.NextLink - if respObj.NextLink != nil { - result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListOperationResponse, err error) { - req, err := c.preparerForListWithNextLink(ctx, nextLink) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", nil, "Failure preparing request") - return - } - - result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", result.HttpResponse, "Failure sending request") - return - } - - result, err = c.responderForList(result.HttpResponse) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "List", result.HttpResponse, "Failure responding to request") - return - } - - return - } - } - return -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listbyresourcegroup_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listbyresourcegroup_autorest.go deleted file mode 100644 index 06c80ed42a17..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listbyresourcegroup_autorest.go +++ /dev/null @@ -1,187 +0,0 @@ -package configurationstores - -import ( - "context" - "fmt" - "net/http" - "net/url" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ListByResourceGroupOperationResponse struct { - HttpResponse *http.Response - Model *[]ConfigurationStore - - nextLink *string - nextPageFunc func(ctx context.Context, nextLink string) (ListByResourceGroupOperationResponse, error) -} - -type ListByResourceGroupCompleteResult struct { - Items []ConfigurationStore -} - -func (r ListByResourceGroupOperationResponse) HasMore() bool { - return r.nextLink != nil -} - -func (r ListByResourceGroupOperationResponse) LoadMore(ctx context.Context) (resp ListByResourceGroupOperationResponse, err error) { - if !r.HasMore() { - err = fmt.Errorf("no more pages returned") - return - } - return r.nextPageFunc(ctx, *r.nextLink) -} - -// ListByResourceGroup ... -func (c ConfigurationStoresClient) ListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (resp ListByResourceGroupOperationResponse, err error) { - req, err := c.preparerForListByResourceGroup(ctx, id) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", resp.HttpResponse, "Failure sending request") - return - } - - resp, err = c.responderForListByResourceGroup(resp.HttpResponse) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", resp.HttpResponse, "Failure responding to request") - return - } - return -} - -// ListByResourceGroupComplete retrieves all of the results into a single object -func (c ConfigurationStoresClient) ListByResourceGroupComplete(ctx context.Context, id commonids.ResourceGroupId) (ListByResourceGroupCompleteResult, error) { - return c.ListByResourceGroupCompleteMatchingPredicate(ctx, id, ConfigurationStoreOperationPredicate{}) -} - -// ListByResourceGroupCompleteMatchingPredicate retrieves all of the results and then applied the predicate -func (c ConfigurationStoresClient) ListByResourceGroupCompleteMatchingPredicate(ctx context.Context, id commonids.ResourceGroupId, predicate ConfigurationStoreOperationPredicate) (resp ListByResourceGroupCompleteResult, err error) { - items := make([]ConfigurationStore, 0) - - page, err := c.ListByResourceGroup(ctx, id) - if err != nil { - err = fmt.Errorf("loading the initial page: %+v", err) - return - } - if page.Model != nil { - for _, v := range *page.Model { - if predicate.Matches(v) { - items = append(items, v) - } - } - } - - for page.HasMore() { - page, err = page.LoadMore(ctx) - if err != nil { - err = fmt.Errorf("loading the next page: %+v", err) - return - } - - if page.Model != nil { - for _, v := range *page.Model { - if predicate.Matches(v) { - items = append(items, v) - } - } - } - } - - out := ListByResourceGroupCompleteResult{ - Items: items, - } - return out, nil -} - -// preparerForListByResourceGroup prepares the ListByResourceGroup request. -func (c ConfigurationStoresClient) preparerForListByResourceGroup(ctx context.Context, id commonids.ResourceGroupId) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "api-version": defaultApiVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(fmt.Sprintf("%s/providers/Microsoft.AppConfiguration/configurationStores", id.ID())), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// preparerForListByResourceGroupWithNextLink prepares the ListByResourceGroup request with the given nextLink token. -func (c ConfigurationStoresClient) preparerForListByResourceGroupWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { - uri, err := url.Parse(nextLink) - if err != nil { - return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) - } - queryParameters := map[string]interface{}{} - for k, v := range uri.Query() { - if len(v) == 0 { - continue - } - val := v[0] - val = autorest.Encode("query", val) - queryParameters[k] = val - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(uri.Path), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// responderForListByResourceGroup handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (c ConfigurationStoresClient) responderForListByResourceGroup(resp *http.Response) (result ListByResourceGroupOperationResponse, err error) { - type page struct { - Values []ConfigurationStore `json:"value"` - NextLink *string `json:"nextLink"` - } - var respObj page - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&respObj), - autorest.ByClosing()) - result.HttpResponse = resp - result.Model = &respObj.Values - result.nextLink = respObj.NextLink - if respObj.NextLink != nil { - result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListByResourceGroupOperationResponse, err error) { - req, err := c.preparerForListByResourceGroupWithNextLink(ctx, nextLink) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", result.HttpResponse, "Failure sending request") - return - } - - result, err = c.responderForListByResourceGroup(result.HttpResponse) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListByResourceGroup", result.HttpResponse, "Failure responding to request") - return - } - - return - } - } - return -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listkeys_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listkeys_autorest.go deleted file mode 100644 index 0220a22f719b..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listkeys_autorest.go +++ /dev/null @@ -1,186 +0,0 @@ -package configurationstores - -import ( - "context" - "fmt" - "net/http" - "net/url" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ListKeysOperationResponse struct { - HttpResponse *http.Response - Model *[]ApiKey - - nextLink *string - nextPageFunc func(ctx context.Context, nextLink string) (ListKeysOperationResponse, error) -} - -type ListKeysCompleteResult struct { - Items []ApiKey -} - -func (r ListKeysOperationResponse) HasMore() bool { - return r.nextLink != nil -} - -func (r ListKeysOperationResponse) LoadMore(ctx context.Context) (resp ListKeysOperationResponse, err error) { - if !r.HasMore() { - err = fmt.Errorf("no more pages returned") - return - } - return r.nextPageFunc(ctx, *r.nextLink) -} - -// ListKeys ... -func (c ConfigurationStoresClient) ListKeys(ctx context.Context, id ConfigurationStoreId) (resp ListKeysOperationResponse, err error) { - req, err := c.preparerForListKeys(ctx, id) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", nil, "Failure preparing request") - return - } - - resp.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", resp.HttpResponse, "Failure sending request") - return - } - - resp, err = c.responderForListKeys(resp.HttpResponse) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", resp.HttpResponse, "Failure responding to request") - return - } - return -} - -// ListKeysComplete retrieves all of the results into a single object -func (c ConfigurationStoresClient) ListKeysComplete(ctx context.Context, id ConfigurationStoreId) (ListKeysCompleteResult, error) { - return c.ListKeysCompleteMatchingPredicate(ctx, id, ApiKeyOperationPredicate{}) -} - -// ListKeysCompleteMatchingPredicate retrieves all of the results and then applied the predicate -func (c ConfigurationStoresClient) ListKeysCompleteMatchingPredicate(ctx context.Context, id ConfigurationStoreId, predicate ApiKeyOperationPredicate) (resp ListKeysCompleteResult, err error) { - items := make([]ApiKey, 0) - - page, err := c.ListKeys(ctx, id) - if err != nil { - err = fmt.Errorf("loading the initial page: %+v", err) - return - } - if page.Model != nil { - for _, v := range *page.Model { - if predicate.Matches(v) { - items = append(items, v) - } - } - } - - for page.HasMore() { - page, err = page.LoadMore(ctx) - if err != nil { - err = fmt.Errorf("loading the next page: %+v", err) - return - } - - if page.Model != nil { - for _, v := range *page.Model { - if predicate.Matches(v) { - items = append(items, v) - } - } - } - } - - out := ListKeysCompleteResult{ - Items: items, - } - return out, nil -} - -// preparerForListKeys prepares the ListKeys request. -func (c ConfigurationStoresClient) preparerForListKeys(ctx context.Context, id ConfigurationStoreId) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "api-version": defaultApiVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(fmt.Sprintf("%s/listKeys", id.ID())), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// preparerForListKeysWithNextLink prepares the ListKeys request with the given nextLink token. -func (c ConfigurationStoresClient) preparerForListKeysWithNextLink(ctx context.Context, nextLink string) (*http.Request, error) { - uri, err := url.Parse(nextLink) - if err != nil { - return nil, fmt.Errorf("parsing nextLink %q: %+v", nextLink, err) - } - queryParameters := map[string]interface{}{} - for k, v := range uri.Query() { - if len(v) == 0 { - continue - } - val := v[0] - val = autorest.Encode("query", val) - queryParameters[k] = val - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(uri.Path), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// responderForListKeys handles the response to the ListKeys request. The method always -// closes the http.Response Body. -func (c ConfigurationStoresClient) responderForListKeys(resp *http.Response) (result ListKeysOperationResponse, err error) { - type page struct { - Values []ApiKey `json:"value"` - NextLink *string `json:"nextLink"` - } - var respObj page - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&respObj), - autorest.ByClosing()) - result.HttpResponse = resp - result.Model = &respObj.Values - result.nextLink = respObj.NextLink - if respObj.NextLink != nil { - result.nextPageFunc = func(ctx context.Context, nextLink string) (result ListKeysOperationResponse, err error) { - req, err := c.preparerForListKeysWithNextLink(ctx, nextLink) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", nil, "Failure preparing request") - return - } - - result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", result.HttpResponse, "Failure sending request") - return - } - - result, err = c.responderForListKeys(result.HttpResponse) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeys", result.HttpResponse, "Failure responding to request") - return - } - - return - } - } - return -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listkeyvalue_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listkeyvalue_autorest.go deleted file mode 100644 index 2ff84ac0ef8b..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_listkeyvalue_autorest.go +++ /dev/null @@ -1,69 +0,0 @@ -package configurationstores - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ListKeyValueOperationResponse struct { - HttpResponse *http.Response - Model *KeyValue -} - -// ListKeyValue ... -func (c ConfigurationStoresClient) ListKeyValue(ctx context.Context, id ConfigurationStoreId, input ListKeyValueParameters) (result ListKeyValueOperationResponse, err error) { - req, err := c.preparerForListKeyValue(ctx, id, input) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeyValue", nil, "Failure preparing request") - return - } - - result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeyValue", result.HttpResponse, "Failure sending request") - return - } - - result, err = c.responderForListKeyValue(result.HttpResponse) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "ListKeyValue", result.HttpResponse, "Failure responding to request") - return - } - - return -} - -// preparerForListKeyValue prepares the ListKeyValue request. -func (c ConfigurationStoresClient) preparerForListKeyValue(ctx context.Context, id ConfigurationStoreId, input ListKeyValueParameters) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "api-version": defaultApiVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(fmt.Sprintf("%s/listKeyValue", id.ID())), - autorest.WithJSON(input), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// responderForListKeyValue handles the response to the ListKeyValue request. The method always -// closes the http.Response Body. -func (c ConfigurationStoresClient) responderForListKeyValue(resp *http.Response) (result ListKeyValueOperationResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Model), - autorest.ByClosing()) - result.HttpResponse = resp - return -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_regeneratekey_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_regeneratekey_autorest.go deleted file mode 100644 index 2ec1bcb15921..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_regeneratekey_autorest.go +++ /dev/null @@ -1,69 +0,0 @@ -package configurationstores - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type RegenerateKeyOperationResponse struct { - HttpResponse *http.Response - Model *ApiKey -} - -// RegenerateKey ... -func (c ConfigurationStoresClient) RegenerateKey(ctx context.Context, id ConfigurationStoreId, input RegenerateKeyParameters) (result RegenerateKeyOperationResponse, err error) { - req, err := c.preparerForRegenerateKey(ctx, id, input) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "RegenerateKey", nil, "Failure preparing request") - return - } - - result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "RegenerateKey", result.HttpResponse, "Failure sending request") - return - } - - result, err = c.responderForRegenerateKey(result.HttpResponse) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "RegenerateKey", result.HttpResponse, "Failure responding to request") - return - } - - return -} - -// preparerForRegenerateKey prepares the RegenerateKey request. -func (c ConfigurationStoresClient) preparerForRegenerateKey(ctx context.Context, id ConfigurationStoreId, input RegenerateKeyParameters) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "api-version": defaultApiVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(fmt.Sprintf("%s/regenerateKey", id.ID())), - autorest.WithJSON(input), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// responderForRegenerateKey handles the response to the RegenerateKey request. The method always -// closes the http.Response Body. -func (c ConfigurationStoresClient) responderForRegenerateKey(resp *http.Response) (result RegenerateKeyOperationResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Model), - autorest.ByClosing()) - result.HttpResponse = resp - return -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_update_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_update_autorest.go deleted file mode 100644 index 970cc76c2972..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/method_update_autorest.go +++ /dev/null @@ -1,79 +0,0 @@ -package configurationstores - -import ( - "context" - "fmt" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/go-azure-helpers/polling" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type UpdateOperationResponse struct { - Poller polling.LongRunningPoller - HttpResponse *http.Response -} - -// Update ... -func (c ConfigurationStoresClient) Update(ctx context.Context, id ConfigurationStoreId, input ConfigurationStoreUpdateParameters) (result UpdateOperationResponse, err error) { - req, err := c.preparerForUpdate(ctx, id, input) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Update", nil, "Failure preparing request") - return - } - - result, err = c.senderForUpdate(ctx, req) - if err != nil { - err = autorest.NewErrorWithError(err, "configurationstores.ConfigurationStoresClient", "Update", result.HttpResponse, "Failure sending request") - return - } - - return -} - -// UpdateThenPoll performs Update then polls until it's completed -func (c ConfigurationStoresClient) UpdateThenPoll(ctx context.Context, id ConfigurationStoreId, input ConfigurationStoreUpdateParameters) error { - result, err := c.Update(ctx, id, input) - if err != nil { - return fmt.Errorf("performing Update: %+v", err) - } - - if err := result.Poller.PollUntilDone(); err != nil { - return fmt.Errorf("polling after Update: %+v", err) - } - - return nil -} - -// preparerForUpdate prepares the Update request. -func (c ConfigurationStoresClient) preparerForUpdate(ctx context.Context, id ConfigurationStoreId, input ConfigurationStoreUpdateParameters) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "api-version": defaultApiVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(c.baseUri), - autorest.WithPath(id.ID()), - autorest.WithJSON(input), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// senderForUpdate sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (c ConfigurationStoresClient) senderForUpdate(ctx context.Context, req *http.Request) (future UpdateOperationResponse, err error) { - var resp *http.Response - resp, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) - if err != nil { - return - } - - future.Poller, err = polling.NewPollerFromResponse(ctx, resp, c.Client, req.Method) - return -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_apikey.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_apikey.go deleted file mode 100644 index 9fa93145170e..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_apikey.go +++ /dev/null @@ -1,31 +0,0 @@ -package configurationstores - -import ( - "time" - - "github.com/hashicorp/go-azure-helpers/lang/dates" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ApiKey struct { - ConnectionString *string `json:"connectionString,omitempty"` - Id *string `json:"id,omitempty"` - LastModified *string `json:"lastModified,omitempty"` - Name *string `json:"name,omitempty"` - ReadOnly *bool `json:"readOnly,omitempty"` - Value *string `json:"value,omitempty"` -} - -func (o *ApiKey) GetLastModifiedAsTime() (*time.Time, error) { - if o.LastModified == nil { - return nil, nil - } - return dates.ParseAsFormat(o.LastModified, "2006-01-02T15:04:05Z07:00") -} - -func (o *ApiKey) SetLastModifiedAsTime(input time.Time) { - formatted := input.Format("2006-01-02T15:04:05Z07:00") - o.LastModified = &formatted -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstore.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstore.go deleted file mode 100644 index b27d5b647d42..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstore.go +++ /dev/null @@ -1,19 +0,0 @@ -package configurationstores - -import ( - "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ConfigurationStore struct { - Id *string `json:"id,omitempty"` - Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` - Location string `json:"location"` - Name *string `json:"name,omitempty"` - Properties *ConfigurationStoreProperties `json:"properties,omitempty"` - Sku Sku `json:"sku"` - Tags *map[string]string `json:"tags,omitempty"` - Type *string `json:"type,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstoreproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstoreproperties.go deleted file mode 100644 index d89c13e0b13f..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstoreproperties.go +++ /dev/null @@ -1,31 +0,0 @@ -package configurationstores - -import ( - "time" - - "github.com/hashicorp/go-azure-helpers/lang/dates" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ConfigurationStoreProperties struct { - CreationDate *string `json:"creationDate,omitempty"` - Encryption *EncryptionProperties `json:"encryption,omitempty"` - Endpoint *string `json:"endpoint,omitempty"` - PrivateEndpointConnections *[]PrivateEndpointConnectionReference `json:"privateEndpointConnections,omitempty"` - ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` - PublicNetworkAccess *PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` -} - -func (o *ConfigurationStoreProperties) GetCreationDateAsTime() (*time.Time, error) { - if o.CreationDate == nil { - return nil, nil - } - return dates.ParseAsFormat(o.CreationDate, "2006-01-02T15:04:05Z07:00") -} - -func (o *ConfigurationStoreProperties) SetCreationDateAsTime(input time.Time) { - formatted := input.Format("2006-01-02T15:04:05Z07:00") - o.CreationDate = &formatted -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstorepropertiesupdateparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstorepropertiesupdateparameters.go deleted file mode 100644 index a221c2e60539..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstorepropertiesupdateparameters.go +++ /dev/null @@ -1,9 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ConfigurationStorePropertiesUpdateParameters struct { - Encryption *EncryptionProperties `json:"encryption,omitempty"` - PublicNetworkAccess *PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstoreupdateparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstoreupdateparameters.go deleted file mode 100644 index f616d2a98ec3..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_configurationstoreupdateparameters.go +++ /dev/null @@ -1,15 +0,0 @@ -package configurationstores - -import ( - "github.com/hashicorp/go-azure-helpers/resourcemanager/identity" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ConfigurationStoreUpdateParameters struct { - Identity *identity.SystemAndUserAssignedMap `json:"identity,omitempty"` - Properties *ConfigurationStorePropertiesUpdateParameters `json:"properties,omitempty"` - Sku *Sku `json:"sku,omitempty"` - Tags *map[string]string `json:"tags,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_encryptionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_encryptionproperties.go deleted file mode 100644 index be0340c7047a..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_encryptionproperties.go +++ /dev/null @@ -1,8 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type EncryptionProperties struct { - KeyVaultProperties *KeyVaultProperties `json:"keyVaultProperties,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_keyvalue.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_keyvalue.go deleted file mode 100644 index 85eee3f305fc..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_keyvalue.go +++ /dev/null @@ -1,33 +0,0 @@ -package configurationstores - -import ( - "time" - - "github.com/hashicorp/go-azure-helpers/lang/dates" -) - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type KeyValue struct { - ContentType *string `json:"contentType,omitempty"` - ETag *string `json:"eTag,omitempty"` - Key *string `json:"key,omitempty"` - Label *string `json:"label,omitempty"` - LastModified *string `json:"lastModified,omitempty"` - Locked *bool `json:"locked,omitempty"` - Tags *map[string]string `json:"tags,omitempty"` - Value *string `json:"value,omitempty"` -} - -func (o *KeyValue) GetLastModifiedAsTime() (*time.Time, error) { - if o.LastModified == nil { - return nil, nil - } - return dates.ParseAsFormat(o.LastModified, "2006-01-02T15:04:05Z07:00") -} - -func (o *KeyValue) SetLastModifiedAsTime(input time.Time) { - formatted := input.Format("2006-01-02T15:04:05Z07:00") - o.LastModified = &formatted -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_keyvaultproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_keyvaultproperties.go deleted file mode 100644 index 1e6e63eb2f8c..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_keyvaultproperties.go +++ /dev/null @@ -1,9 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type KeyVaultProperties struct { - IdentityClientId *string `json:"identityClientId,omitempty"` - KeyIdentifier *string `json:"keyIdentifier,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_listkeyvalueparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_listkeyvalueparameters.go deleted file mode 100644 index 4af1da8070a2..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_listkeyvalueparameters.go +++ /dev/null @@ -1,9 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type ListKeyValueParameters struct { - Key string `json:"key"` - Label *string `json:"label,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpoint.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpoint.go deleted file mode 100644 index e52ec48dad00..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpoint.go +++ /dev/null @@ -1,8 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type PrivateEndpoint struct { - Id *string `json:"id,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpointconnectionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpointconnectionproperties.go deleted file mode 100644 index 7bd6508894c9..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpointconnectionproperties.go +++ /dev/null @@ -1,10 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type PrivateEndpointConnectionProperties struct { - PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` - PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState"` - ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpointconnectionreference.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpointconnectionreference.go deleted file mode 100644 index 3a67ff547973..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privateendpointconnectionreference.go +++ /dev/null @@ -1,11 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type PrivateEndpointConnectionReference struct { - Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Properties *PrivateEndpointConnectionProperties `json:"properties,omitempty"` - Type *string `json:"type,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privatelinkserviceconnectionstate.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privatelinkserviceconnectionstate.go deleted file mode 100644 index f6c8547cb4fb..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_privatelinkserviceconnectionstate.go +++ /dev/null @@ -1,10 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type PrivateLinkServiceConnectionState struct { - ActionsRequired *ActionsRequired `json:"actionsRequired,omitempty"` - Description *string `json:"description,omitempty"` - Status *ConnectionStatus `json:"status,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_regeneratekeyparameters.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_regeneratekeyparameters.go deleted file mode 100644 index f84013d2630f..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_regeneratekeyparameters.go +++ /dev/null @@ -1,8 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type RegenerateKeyParameters struct { - Id *string `json:"id,omitempty"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_sku.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_sku.go deleted file mode 100644 index 6472ed882f43..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/model_sku.go +++ /dev/null @@ -1,8 +0,0 @@ -package configurationstores - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -type Sku struct { - Name string `json:"name"` -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/predicates.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/predicates.go deleted file mode 100644 index d4541357a232..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/predicates.go +++ /dev/null @@ -1,67 +0,0 @@ -package configurationstores - -type ApiKeyOperationPredicate struct { - ConnectionString *string - Id *string - LastModified *string - Name *string - ReadOnly *bool - Value *string -} - -func (p ApiKeyOperationPredicate) Matches(input ApiKey) bool { - - if p.ConnectionString != nil && (input.ConnectionString == nil && *p.ConnectionString != *input.ConnectionString) { - return false - } - - if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { - return false - } - - if p.LastModified != nil && (input.LastModified == nil && *p.LastModified != *input.LastModified) { - return false - } - - if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { - return false - } - - if p.ReadOnly != nil && (input.ReadOnly == nil && *p.ReadOnly != *input.ReadOnly) { - return false - } - - if p.Value != nil && (input.Value == nil && *p.Value != *input.Value) { - return false - } - - return true -} - -type ConfigurationStoreOperationPredicate struct { - Id *string - Location *string - Name *string - Type *string -} - -func (p ConfigurationStoreOperationPredicate) Matches(input ConfigurationStore) bool { - - if p.Id != nil && (input.Id == nil && *p.Id != *input.Id) { - return false - } - - if p.Location != nil && *p.Location != input.Location { - return false - } - - if p.Name != nil && (input.Name == nil && *p.Name != *input.Name) { - return false - } - - if p.Type != nil && (input.Type == nil && *p.Type != *input.Type) { - return false - } - - return true -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/version.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/version.go deleted file mode 100644 index 27fcd4fd0ee9..000000000000 --- a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/appconfiguration/2020-06-01/configurationstores/version.go +++ /dev/null @@ -1,12 +0,0 @@ -package configurationstores - -import "fmt" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See NOTICE.txt in the project root for license information. - -const defaultApiVersion = "2020-06-01" - -func userAgent() string { - return fmt.Sprintf("hashicorp/go-azure-sdk/configurationstores/%s", defaultApiVersion) -} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/method_disasterrecoveryconfigschecknameavailability_autorest.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/method_disasterrecoveryconfigschecknameavailability_autorest.go new file mode 100644 index 000000000000..ea4861192a29 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/eventhub/2017-04-01/checknameavailabilitydisasterrecoveryconfigs/method_disasterrecoveryconfigschecknameavailability_autorest.go @@ -0,0 +1,69 @@ +package checknameavailabilitydisasterrecoveryconfigs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" +) + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type DisasterRecoveryConfigsCheckNameAvailabilityOperationResponse struct { + HttpResponse *http.Response + Model *CheckNameAvailabilityResult +} + +// DisasterRecoveryConfigsCheckNameAvailability ... +func (c CheckNameAvailabilityDisasterRecoveryConfigsClient) DisasterRecoveryConfigsCheckNameAvailability(ctx context.Context, id NamespaceId, input CheckNameAvailabilityParameter) (result DisasterRecoveryConfigsCheckNameAvailabilityOperationResponse, err error) { + req, err := c.preparerForDisasterRecoveryConfigsCheckNameAvailability(ctx, id, input) + if err != nil { + err = autorest.NewErrorWithError(err, "checknameavailabilitydisasterrecoveryconfigs.CheckNameAvailabilityDisasterRecoveryConfigsClient", "DisasterRecoveryConfigsCheckNameAvailability", nil, "Failure preparing request") + return + } + + result.HttpResponse, err = c.Client.Send(req, azure.DoRetryWithRegistration(c.Client)) + if err != nil { + err = autorest.NewErrorWithError(err, "checknameavailabilitydisasterrecoveryconfigs.CheckNameAvailabilityDisasterRecoveryConfigsClient", "DisasterRecoveryConfigsCheckNameAvailability", result.HttpResponse, "Failure sending request") + return + } + + result, err = c.responderForDisasterRecoveryConfigsCheckNameAvailability(result.HttpResponse) + if err != nil { + err = autorest.NewErrorWithError(err, "checknameavailabilitydisasterrecoveryconfigs.CheckNameAvailabilityDisasterRecoveryConfigsClient", "DisasterRecoveryConfigsCheckNameAvailability", result.HttpResponse, "Failure responding to request") + return + } + + return +} + +// preparerForDisasterRecoveryConfigsCheckNameAvailability prepares the DisasterRecoveryConfigsCheckNameAvailability request. +func (c CheckNameAvailabilityDisasterRecoveryConfigsClient) preparerForDisasterRecoveryConfigsCheckNameAvailability(ctx context.Context, id NamespaceId, input CheckNameAvailabilityParameter) (*http.Request, error) { + queryParameters := map[string]interface{}{ + "api-version": defaultApiVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(c.baseUri), + autorest.WithPath(fmt.Sprintf("%s/disasterRecoveryConfigs/checkNameAvailability", id.ID())), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// responderForDisasterRecoveryConfigsCheckNameAvailability handles the response to the DisasterRecoveryConfigsCheckNameAvailability request. The method always +// closes the http.Response Body. +func (c CheckNameAvailabilityDisasterRecoveryConfigsClient) responderForDisasterRecoveryConfigsCheckNameAvailability(resp *http.Response) (result DisasterRecoveryConfigsCheckNameAvailabilityOperationResponse, err error) { + err = autorest.Respond( + resp, + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Model), + autorest.ByClosing()) + result.HttpResponse = resp + return +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentpropertiesregistrationdefinitionproperties.go b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentpropertiesregistrationdefinitionproperties.go new file mode 100644 index 000000000000..da5e0aae8a60 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/resource-manager/managedservices/2019-06-01/registrationassignments/model_registrationassignmentpropertiesregistrationdefinitionproperties.go @@ -0,0 +1,15 @@ +package registrationassignments + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See NOTICE.txt in the project root for license information. + +type RegistrationAssignmentPropertiesRegistrationDefinitionProperties struct { + Authorizations *[]Authorization `json:"authorizations,omitempty"` + Description *string `json:"description,omitempty"` + ManagedByTenantId *string `json:"managedByTenantId,omitempty"` + ManagedByTenantName *string `json:"managedByTenantName,omitempty"` + ManageeTenantId *string `json:"manageeTenantId,omitempty"` + ManageeTenantName *string `json:"manageeTenantName,omitempty"` + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty"` + RegistrationDefinitionName *string `json:"registrationDefinitionName,omitempty"` +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/add.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/add.go deleted file mode 100644 index 0e60034e4937..000000000000 --- a/vendor/github.com/hashicorp/terraform-exec/tfexec/add.go +++ /dev/null @@ -1,101 +0,0 @@ -package tfexec - -import ( - "context" - "fmt" - "os/exec" - "strconv" - "strings" -) - -type addConfig struct { - fromState bool - out string - includeOptional bool - provider string - reattachInfo ReattachInfo -} - -var defaultAddOptions = addConfig{} - -type AddOption interface { - configureAdd(*addConfig) -} - -func (opt *FromStateOption) configureAdd(conf *addConfig) { - conf.fromState = opt.fromState -} - -func (opt *OutOption) configureAdd(conf *addConfig) { - conf.out = opt.path -} - -func (opt *IncludeOptionalOption) configureAdd(conf *addConfig) { - conf.includeOptional = opt.includeOptional -} - -func (opt *ProviderOption) configureAdd(conf *addConfig) { - conf.provider = opt.provider -} - -func (opt *ReattachOption) configureAdd(conf *addConfig) { - conf.reattachInfo = opt.info -} - -// Add represents the `terraform add` subcommand (added in 1.1.0). -// -// Note that this function signature and behaviour is subject -// to breaking changes including removal of that function -// until final 1.1.0 Terraform version (with this command) is released. -func (tf *Terraform) Add(ctx context.Context, address string, opts ...AddOption) (string, error) { - cmd, err := tf.addCmd(ctx, address, opts...) - if err != nil { - return "", err - } - - var outBuf strings.Builder - cmd.Stdout = mergeWriters(cmd.Stdout, &outBuf) - - if err := tf.runTerraformCmd(ctx, cmd); err != nil { - return "", err - } - - return outBuf.String(), nil -} - -func (tf *Terraform) addCmd(ctx context.Context, address string, opts ...AddOption) (*exec.Cmd, error) { - err := tf.compatible(ctx, tf1_1_0, nil) - if err != nil { - return nil, fmt.Errorf("terraform add was added in 1.1.0: %w", err) - } - - c := defaultAddOptions - - for _, o := range opts { - o.configureAdd(&c) - } - - args := []string{"add"} - - args = append(args, "-from-state="+strconv.FormatBool(c.fromState)) - if c.out != "" { - args = append(args, "-out="+c.out) - } - args = append(args, "-optional="+strconv.FormatBool(c.includeOptional)) - if c.provider != "" { - args = append(args, "-provider="+c.provider) - } - - args = append(args, address) - - mergeEnv := map[string]string{} - if c.reattachInfo != nil { - reattachStr, err := c.reattachInfo.marshalString() - if err != nil { - return nil, err - } - mergeEnv[reattachEnvVar] = reattachStr - } - - return tf.buildTerraformCmd(ctx, mergeEnv, args...), nil -} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/cmdstring.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/cmdstring.go deleted file mode 100644 index 4f81d1148e5f..000000000000 --- a/vendor/github.com/hashicorp/terraform-exec/tfexec/cmdstring.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build go1.13 - -package tfexec - -import ( - "os/exec" -) - -// cmdString handles go 1.12 as stringer was only added to exec.Cmd in 1.13 -func cmdString(c *exec.Cmd) string { - return c.String() -} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfexec/cmdstring_go112.go b/vendor/github.com/hashicorp/terraform-exec/tfexec/cmdstring_go112.go deleted file mode 100644 index 75614dbf6bb5..000000000000 --- a/vendor/github.com/hashicorp/terraform-exec/tfexec/cmdstring_go112.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !go1.13 - -package tfexec - -import ( - "os/exec" - "strings" -) - -// cmdString handles go 1.12 as stringer was only added to exec.Cmd in 1.13 -func cmdString(c *exec.Cmd) string { - b := new(strings.Builder) - b.WriteString(c.Path) - for _, a := range c.Args[1:] { - b.WriteByte(' ') - b.WriteString(a) - } - return b.String() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/generate.sh b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/generate.sh deleted file mode 100644 index ac9ec74b3e1c..000000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov5/internal/tfplugin5/generate.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -# We do not run protoc under go:generate because we want to ensure that all -# dependencies of go:generate are "go get"-able for general dev environment -# usability. To compile all protobuf files in this repository, run -# "make protobuf" at the top-level. - -set -eu - -SOURCE="${BASH_SOURCE[0]}" -while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done -DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" - -cd "$DIR" - -protoc --proto_path=. --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative tfplugin5.proto diff --git a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/generate.sh b/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/generate.sh deleted file mode 100644 index ca2a04688838..000000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-go/tfprotov6/internal/tfplugin6/generate.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -# We do not run protoc under go:generate because we want to ensure that all -# dependencies of go:generate are "go get"-able for general dev environment -# usability. To compile all protobuf files in this repository, run -# "make protobuf" at the top-level. - -set -eu - -SOURCE="${BASH_SOURCE[0]}" -while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done -DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" - -cd "$DIR" - -protoc --proto_path=. --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative tfplugin6.proto diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/single_attr_body.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/single_attr_body.go deleted file mode 100644 index 68f48da8f35c..000000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/single_attr_body.go +++ /dev/null @@ -1,85 +0,0 @@ -package hcl2shim - -import ( - "fmt" - - hcl2 "github.com/hashicorp/hcl/v2" -) - -// SingleAttrBody is a weird implementation of hcl2.Body that acts as if -// it has a single attribute whose value is the given expression. -// -// This is used to shim Resource.RawCount and Output.RawConfig to behave -// more like they do in the old HCL loader. -type SingleAttrBody struct { - Name string - Expr hcl2.Expression -} - -var _ hcl2.Body = SingleAttrBody{} - -func (b SingleAttrBody) Content(schema *hcl2.BodySchema) (*hcl2.BodyContent, hcl2.Diagnostics) { - content, all, diags := b.content(schema) - if !all { - // This should never happen because this body implementation should only - // be used by code that is aware that it's using a single-attr body. - diags = append(diags, &hcl2.Diagnostic{ - Severity: hcl2.DiagError, - Summary: "Invalid attribute", - Detail: fmt.Sprintf("The correct attribute name is %q.", b.Name), - Subject: b.Expr.Range().Ptr(), - }) - } - return content, diags -} - -func (b SingleAttrBody) PartialContent(schema *hcl2.BodySchema) (*hcl2.BodyContent, hcl2.Body, hcl2.Diagnostics) { - content, all, diags := b.content(schema) - var remain hcl2.Body - if all { - // If the request matched the one attribute we represent, then the - // remaining body is empty. - remain = hcl2.EmptyBody() - } else { - remain = b - } - return content, remain, diags -} - -func (b SingleAttrBody) content(schema *hcl2.BodySchema) (*hcl2.BodyContent, bool, hcl2.Diagnostics) { - ret := &hcl2.BodyContent{} - all := false - var diags hcl2.Diagnostics - - for _, attrS := range schema.Attributes { - if attrS.Name == b.Name { - attrs, _ := b.JustAttributes() - ret.Attributes = attrs - all = true - } else if attrS.Required { - diags = append(diags, &hcl2.Diagnostic{ - Severity: hcl2.DiagError, - Summary: "Missing attribute", - Detail: fmt.Sprintf("The attribute %q is required.", attrS.Name), - Subject: b.Expr.Range().Ptr(), - }) - } - } - - return ret, all, diags -} - -func (b SingleAttrBody) JustAttributes() (hcl2.Attributes, hcl2.Diagnostics) { - return hcl2.Attributes{ - b.Name: { - Expr: b.Expr, - Name: b.Name, - NameRange: b.Expr.Range(), - Range: b.Expr.Range(), - }, - }, nil -} - -func (b SingleAttrBody) MissingItemRange() hcl2.Range { - return b.Expr.Range() -} diff --git a/vendor/github.com/mattn/go-colorable/.travis.yml b/vendor/github.com/mattn/go-colorable/.travis.yml deleted file mode 100644 index 7942c565ce62..000000000000 --- a/vendor/github.com/mattn/go-colorable/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go -sudo: false -go: - - 1.13.x - - tip - -before_install: - - go get -t -v ./... - -script: - - ./go.test.sh - -after_success: - - bash <(curl -s https://codecov.io/bash) - diff --git a/vendor/github.com/mattn/go-isatty/.travis.yml b/vendor/github.com/mattn/go-isatty/.travis.yml deleted file mode 100644 index 604314dd44c3..000000000000 --- a/vendor/github.com/mattn/go-isatty/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go -sudo: false -go: - - 1.13.x - - tip - -before_install: - - go get -t -v ./... - -script: - - ./go.test.sh - -after_success: - - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/google.golang.org/grpc/credentials/go12.go b/vendor/google.golang.org/grpc/credentials/go12.go deleted file mode 100644 index ccbf35b33125..000000000000 --- a/vendor/google.golang.org/grpc/credentials/go12.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build go1.12 - -/* - * - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package credentials - -import "crypto/tls" - -// This init function adds cipher suite constants only defined in Go 1.12. -func init() { - cipherSuiteLookup[tls.TLS_AES_128_GCM_SHA256] = "TLS_AES_128_GCM_SHA256" - cipherSuiteLookup[tls.TLS_AES_256_GCM_SHA384] = "TLS_AES_256_GCM_SHA384" - cipherSuiteLookup[tls.TLS_CHACHA20_POLY1305_SHA256] = "TLS_CHACHA20_POLY1305_SHA256" -} diff --git a/vendor/google.golang.org/grpc/install_gae.sh b/vendor/google.golang.org/grpc/install_gae.sh deleted file mode 100644 index 15ff9facdd78..000000000000 --- a/vendor/google.golang.org/grpc/install_gae.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -TMP=$(mktemp -d /tmp/sdk.XXX) \ -&& curl -o $TMP.zip "https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip" \ -&& unzip -q $TMP.zip -d $TMP \ -&& export PATH="$PATH:$TMP/go_appengine" \ No newline at end of file diff --git a/vendor/google.golang.org/grpc/internal/credentials/spiffe_appengine.go b/vendor/google.golang.org/grpc/internal/credentials/spiffe_appengine.go deleted file mode 100644 index af6f57719768..000000000000 --- a/vendor/google.golang.org/grpc/internal/credentials/spiffe_appengine.go +++ /dev/null @@ -1,31 +0,0 @@ -// +build appengine - -/* - * - * Copyright 2020 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package credentials - -import ( - "crypto/tls" - "net/url" -) - -// SPIFFEIDFromState is a no-op for appengine builds. -func SPIFFEIDFromState(state tls.ConnectionState) *url.URL { - return nil -} diff --git a/vendor/google.golang.org/grpc/internal/credentials/syscallconn_appengine.go b/vendor/google.golang.org/grpc/internal/credentials/syscallconn_appengine.go deleted file mode 100644 index a6144cd661c2..000000000000 --- a/vendor/google.golang.org/grpc/internal/credentials/syscallconn_appengine.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build appengine - -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package credentials - -import ( - "net" -) - -// WrapSyscallConn returns newConn on appengine. -func WrapSyscallConn(rawConn, newConn net.Conn) net.Conn { - return newConn -} diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/target.go b/vendor/google.golang.org/grpc/internal/grpcutil/target.go deleted file mode 100644 index 8833021da02e..000000000000 --- a/vendor/google.golang.org/grpc/internal/grpcutil/target.go +++ /dev/null @@ -1,89 +0,0 @@ -/* - * - * Copyright 2020 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package grpcutil provides a bunch of utility functions to be used across the -// gRPC codebase. -package grpcutil - -import ( - "strings" - - "google.golang.org/grpc/resolver" -) - -// split2 returns the values from strings.SplitN(s, sep, 2). -// If sep is not found, it returns ("", "", false) instead. -func split2(s, sep string) (string, string, bool) { - spl := strings.SplitN(s, sep, 2) - if len(spl) < 2 { - return "", "", false - } - return spl[0], spl[1], true -} - -// ParseTarget splits target into a resolver.Target struct containing scheme, -// authority and endpoint. skipUnixColonParsing indicates that the parse should -// not parse "unix:[path]" cases. This should be true in cases where a custom -// dialer is present, to prevent a behavior change. -// -// If target is not a valid scheme://authority/endpoint as specified in -// https://github.com/grpc/grpc/blob/master/doc/naming.md, -// it returns {Endpoint: target}. -func ParseTarget(target string, skipUnixColonParsing bool) (ret resolver.Target) { - var ok bool - if strings.HasPrefix(target, "unix-abstract:") { - if strings.HasPrefix(target, "unix-abstract://") { - // Maybe, with Authority specified, try to parse it - var remain string - ret.Scheme, remain, _ = split2(target, "://") - ret.Authority, ret.Endpoint, ok = split2(remain, "/") - if !ok { - // No Authority, add the "//" back - ret.Endpoint = "//" + remain - } else { - // Found Authority, add the "/" back - ret.Endpoint = "/" + ret.Endpoint - } - } else { - // Without Authority specified, split target on ":" - ret.Scheme, ret.Endpoint, _ = split2(target, ":") - } - return ret - } - ret.Scheme, ret.Endpoint, ok = split2(target, "://") - if !ok { - if strings.HasPrefix(target, "unix:") && !skipUnixColonParsing { - // Handle the "unix:[local/path]" and "unix:[/absolute/path]" cases, - // because splitting on :// only handles the - // "unix://[/absolute/path]" case. Only handle if the dialer is nil, - // to avoid a behavior change with custom dialers. - return resolver.Target{Scheme: "unix", Endpoint: target[len("unix:"):]} - } - return resolver.Target{Endpoint: target} - } - ret.Authority, ret.Endpoint, ok = split2(ret.Endpoint, "/") - if !ok { - return resolver.Target{Endpoint: target} - } - if ret.Scheme == "unix" { - // Add the "/" back in the unix case, so the unix resolver receives the - // actual endpoint in the "unix://[/absolute/path]" case. - ret.Endpoint = "/" + ret.Endpoint - } - return ret -} diff --git a/vendor/google.golang.org/grpc/internal/resolver/dns/go113.go b/vendor/google.golang.org/grpc/internal/resolver/dns/go113.go deleted file mode 100644 index 8783a8cf8214..000000000000 --- a/vendor/google.golang.org/grpc/internal/resolver/dns/go113.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build go1.13 - -/* - * - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package dns - -import "net" - -func init() { - filterError = func(err error) error { - if dnsErr, ok := err.(*net.DNSError); ok && dnsErr.IsNotFound { - // The name does not exist; not an error. - return nil - } - return err - } -} From 4307d0ebe861066bf09b252bab640cb0729f9c75 Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 19 Jul 2022 16:52:40 +0800 Subject: [PATCH 11/12] remove test --- test/main.tf | 96 ---------------------------------------------------- 1 file changed, 96 deletions(-) delete mode 100644 test/main.tf diff --git a/test/main.tf b/test/main.tf deleted file mode 100644 index 4100073e2067..000000000000 --- a/test/main.tf +++ /dev/null @@ -1,96 +0,0 @@ -provider "azurerm" { - features {} -} - -resource "azurerm_resource_group" "test" { - name = "xiaxintestRG-WAlogs" - location = "east us" -} - -resource "azurerm_service_plan" "test" { - name = "xiaxintestASP-logging" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - os_type = "Linux" - sku_name = "B1" -} - -resource "azurerm_linux_web_app" "test" { - name = "LinuxWA-logging" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - service_plan_id = azurerm_service_plan.test.id - - site_config {} - - /* logs { - application_logs { - file_system_level = "Off" - azure_blob_storage { - level = "Information" - sas_url = "http://x.com/" - retention_in_days = 2 - } - } - - http_logs { - file_system { - retention_in_days = 4 - retention_in_mb = 25 - } - } - detailed_error_messages = true - } */ -} - -resource "azurerm_linux_web_app" "test1" { - name = "LinuxWA-loggingDefault" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - service_plan_id = azurerm_service_plan.test.id - site_config {} - logs { - application_logs { - file_system_level = "Information" - azure_blob_storage { - level = "Warning" - sas_url = "http://x.com/" - retention_in_days = 2 - } - } - - http_logs { - file_system { - retention_in_days = 7 - retention_in_mb = 25 - } - } - detailed_error_messages = true - } -} - -resource "azurerm_linux_web_app" "test2" { - name = "LinuxWA-logging1" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - service_plan_id = azurerm_service_plan.test.id - site_config {} - logs { -# application_logs { -# file_system_level = "Off" -# azure_blob_storage { -# level = "Warning" -# sas_url = "http://x.com/" -# retention_in_days = 2 -# } -# } - -# http_logs { -# file_system { -# retention_in_days = 7 -# retention_in_mb = 25 -# } -# } - detailed_error_messages = true - } -} From a2565076c8c1c0ac5368c25e305b0d4cc8482bc7 Mon Sep 17 00:00:00 2001 From: xiaxin18 Date: Tue, 19 Jul 2022 16:56:54 +0800 Subject: [PATCH 12/12] merging upstream